Open History to see the last commit
1import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts";
2import type {
3 Heading,
4 Link,
5 Paragraph,
6 PhrasingContent,
7 Root,
8 RootContent,
9 TableCell,
10 Text,
11} from "mdast";
12import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts";
13import { type PluggableList, type Processor, type Transformer, unified } from "unified";
14import remarkParse from "remark-parse";
15import remarkRehype from "remark-rehype";
16import { find, html } from "property-information";
17import rehypeRaw from "rehype-raw";
18import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
19import remarkBreaks from "remark-breaks";
20import remarkGfm from "remark-gfm";
21import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
22import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
23import { remarkKeepOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
24import {
25 CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
26 remarkCodexDirectives,
27} from "./codexMarkdownDirectives.ts";
28import {
29 absoluteFilePathMatches,
30 isWindowsDrivePathHref,
31 normalizeMarkdownLinkDestination,
32} from "./markdownLinks.ts";
33import { isWindowsAbsolutePath } from "./path.ts";
34import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
35
36export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
37
38type MarkdownImageHastNode = {
39 type?: string;
40 value?: string;
41 tagName?: string;
42 properties?: Record<string, unknown>;
43 children?: MarkdownImageHastNode[];
44};
45
46function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
47 return (node.children ?? []).filter(
48 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
49 );
50}
51
52const STANDALONE_IMAGE_BLOCKS = new Set([
53 "p",
54 "div",
55 "li",
56 "td",
57 "th",
58 "figure",
59 "center",
60 "blockquote",
61]);
62
63function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
64 const children = meaningfulHastChildren(node);
65 if (children.length !== 1) return undefined;
66 const only = children[0];
67 if (only?.type !== "element") return undefined;
68 if (only.tagName === "img") return only;
69 return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"
70 ? soleImageDescendant(only)
71 : undefined;
72}
73
74function markStandaloneImages(node: MarkdownImageHastNode) {
75 if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {
76 const image = soleImageDescendant(node);
77 if (image) image.properties = { ...image.properties, dataStandalone: true };
78 }
79 node.children?.forEach((child) => {
80 if (child.type === "element") markStandaloneImages(child);
81 });
82}
83
84// Whole tags, attributes, and comments, so closing-anchor text inside them never counts as a tag.
85const RAW_HTML_TAG_PATTERN = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
86
87function rehypePreserveBareAnchorPlaceholders() {
88 return (tree: MarkdownImageHastNode) => {
89 const anchors: Array<MarkdownImageHastNode | null> = [];
90 let rawTextTag: string | undefined;
91 const visit = (node: MarkdownImageHastNode) => {
92 if (node.type === "raw" && typeof node.value === "string") {
93 const tags = new RegExp(RAW_HTML_TAG_PATTERN);
94 let offset = 0;
95 while (rawTextTag !== "plaintext") {
96 // Raw text ends at its closing tag even inside comment-looking text.
97 const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;
98 matcher.lastIndex = offset;
99 const match = matcher.exec(node.value);
100 if (!match) break;
101 const [tag] = match;
102 offset = matcher.lastIndex;
103 if (rawTextTag) {
104 rawTextTag = undefined;
105 continue;
106 }
107 if (tag.startsWith("<!--")) continue;
108 const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();
109 const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();
110 if (
111 opening &&
112 /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)
113 ) {
114 rawTextTag = opening;
115 } else if (opening === "a") {
116 anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);
117 } else if (closing === "a") {
118 anchors.pop();
119 }
120 }
121 }
122 node.children?.forEach(visit);
123 };
124
125 visit(tree);
126 for (const anchor of anchors) {
127 if (anchor) anchor.type = "text";
128 }
129 };
130}
131
132const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i;
133
134/**
135 * The renderer resolves an `<img>`'s `src` (workspace files, host media) but never a `<source>`'s
136 * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves
137 * onto the `<img>` for the renderer to pick by theme; every source is then dropped.
138 */
139function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) {
140 if (!picture.children) return;
141 const image = picture.children.find((child) => child.tagName === "img");
142 for (const source of picture.children) {
143 if (source.tagName !== "source" || !image) continue;
144 const media = source.properties?.media;
145 const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined;
146 const srcSet = source.properties?.srcSet;
147 const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet;
148 // A candidate's URL runs to the first space (a descriptor such as `2x` may follow).
149 const url =
150 typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : "";
151 const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc";
152 // As in a browser, the first source that matches a scheme is the one shown.
153 if (scheme && url && image.properties?.[key] === undefined) {
154 // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path.
155 const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url;
156 image.properties = { ...image.properties, [key]: value };
157 }
158 }
159 picture.children = picture.children.filter((child) => child.tagName !== "source");
160}
161
162function rehypePreserveImageSourceMeta() {
163 return (tree: MarkdownImageHastNode) => {
164 const visit = (node: MarkdownImageHastNode) => {
165 const src = node.properties?.src;
166 const title = node.properties?.title;
167 if (node.type === "element" && node.tagName === "picture") {
168 moveColorSchemeSourcesToImage(node);
169 }
170 if (node.type === "element" && node.tagName === "img") {
171 node.properties = {
172 ...node.properties,
173 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
174 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
175 };
176 }
177 node.children?.forEach(visit);
178 };
179
180 visit(tree);
181 markStandaloneImages(tree);
182 };
183}
184
185const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"];
186
187// The sanitizer compares schemes case-sensitively, so lowercase accepted editor links first.
188function rehypeNormalizeLocalEditorLinks() {
189 return (tree: MarkdownImageHastNode) => {
190 const visit = (node: MarkdownImageHastNode) => {
191 const href = node.properties?.href;
192 if (node.type === "element" && node.tagName === "a" && typeof href === "string") {
193 try {
194 const url = new URL(href);
195 if (isLocalEditorFileUrl(url)) node.properties = { ...node.properties, href: url.href };
196 } catch {
197 // Not an absolute URL; the sanitizer decides.
198 }
199 }
200 node.children?.forEach(visit);
201 };
202
203 visit(tree);
204 };
205}
206
207const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
208 ...defaultSchema,
209 attributes: {
210 ...defaultSchema.attributes,
211 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
212 // Fence languages plus the two math classes the web chat's math plugin emits.
213 code: [
214 ["className", /^language-./, "math-inline", "math-display"],
215 "dataCodeMeta",
216 "dataInlineCode",
217 ],
218 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
219 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
220 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
221 img: [
222 ...(defaultSchema.attributes?.img ?? []),
223 "dataDarkSrc",
224 "dataLightSrc",
225 "dataLocalSrc",
226 "dataMarkdownTitle",
227 "dataStandalone",
228 ],
229 },
230 protocols: {
231 ...defaultSchema.protocols,
232 href: [
233 ...(defaultSchema.protocols?.href ?? []),
234 "file",
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 Parameters<typeof rehypeSanitize>[0];
246
247export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
248 remarkGfm,
249 remarkEndAutolinksAtScriptPunctuation,
250 remarkKeepAutolinkSuffixes,
251 remarkLinkAbsoluteFilePaths,
252 remarkKeepWindowsPaths,
253 remarkGithubAlerts,
254 remarkKeepOrderedListNumbers,
255 remarkNormalizeListItemIndentation,
256 remarkCodexDirectives,
257 remarkBreakAroundImageLines,
258 remarkPreserveCodeMeta,
259 remarkNormalizeLinksAndTagInlineCode,
260];
261
262export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
263 remarkGfm,
264 remarkEndAutolinksAtScriptPunctuation,
265 remarkKeepAutolinkSuffixes,
266 remarkLinkAbsoluteFilePaths,
267 remarkKeepWindowsPaths,
268 remarkGithubAlerts,
269 remarkKeepOrderedListNumbers,
270 remarkNormalizeListItemIndentation,
271 remarkCodexDirectives,
272 remarkBreakAroundImageLines,
273 remarkBreaks,
274 remarkPreserveCodeMeta,
275 remarkNormalizeLinksAndTagInlineCode,
276];
277
278// Users type paths like ~/a and (~/b, which GFM's single-tilde strikethrough hides as <del>.
279// Appended after the base list, this reconfigures its remark-gfm entry; ~~double~~ still strikes.
280export const CHAT_USER_MARKDOWN_REMARK_PLUGINS: PluggableList = [
281 [remarkGfm, { singleTilde: false }],
282];
283
284// Start tags an HTML parser closes an open `<p>` for.
285const CLOSES_PARAGRAPH = new Set(
286 "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split(
287 " ",
288 ),
289);
290const HEADING = /^h[1-6]$/;
291
292interface HtmlScope {
293 readonly anchor: boolean;
294 readonly paragraph: boolean;
295 readonly heading: boolean;
296}
297
298/**
299 * Whether the tree needs the HTML parser: raw HTML, or nesting it repairs (a footnote call in a
300 * link label nests `<a>`). Otherwise it only rewrites properties as hast-util-to-parse5 does and
301 * drops `data`, both repeated here, and moves blank text that renders the same.
302 */
303function needsHtmlParser(node: MarkdownImageHastNode, scope: HtmlScope): boolean {
304 if (node.type === "raw") return true;
305 let inner = scope;
306 if (node.type === "element" && node.tagName) {
307 const { tagName } = node;
308 const heading = HEADING.test(tagName);
309 if (
310 (tagName === "a" && scope.anchor) ||
311 (scope.paragraph && CLOSES_PARAGRAPH.has(tagName)) ||
312 (heading && scope.heading)
313 ) {
314 return true;
315 }
316 inner = {
317 anchor: scope.anchor || tagName === "a",
318 paragraph: scope.paragraph || tagName === "p",
319 heading: scope.heading || heading,
320 };
321 const properties = node.properties ?? {};
322 for (const key of Object.keys(properties)) {
323 const value = properties[key];
324 const info = find(html, key);
325 if (
326 value === false ||
327 value === null ||
328 value === undefined ||
329 Number.isNaN(value) ||
330 (!value && info.boolean)
331 ) {
332 delete properties[key];
333 } else if (value === true && !info.boolean && !info.overloadedBoolean) {
334 properties[key] = "";
335 }
336 }
337 delete (node as { data?: unknown }).data;
338 }
339 return (node.children ?? []).some((child) => needsHtmlParser(child, inner));
340}
341
342const TOP_SCOPE: HtmlScope = { anchor: false, paragraph: false, heading: false };
343
344/** rehype-raw reparses the whole tree through an HTML parser, which most trees can skip. */
345function rehypeRawWhenPresent(this: Processor) {
346 const transform = rehypeRaw.call(this) as unknown as (
347 tree: MarkdownImageHastNode,
348 file: unknown,
349 ) => unknown;
350 return (tree: MarkdownImageHastNode, file: unknown) =>
351 needsHtmlParser(tree, TOP_SCOPE) ? transform(tree, file) : undefined;
352}
353
354export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
355 rehypePreserveBareAnchorPlaceholders,
356 rehypeRawWhenPresent,
357 rehypePreserveImageSourceMeta,
358 rehypeNormalizeLocalEditorLinks,
359 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
360];
361
362const isImageNode = (node: PhrasingContent | undefined): boolean =>
363 node?.type === "image" ||
364 node?.type === "imageReference" ||
365 ((node?.type === "link" || node?.type === "linkReference") &&
366 node.children.length === 1 &&
367 isImageNode(node.children[0]));
368const endsLine = (node: PhrasingContent | undefined) =>
369 node === undefined ||
370 node.type === "break" ||
371 (node.type === "text" && /\n[ \t]*$/.test(node.value));
372const startsLine = (node: PhrasingContent | undefined) =>
373 node === undefined ||
374 node.type === "break" ||
375 (node.type === "text" && /^[ \t]*\n/.test(node.value));
376
377function breakLinesAroundImages(paragraph: Paragraph) {
378 const children = paragraph.children;
379 if (!children.some(isImageNode)) return;
380 const ownsLine = (index: number) =>
381 isImageNode(children[index]) &&
382 endsLine(children[index - 1]) &&
383 startsLine(children[index + 1]);
384 paragraph.children = children.flatMap((child, index): PhrasingContent[] => {
385 if (child.type !== "text") return [child];
386 const afterImage = ownsLine(index - 1);
387 const beforeImage = ownsLine(index + 1);
388 if (!afterImage && !beforeImage) return [child];
389 const parts: PhrasingContent[] = [];
390 let value = child.value;
391 if (afterImage) {
392 value = value.replace(/^[ \t]*\n/, "");
393 parts.push({ type: "break" });
394 }
395 const breakAfter = beforeImage && /\n[ \t]*$/.test(value);
396 if (breakAfter) value = value.replace(/[ \t]*\n[ \t]*$/, "");
397 if (value) parts.push({ type: "text", value });
398 if (breakAfter) parts.push({ type: "break" });
399 return parts;
400 });
401}
402
403/**
404 * Agents label screenshots with a line like `**Palette**` right above the image. CommonMark
405 * joins those lines into one paragraph, which puts the image inline beside its label. An
406 * image alone on its source line keeps that line; prose and inline badges still wrap.
407 */
408function remarkBreakAroundImageLines() {
409 return (tree: Root) => {
410 const visit = (node: Root | RootContent) => {
411 if (node.type === "paragraph") breakLinesAroundImages(node);
412 else if ("children" in node) node.children.forEach(visit);
413 };
414 visit(tree);
415 };
416}
417
418type MarkdownAstNode = {
419 type?: string;
420 meta?: unknown;
421 url?: string;
422 data?: {
423 hProperties?: Record<string, unknown>;
424 };
425 children?: MarkdownAstNode[];
426};
427
428function remarkKeepAutolinkSuffixes(): Transformer<Root> {
429 return (tree, file) => {
430 const source = String(file);
431 const visit = (node: Root | RootContent) => {
432 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
433 for (let index = 0; index < node.children.length; index++) {
434 const child = node.children[index];
435 const next = node.children[index + 1];
436 if (child?.type === "link" && /^https?:\/\//i.test(child.url) && next?.type === "text") {
437 const suffix = /^[_~]+/.exec(next.value)?.[0];
438 if (!suffix) continue;
439 const label = child.children.length === 1 ? child.children[0] : undefined;
440 if (label?.type !== "text") continue;
441 if (label.value !== child.url && `http://${label.value}` !== child.url) continue;
442 const start = child.position?.start.offset;
443 const end = child.position?.end.offset;
444 const bare =
445 !child.position ||
446 (start !== undefined &&
447 end !== undefined &&
448 source.slice(start, end) === label.value &&
449 source.slice(end, end + suffix.length) === suffix);
450 if (bare) {
451 child.url += suffix;
452 label.value += suffix;
453 next.value = next.value.slice(suffix.length);
454 if (child.position && end !== undefined) {
455 const boundary = {
456 ...child.position.end,
457 column: child.position.end.column + suffix.length,
458 offset: end + suffix.length,
459 };
460 child.position.end = boundary;
461 if (label.position) label.position.end = boundary;
462 if (next.position) next.position.start = boundary;
463 }
464 if (!next.value) node.children.splice(index + 1, 1);
465 }
466 }
467 if (child) visit(child);
468 }
469 };
470 visit(tree);
471 };
472}
473
474// Punctuation and symbols from CJK Symbols and Punctuation and from Halfwidth and Fullwidth Forms,
475// plus the Arabic-script comma, semicolon, question mark, and full stop.
476const SCRIPT_PUNCTUATION = /(?=[ -〿-،؛؟۔])[\p{P}\p{S}]/u;
477
478/**
479 * GFM runs a bare URL on until whitespace, so Chinese, Japanese, and Arabic punctuation joins it,
480 * along with the rest of the sentence and any `**` that should have closed around it. A URL that is
481 * ASCII up to such a mark ends there. Unicode earlier in the URL means the mark may belong to it, so it stays.
482 */
483function scriptPunctuationIndex(link: Link): number {
484 const label = link.children.length === 1 ? link.children[0] : undefined;
485 if (label?.type !== "text" || !/^https?:\/\//i.test(link.url)) return -1;
486 if (link.url !== label.value && link.url !== `http://${label.value}`) return -1;
487 const index = label.value.search(/[^!-~]/u);
488 return index > 0 && SCRIPT_PUNCTUATION.test(label.value.charAt(index)) ? index : -1;
489}
490
491/** GFM's text pass links bare URLs without positions; its tokenizer's links span their URL. */
492function isBareLink(link: Link, source: string): boolean {
493 const start = link.position?.start.offset;
494 const end = link.position?.end.offset;
495 const label = link.children[0];
496 return (
497 !link.position ||
498 (start !== undefined &&
499 end !== undefined &&
500 label?.type === "text" &&
501 source.slice(start, end) === label.value)
502 );
503}
504
505/** Source offsets of the marks that tokenized bare URLs run past. */
506function scriptPunctuationOffsets(node: RootContent, source: string): number[] {
507 if (node.type === "link") {
508 const index = scriptPunctuationIndex(node);
509 const start = node.position?.start.offset;
510 return index > 0 && start !== undefined && isBareLink(node, source) ? [start + index] : [];
511 }
512 return "children" in node && node.type !== "linkReference"
513 ? (node.children as RootContent[]).flatMap((child) => scriptPunctuationOffsets(child, source))
514 : [];
515}
516
517const hasReference = (node: RootContent): boolean =>
518 node.type === "linkReference" ||
519 node.type === "imageReference" ||
520 node.type === "footnoteReference" ||
521 ("children" in node && (node.children as RootContent[]).some(hasReference));
522
523/** How many of the ascending numbers are below `value`. */
524function countBelow(sorted: readonly number[], value: number): number {
525 let low = 0;
526 let high = sorted.length;
527 while (low < high) {
528 const middle = (low + high) >> 1;
529 if (sorted[middle]! < value) low = middle + 1;
530 else high = middle;
531 }
532 return low;
533}
534
535/**
536 * Parses the block's text again with a tab before each mark. The tab ends the URL as a space would,
537 * so emphasis around the URL closes and later URLs and code get their own nodes. The tabs are then
538 * dropped and positions mapped back to the source. Returns false and leaves the block alone when its
539 * text would parse differently on its own, as a quote's continuation lines do.
540 */
541function reparseAtScriptPunctuation(
542 processor: Processor,
543 block: Paragraph | Heading | TableCell,
544 source: string,
545 offsets: number[],
546): boolean {
547 // A task item's paragraph starts at its checkbox; its first child starts after it.
548 const from = block.children[0]?.position?.start;
549 const to = block.children.at(-1)?.position?.end;
550 if (from?.offset === undefined || to?.offset === undefined || hasReference(block)) return false;
551 const base = from.offset;
552 const text = source.slice(base, to.offset);
553 // A tab is the marker, a quote's `>` on a later line would read as a new quote, a list's
554 // indentation would join a code span, and only a table unescapes `\|` in code.
555 if (
556 text.includes("\t") ||
557 /[\r\n][ ]*>/.test(text) ||
558 (/[\r\n] /.test(text) && text.includes("`")) ||
559 (block.type === "tableCell" && text.includes("\\|"))
560 ) {
561 return false;
562 }
563 const marks = offsets.map((offset) => offset - base);
564 // Each pass finds the next URL in a run with no spaces, like `http://a,http://b,http://c`.
565 for (let attempt = 0; attempt < 16; attempt++) {
566 marks.sort((a, b) => a - b);
567 const tabs = marks.map((mark, index) => mark + index);
568 const unmarked = (offset: number) => offset - countBelow(tabs, offset);
569 const marked = [0, ...marks]
570 .map((start, index) => text.slice(start, marks[index] ?? text.length))
571 .join("\t");
572 const [paragraph, ...rest] = (processor.parse(marked) as Root).children;
573 if (paragraph?.type !== "paragraph" || rest.length > 0) return false;
574 const more = scriptPunctuationOffsets(paragraph, marked);
575 if (more.length > 0) {
576 marks.push(...more.map(unmarked));
577 continue;
578 }
579
580 let tabCount = 0;
581 const moved = new Set<object>();
582 const restore = (node: RootContent): boolean => {
583 for (const point of node.position ? [node.position.start, node.position.end] : []) {
584 const offset = point.offset;
585 if (offset === undefined || moved.has(point)) continue;
586 moved.add(point);
587 const tabsOnLine = countBelow(tabs, offset) - countBelow(tabs, offset - point.column + 1);
588 point.column = (point.line === 1 ? from.column - 1 : 0) + point.column - tabsOnLine;
589 point.line += from.line - 1;
590 point.offset = base + unmarked(offset);
591 }
592 if (node.type === "text") {
593 tabCount += node.value.split("\t").length - 1;
594 node.value = node.value.replaceAll("\t", "");
595 } else if (
596 ("value" in node && node.value.includes("\t")) ||
597 ("url" in node && node.url.includes("\t"))
598 ) {
599 return false;
600 }
601 if (!("children" in node)) return true;
602 const children = node.children as RootContent[];
603 if (!children.every(restore)) return false;
604 node.children = children.filter(
605 (child) => child.type !== "text" || child.value !== "",
606 ) as typeof node.children;
607 return true;
608 };
609 if (!restore(paragraph) || tabCount !== tabs.length) return false;
610 block.children = paragraph.children;
611 return true;
612 }
613 return false;
614}
615
616/** Ends the bare URLs a reparse could not, and those GFM's text pass linked after emphasis. */
617function splitAtScriptPunctuation(node: RootContent, source: string) {
618 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
619 const children = node.children as RootContent[];
620 for (let index = 0; index < children.length; index++) {
621 const child = children[index]!;
622 if (child.type !== "link") {
623 splitAtScriptPunctuation(child, source);
624 continue;
625 }
626 const at = isBareLink(child, source) ? scriptPunctuationIndex(child) : -1;
627 const label = child.children[0];
628 if (at < 0 || label?.type !== "text") continue;
629 // GFM drops this punctuation from the end of a URL; remarkKeepAutolinkSuffixes restores `_` and `~`.
630 const length = label.value.slice(0, at).replace(/[!"'*,.:;?_~]+$/, "").length;
631 const tail: Text = { type: "text", value: label.value.slice(length) };
632 const start = child.position?.start;
633 if (child.position && start?.offset !== undefined) {
634 const end = {
635 line: start.line,
636 column: start.column + length,
637 offset: start.offset + length,
638 };
639 tail.position = { start: end, end: child.position.end };
640 child.position = { start, end };
641 label.position = { start, end };
642 }
643 child.url = child.url.slice(0, child.url.length - label.value.length + length);
644 label.value = label.value.slice(0, length);
645 children.splice(index + 1, 0, tail);
646 index++;
647 }
648}
649
650function remarkEndAutolinksAtScriptPunctuation(this: Processor): Transformer<Root> {
651 return (tree, file) => {
652 const source = String(file);
653 if (!SCRIPT_PUNCTUATION.test(source)) return;
654 const visit = (node: RootContent) => {
655 if (node.type === "paragraph" || node.type === "heading" || node.type === "tableCell") {
656 const offsets = scriptPunctuationOffsets(node, source);
657 if (offsets.length > 0) reparseAtScriptPunctuation(this, node, source, offsets);
658 splitAtScriptPunctuation(node, source);
659 } else if ("children" in node) {
660 (node.children as RootContent[]).forEach(visit);
661 }
662 };
663 tree.children.forEach(visit);
664 };
665}
666
667function remarkLinkAbsoluteFilePaths(): Transformer<Root> {
668 return (tree) => {
669 // Raw `<a>` tags are sibling html nodes, so text inside one is not under a link node.
670 let rawAnchorDepth = 0;
671 const visit = (node: Root | RootContent) => {
672 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
673 node.children = node.children.flatMap((child): typeof node.children => {
674 if (child.type === "html") {
675 for (const [tag] of child.value.matchAll(RAW_HTML_TAG_PATTERN)) {
676 if (/^<a[\s/>]/i.test(tag)) rawAnchorDepth += 1;
677 else if (/^<\/a[\s>]/i.test(tag)) rawAnchorDepth = Math.max(0, rawAnchorDepth - 1);
678 }
679 }
680 if (child.type !== "text" || rawAnchorDepth > 0) {
681 visit(child);
682 return [child];
683 }
684 const parts: PhrasingContent[] = [];
685 let offset = 0;
686 for (const { index, path } of absoluteFilePathMatches(child.value)) {
687 if (index > offset) parts.push({ type: "text", value: child.value.slice(offset, index) });
688 parts.push({ type: "link", url: path, children: [{ type: "text", value: path }] });
689 offset = index + path.length;
690 }
691 if (offset === 0) return [child];
692 if (offset < child.value.length)
693 parts.push({ type: "text", value: child.value.slice(offset) });
694 return parts;
695 });
696 };
697 visit(tree);
698 };
699}
700
701function remarkPreserveCodeMeta() {
702 return (tree: MarkdownAstNode) => {
703 const visit = (node: MarkdownAstNode) => {
704 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
705 node.data = {
706 ...node.data,
707 hProperties: {
708 ...node.data?.hProperties,
709 dataCodeMeta: node.meta.trim(),
710 },
711 };
712 }
713 node.children?.forEach(visit);
714 };
715
716 visit(tree);
717 };
718}
719
720function remarkNormalizeLinksAndTagInlineCode() {
721 return (tree: MarkdownAstNode) => {
722 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
723 if (
724 (node.type === "link" || node.type === "definition") &&
725 typeof node.url === "string" &&
726 /^[A-Za-z]:[\\/]/.test(node.url)
727 ) {
728 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
729 }
730 if (node.type === "inlineCode" && !insideLink) {
731 node.data = {
732 ...node.data,
733 hProperties: {
734 ...node.data?.hProperties,
735 dataInlineCode: "",
736 },
737 };
738 }
739 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
740 node.children?.forEach((child) => visit(child, childInsideLink));
741 };
742
743 visit(tree, false);
744 };
745}
746
747export function shouldPreserveAssistantLineBreaks(text: string): boolean {
748 return /^★ Insight(?:\s|─)/mu.test(text);
749}
750
751export function remarkAssistantInsights(this: Processor) {
752 return (tree: Root, file: { value: unknown }) => {
753 const source = String(file.value);
754 if (!source.includes("★ Insight")) return;
755 const protectedRanges: { start: number; end: number; code: boolean }[] = [];
756 const inspect = (node: RootContent | PhrasingContent) => {
757 const start = node.position?.start.offset;
758 const end = node.position?.end.offset;
759 if (start !== undefined && end !== undefined) {
760 const code =
761 node.type === "code" ||
762 node.type === "html" ||
763 (node.type === "inlineCode" && node.position?.start.line !== node.position?.end.line);
764 if (code || node.type === "list" || node.type === "blockquote")
765 protectedRanges.push({ start, end, code });
766 }
767 if ("children" in node) node.children.forEach(inspect);
768 };
769 tree.children.forEach(inspect);
770 const starts = new Set<number>();
771 const offsets: { original: number; rewritten: number; prefix: number }[] = [];
772 let indent: string | undefined;
773 let original = 0;
774 let rewritten = 0;
775 const lines = source.split(/(?<=\n)|(?<=\r)(?!\n)/u).map((line, index) => {
776 const value = line.replace(/[\r\n]+$/u, "");
777 const blocked = protectedRanges.some(
778 (range) =>
779 original >= range.start && original < range.end && (indent === undefined || range.code),
780 );
781 const opening =
782 indent === undefined && !blocked
783 ? /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u.exec(value)
784 : null;
785 const closing =
786 indent !== undefined && !blocked ? /^( {0,3})(`?)─{3,}\2[ \t]*$/u.exec(value) : null;
787 let prefix = 0;
788 let output = line;
789 if (opening) {
790 indent = opening[1] ?? "";
791 starts.add(index + 1);
792 output = ">" + line.slice(value.length);
793 } else if (closing && closing[1] === indent) {
794 indent = undefined;
795 output = line.slice(value.length);
796 } else if (indent !== undefined) {
797 prefix = 2;
798 output = "> " + line;
799 }
800 offsets.push({ original, rewritten, prefix });
801 original += line.length;
802 rewritten += output.length;
803 return output;
804 });
805 if (starts.size === 0) return;
806 const parsed = this.parse(lines.join("")) as Root;
807 const restorePosition = (node: RootContent | PhrasingContent) => {
808 if (node.position) {
809 for (const point of [node.position.start, node.position.end]) {
810 const offset = offsets[point.line - 1];
811 if (!offset) continue;
812 point.column = Math.max(1, point.column - offset.prefix);
813 if (point.offset !== undefined)
814 point.offset += offset.original - offset.rewritten - offset.prefix;
815 }
816 }
817 if ("children" in node) node.children.forEach(restorePosition);
818 };
819 for (const node of parsed.children) {
820 if (node.type === "blockquote" && starts.has(node.position?.start.line ?? 0)) {
821 node.data = { ...node.data, hProperties: { dataAlert: "insight" } };
822 }
823 restorePosition(node);
824 }
825 tree.children = parsed.children;
826 };
827}
828
829const imageSourceProcessor = unified()
830 .use(remarkParse)
831 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
832 .use(remarkRehype, { allowDangerousHtml: true })
833 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
834
835interface ImageSourceNode {
836 readonly type: string;
837 readonly tagName?: string;
838 readonly properties?: {
839 readonly src?: unknown;
840 readonly dataLocalSrc?: unknown;
841 readonly dataDarkSrc?: unknown;
842 readonly dataLightSrc?: unknown;
843 };
844 readonly children?: ReadonlyArray<ImageSourceNode>;
845}
846
847/**
848 * The sources of the images chat markdown shows, read as ChatMarkdown's `img` renderer reads
849 * them. Code, comments, and plain links show no image, so they add none.
850 */
851export function chatMarkdownImageSources(markdown: string): Array<string> {
852 const sources: Array<string> = [];
853 const visit = (node: ImageSourceNode) => {
854 if (node.type === "element" && node.tagName === "img") {
855 const { src, dataLocalSrc, dataDarkSrc, dataLightSrc } = node.properties ?? {};
856 // The sanitizer drops a Windows drive path from `src`; the renderer reads it from here.
857 if (typeof dataLocalSrc === "string") {
858 sources.push(normalizeMarkdownLinkDestination(dataLocalSrc).replaceAll("\\", "/"));
859 } else if (typeof src === "string") {
860 sources.push(normalizeMarkdownLinkDestination(src));
861 }
862 // A `<picture>` shows one of these instead, by the viewer's theme.
863 for (const variant of [dataDarkSrc, dataLightSrc]) {
864 if (typeof variant === "string") sources.push(normalizeMarkdownLinkDestination(variant));
865 }
866 }
867 node.children?.forEach(visit);
868 };
869 visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode);
870 return sources;
871}
872
873const linkDestinationProcessor = unified().use(remarkParse).use(remarkKeepWindowsPaths);
874
875// An angle destination cannot hold an unescaped `<` or `>`, or end on a lone backslash.
876const ANGLE_DESTINATION_CONTENT = /^(?:[^\\<>]|\\.)*$/;
877
878/** Reads a destination from `extractMarkdownLinkHrefs` as the renderer's parser does. */
879export function decodeMarkdownLinkEscapes(href: string): string {
880 // Only the parser knows character references, so destinations that may have one go through it.
881 if (href.includes("&")) {
882 // The extractor drops angle brackets, and only that form keeps an unmatched `)` in the path.
883 const destination = ANGLE_DESTINATION_CONTENT.test(href) ? `<${href}>` : href;
884 const paragraph = linkDestinationProcessor.parse(`[](${destination})`).children[0];
885 const link = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined;
886 if (link?.type === "link") return link.url;
887 }
888 return isWindowsAbsolutePath(href) ? href : href.replace(/\\([!-/:-@[-`{-~])/g, "$1");
889}