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

markdownPipeline.ts

753 lines28.6 KB

1import type {
2 Heading,
3 Link,
4 Paragraph,
5 PhrasingContent,
6 Root,
7 RootContent,
8 TableCell,
9 Text,
10} from "mdast";
11import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts";
12import { type PluggableList, type Processor, type Transformer, unified } from "unified";
13import remarkParse from "remark-parse";
14import remarkRehype from "remark-rehype";
15import { find, html } from "property-information";
16import rehypeRaw from "rehype-raw";
17import rehypeSanitize from "rehype-sanitize";
18import remarkBreaks from "remark-breaks";
19import remarkGfm from "remark-gfm";
20import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
21import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
22import { remarkKeepOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
23import {
24 remarkEnableLeadingWhitespace,
25 remarkKeepLeadingWhitespace,
26} from "./markdownLeadingWhitespace.ts";
27import { remarkCodexDirectives } from "./codexMarkdownDirectives.ts";
28import { absoluteFilePathMatches } from "./markdownLinks.ts";
29import { isWindowsAbsolutePath } from "./path.ts";
30import {
31 CHAT_MARKDOWN_SANITIZE_SCHEMA,
32 chatMarkdownImageSource,
33 rehypeNormalizeLocalEditorLinks,
34 rehypePreserveImageSourceMeta,
35 type ChatMarkdownImageProperties,
36} from "./markdownHast.ts";
37​
38export { chatMarkdownImageSource, type ChatMarkdownImageProperties };
39​
40export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
41​
42type MarkdownImageHastNode = {
43 type?: string;
44 value?: string;
45 tagName?: string;
46 properties?: Record<string, unknown>;
47 children?: MarkdownImageHastNode[];
48};
49​
50// Whole tags, attributes, and comments, so closing-anchor text inside them never counts as a tag.
51const RAW_HTML_TAG_PATTERN = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
52​
53function rehypePreserveBareAnchorPlaceholders() {
54 return (tree: MarkdownImageHastNode) => {
55 const anchors: Array<MarkdownImageHastNode | null> = [];
56 let rawTextTag: string | undefined;
57 const visit = (node: MarkdownImageHastNode) => {
58 if (node.type === "raw" && typeof node.value === "string") {
59 const tags = new RegExp(RAW_HTML_TAG_PATTERN);
60 let offset = 0;
61 while (rawTextTag !== "plaintext") {
62 // Raw text ends at its closing tag even inside comment-looking text.
63 const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;
64 matcher.lastIndex = offset;
65 const match = matcher.exec(node.value);
66 if (!match) break;
67 const [tag] = match;
68 offset = matcher.lastIndex;
69 if (rawTextTag) {
70 rawTextTag = undefined;
71 continue;
72 }
73 if (tag.startsWith("<!--")) continue;
74 const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();
75 const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();
76 if (
77 opening &&
78 /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)
79 ) {
80 rawTextTag = opening;
81 } else if (opening === "a") {
82 anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);
83 } else if (closing === "a") {
84 anchors.pop();
85 }
86 }
87 }
88 node.children?.forEach(visit);
89 };
90​
91 visit(tree);
92 for (const anchor of anchors) {
93 if (anchor) anchor.type = "text";
94 }
95 };
97​
98export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
99 remarkGfm,
100 remarkEndAutolinksAtScriptPunctuation,
101 remarkKeepAutolinkSuffixes,
102 remarkLinkAbsoluteFilePaths,
103 remarkKeepWindowsPaths,
104 remarkGithubAlerts,
105 remarkKeepOrderedListNumbers,
106 remarkNormalizeListItemIndentation,
107 remarkCodexDirectives,
108 remarkBreakAroundImageLines,
109 remarkPreserveCodeMeta,
110 remarkNormalizeLinksAndTagInlineCode,
111];
112​
113// Leading whitespace is kept only where each line renders as a line.
114export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
115 remarkGfm,
116 remarkEndAutolinksAtScriptPunctuation,
117 remarkKeepAutolinkSuffixes,
118 remarkKeepLeadingWhitespace,
119 remarkLinkAbsoluteFilePaths,
120 remarkKeepWindowsPaths,
121 remarkGithubAlerts,
122 remarkKeepOrderedListNumbers,
123 remarkNormalizeListItemIndentation,
124 remarkCodexDirectives,
125 remarkBreakAroundImageLines,
126 remarkBreaks,
127 remarkPreserveCodeMeta,
128 remarkNormalizeLinksAndTagInlineCode,
129];
130​
131// Users type paths like ~/a and (~/b, which GFM's single-tilde strikethrough hides as <del>.
132// Appended after the base list, this reconfigures its remark-gfm entry; ~~double~~ still strikes.
133// Users also indent lines with spaces, which CommonMark drops from a paragraph.
134export const CHAT_USER_MARKDOWN_REMARK_PLUGINS: PluggableList = [
135 [remarkGfm, { singleTilde: false }],
136 remarkEnableLeadingWhitespace,
137];
138​
139// Start tags an HTML parser closes an open `<p>` for.
140const CLOSES_PARAGRAPH = new Set(
141 "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(
142 " ",
143 ),
144);
145const HEADING = /^h[1-6]$/;
146​
147interface HtmlScope {
148 readonly anchor: boolean;
149 readonly paragraph: boolean;
150 readonly heading: boolean;
152​
153/**
154 * Whether the tree needs the HTML parser: raw HTML, or nesting it repairs (a footnote call in a
155 * link label nests `<a>`). Otherwise it only rewrites properties as hast-util-to-parse5 does and
156 * drops `data`, both repeated here, and moves blank text that renders the same.
157 */
158function needsHtmlParser(node: MarkdownImageHastNode, scope: HtmlScope): boolean {
159 if (node.type === "raw") return true;
160 let inner = scope;
161 if (node.type === "element" && node.tagName) {
162 const { tagName } = node;
163 const heading = HEADING.test(tagName);
164 if (
165 (tagName === "a" && scope.anchor) ||
166 (scope.paragraph && CLOSES_PARAGRAPH.has(tagName)) ||
167 (heading && scope.heading)
168 ) {
169 return true;
170 }
171 inner = {
172 anchor: scope.anchor || tagName === "a",
173 paragraph: scope.paragraph || tagName === "p",
174 heading: scope.heading || heading,
175 };
176 const properties = node.properties ?? {};
177 for (const key of Object.keys(properties)) {
178 const value = properties[key];
179 const info = find(html, key);
180 if (
181 value === false ||
182 value === null ||
183 value === undefined ||
184 Number.isNaN(value) ||
185 (!value && info.boolean)
186 ) {
187 delete properties[key];
188 } else if (value === true && !info.boolean && !info.overloadedBoolean) {
189 properties[key] = "";
190 }
191 }
192 delete (node as { data?: unknown }).data;
193 }
194 return (node.children ?? []).some((child) => needsHtmlParser(child, inner));
196​
197const TOP_SCOPE: HtmlScope = { anchor: false, paragraph: false, heading: false };
198​
199/** rehype-raw reparses the whole tree through an HTML parser, which most trees can skip. */
200function rehypeRawWhenPresent(this: Processor) {
201 const transform = rehypeRaw.call(this) as unknown as (
202 tree: MarkdownImageHastNode,
203 file: unknown,
204 ) => unknown;
205 return (tree: MarkdownImageHastNode, file: unknown) =>
206 needsHtmlParser(tree, TOP_SCOPE) ? transform(tree, file) : undefined;
208​
209export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
210 rehypePreserveBareAnchorPlaceholders,
211 rehypeRawWhenPresent,
212 rehypePreserveImageSourceMeta,
213 rehypeNormalizeLocalEditorLinks,
214 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
215];
216​
217const isImageNode = (node: PhrasingContent | undefined): boolean =>
218 node?.type === "image" ||
219 node?.type === "imageReference" ||
220 ((node?.type === "link" || node?.type === "linkReference") &&
221 node.children.length === 1 &&
222 isImageNode(node.children[0]));
223const endsLine = (node: PhrasingContent | undefined) =>
224 node === undefined ||
225 node.type === "break" ||
226 (node.type === "text" && /\n[ \t]*$/.test(node.value));
227const startsLine = (node: PhrasingContent | undefined) =>
228 node === undefined ||
229 node.type === "break" ||
230 (node.type === "text" && /^[ \t]*\n/.test(node.value));
231​
232// A caption line ending in a screenshot reads as a figure, so the trailing images get a line.
233function trailingImagesStart(children: readonly PhrasingContent[]): number | undefined {
234 let start: number | undefined;
235 for (let index = children.length - 1; index >= 0; index--) {
236 const child = children[index]!;
237 if (isImageNode(child)) start = index;
238 else if (child.type !== "break" && !(child.type === "text" && !child.value.trim()))
239 return start;
240 }
241 return undefined;
243​
244function breakLinesAroundImages(paragraph: Paragraph) {
245 const children = paragraph.children;
246 if (!children.some(isImageNode)) return;
247 const ownsLine = (index: number) =>
248 isImageNode(children[index]) &&
249 endsLine(children[index - 1]) &&
250 startsLine(children[index + 1]);
251 const trailingStart = trailingImagesStart(children);
252 paragraph.children = children.flatMap((child, index): PhrasingContent[] => {
253 // Kept indentation after a line ending already sits on a line of its own.
254 const beforeTrailing =
255 index + 1 === trailingStart &&
256 !(child.type === "text" && !child.value.trim() && endsLine(children[index - 1]));
257 if (child.type !== "text") {
258 return beforeTrailing && child.type !== "break" ? [child, { type: "break" }] : [child];
259 }
260 const afterImage = ownsLine(index - 1);
261 const beforeImage = ownsLine(index + 1);
262 if (!afterImage && !beforeImage && !beforeTrailing) return [child];
263 const parts: PhrasingContent[] = [];
264 let value = child.value;
265 if (afterImage) {
266 value = value.replace(/^[ \t]*\n/, "");
267 parts.push({ type: "break" });
268 }
269 const breakAfter = (beforeImage && /\n[ \t]*$/.test(value)) || beforeTrailing;
270 if (breakAfter) value = value.replace(/[ \t]*(?:\n[ \t]*)?$/, "");
271 if (value) parts.push({ type: "text", value });
272 if (breakAfter) parts.push({ type: "break" });
273 return parts;
274 });
276​
277/**
278 * Agents label screenshots with a line like `**Palette**` right above the image. CommonMark
279 * joins those lines into one paragraph, which puts the image inline beside its label. An
280 * image alone on its source line keeps that line; prose and inline badges still wrap.
281 */
282function remarkBreakAroundImageLines() {
283 return (tree: Root) => {
284 const visit = (node: Root | RootContent) => {
285 if (node.type === "paragraph") breakLinesAroundImages(node);
286 else if ("children" in node) node.children.forEach(visit);
287 };
288 visit(tree);
289 };
291​
292type MarkdownAstNode = {
293 type?: string;
294 meta?: unknown;
295 url?: string;
296 data?: {
297 hProperties?: Record<string, unknown>;
298 };
299 children?: MarkdownAstNode[];
300};
301​
302function remarkKeepAutolinkSuffixes(): Transformer<Root> {
303 return (tree, file) => {
304 const source = String(file);
305 const visit = (node: Root | RootContent) => {
306 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
307 for (let index = 0; index < node.children.length; index++) {
308 const child = node.children[index];
309 const next = node.children[index + 1];
310 if (child?.type === "link" && /^https?:\/\//i.test(child.url) && next?.type === "text") {
311 const suffix = /^[_~]+/.exec(next.value)?.[0];
312 if (!suffix) continue;
313 const label = child.children.length === 1 ? child.children[0] : undefined;
314 if (label?.type !== "text") continue;
315 if (label.value !== child.url && `http://${label.value}` !== child.url) continue;
316 const start = child.position?.start.offset;
317 const end = child.position?.end.offset;
318 const bare =
319 !child.position ||
320 (start !== undefined &&
321 end !== undefined &&
322 source.slice(start, end) === label.value &&
323 source.slice(end, end + suffix.length) === suffix);
324 if (bare) {
325 child.url += suffix;
326 label.value += suffix;
327 next.value = next.value.slice(suffix.length);
328 if (child.position && end !== undefined) {
329 const boundary = {
330 ...child.position.end,
331 column: child.position.end.column + suffix.length,
332 offset: end + suffix.length,
333 };
334 child.position.end = boundary;
335 if (label.position) label.position.end = boundary;
336 if (next.position) next.position.start = boundary;
337 }
338 if (!next.value) node.children.splice(index + 1, 1);
339 }
340 }
341 if (child) visit(child);
342 }
343 };
344 visit(tree);
345 };
347​
348// Punctuation and symbols from CJK Symbols and Punctuation and from Halfwidth and Fullwidth Forms,
349// plus the Arabic-script comma, semicolon, question mark, and full stop.
350const SCRIPT_PUNCTUATION = /(?=[ -〿＀-￯،؛؟۔])[\p{P}\p{S}]/u;
351​
352/**
353 * GFM runs a bare URL on until whitespace, so Chinese, Japanese, and Arabic punctuation joins it,
354 * along with the rest of the sentence and any `**` that should have closed around it. A URL that is
355 * ASCII up to such a mark ends there. Unicode earlier in the URL means the mark may belong to it, so it stays.
356 */
357function scriptPunctuationIndex(link: Link): number {
358 const label = link.children.length === 1 ? link.children[0] : undefined;
359 if (label?.type !== "text" || !/^https?:\/\//i.test(link.url)) return -1;
360 if (link.url !== label.value && link.url !== `http://${label.value}`) return -1;
361 const index = label.value.search(/[^!-~]/u);
362 return index > 0 && SCRIPT_PUNCTUATION.test(label.value.charAt(index)) ? index : -1;
364​
365/** GFM's text pass links bare URLs without positions; its tokenizer's links span their URL. */
366function isBareLink(link: Link, source: string): boolean {
367 const start = link.position?.start.offset;
368 const end = link.position?.end.offset;
369 const label = link.children[0];
370 return (
371 !link.position ||
372 (start !== undefined &&
373 end !== undefined &&
374 label?.type === "text" &&
375 source.slice(start, end) === label.value)
376 );
378​
379/** Source offsets of the marks that tokenized bare URLs run past. */
380function scriptPunctuationOffsets(node: RootContent, source: string): number[] {
381 if (node.type === "link") {
382 const index = scriptPunctuationIndex(node);
383 const start = node.position?.start.offset;
384 return index > 0 && start !== undefined && isBareLink(node, source) ? [start + index] : [];
385 }
386 return "children" in node && node.type !== "linkReference"
387 ? (node.children as RootContent[]).flatMap((child) => scriptPunctuationOffsets(child, source))
388 : [];
390​
391const hasReference = (node: RootContent): boolean =>
392 node.type === "linkReference" ||
393 node.type === "imageReference" ||
394 node.type === "footnoteReference" ||
395 ("children" in node && (node.children as RootContent[]).some(hasReference));
396​
397/** How many of the ascending numbers are below `value`. */
398function countBelow(sorted: readonly number[], value: number): number {
399 let low = 0;
400 let high = sorted.length;
401 while (low < high) {
402 const middle = (low + high) >> 1;
403 if (sorted[middle]! < value) low = middle + 1;
404 else high = middle;
405 }
406 return low;
408​
409/**
410 * Parses the block's text again with a tab before each mark. The tab ends the URL as a space would,
411 * so emphasis around the URL closes and later URLs and code get their own nodes. The tabs are then
412 * dropped and positions mapped back to the source. Returns false and leaves the block alone when its
413 * text would parse differently on its own, as a quote's continuation lines do.
414 */
415function reparseAtScriptPunctuation(
416 processor: Processor,
417 block: Paragraph | Heading | TableCell,
418 source: string,
419 offsets: number[],
420): boolean {
421 // A task item's paragraph starts at its checkbox; its first child starts after it.
422 const from = block.children[0]?.position?.start;
423 const to = block.children.at(-1)?.position?.end;
424 if (from?.offset === undefined || to?.offset === undefined || hasReference(block)) return false;
425 const base = from.offset;
426 const text = source.slice(base, to.offset);
427 // A tab is the marker, a quote's `>` on a later line would read as a new quote, a list's
428 // indentation would join a code span, and only a table unescapes `\|` in code.
429 if (
430 text.includes("\t") ||
431 /[\r\n][ ]*>/.test(text) ||
432 (/[\r\n] /.test(text) && text.includes("`")) ||
433 (block.type === "tableCell" && text.includes("\\|"))
434 ) {
435 return false;
436 }
437 const marks = offsets.map((offset) => offset - base);
438 // Each pass finds the next URL in a run with no spaces, like `http://a,http://b,http://c`.
439 for (let attempt = 0; attempt < 16; attempt++) {
440 marks.sort((a, b) => a - b);
441 const tabs = marks.map((mark, index) => mark + index);
442 const unmarked = (offset: number) => offset - countBelow(tabs, offset);
443 const marked = [0, ...marks]
444 .map((start, index) => text.slice(start, marks[index] ?? text.length))
445 .join("\t");
446 const [paragraph, ...rest] = (processor.parse(marked) as Root).children;
447 if (paragraph?.type !== "paragraph" || rest.length > 0) return false;
448 const more = scriptPunctuationOffsets(paragraph, marked);
449 if (more.length > 0) {
450 marks.push(...more.map(unmarked));
451 continue;
452 }
453​
454 let tabCount = 0;
455 const moved = new Set<object>();
456 const restore = (node: RootContent): boolean => {
457 for (const point of node.position ? [node.position.start, node.position.end] : []) {
458 const offset = point.offset;
459 if (offset === undefined || moved.has(point)) continue;
460 moved.add(point);
461 const tabsOnLine = countBelow(tabs, offset) - countBelow(tabs, offset - point.column + 1);
462 point.column = (point.line === 1 ? from.column - 1 : 0) + point.column - tabsOnLine;
463 point.line += from.line - 1;
464 point.offset = base + unmarked(offset);
465 }
466 if (node.type === "text") {
467 tabCount += node.value.split("\t").length - 1;
468 node.value = node.value.replaceAll("\t", "");
469 } else if (
470 ("value" in node && node.value.includes("\t")) ||
471 ("url" in node && node.url.includes("\t"))
472 ) {
473 return false;
474 }
475 if (!("children" in node)) return true;
476 const children = node.children as RootContent[];
477 if (!children.every(restore)) return false;
478 node.children = children.filter(
479 (child) => child.type !== "text" || child.value !== "",
480 ) as typeof node.children;
481 return true;
482 };
483 if (!restore(paragraph) || tabCount !== tabs.length) return false;
484 block.children = paragraph.children;
485 return true;
486 }
487 return false;
489​
490/** Ends the bare URLs a reparse could not, and those GFM's text pass linked after emphasis. */
491function splitAtScriptPunctuation(node: RootContent, source: string) {
492 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
493 const children = node.children as RootContent[];
494 for (let index = 0; index < children.length; index++) {
495 const child = children[index]!;
496 if (child.type !== "link") {
497 splitAtScriptPunctuation(child, source);
498 continue;
499 }
500 const at = isBareLink(child, source) ? scriptPunctuationIndex(child) : -1;
501 const label = child.children[0];
502 if (at < 0 || label?.type !== "text") continue;
503 // GFM drops this punctuation from the end of a URL; remarkKeepAutolinkSuffixes restores `_` and `~`.
504 const length = label.value.slice(0, at).replace(/[!"'*,.:;?_~]+$/, "").length;
505 const tail: Text = { type: "text", value: label.value.slice(length) };
506 const start = child.position?.start;
507 if (child.position && start?.offset !== undefined) {
508 const end = {
509 line: start.line,
510 column: start.column + length,
511 offset: start.offset + length,
512 };
513 tail.position = { start: end, end: child.position.end };
514 child.position = { start, end };
515 label.position = { start, end };
516 }
517 child.url = child.url.slice(0, child.url.length - label.value.length + length);
518 label.value = label.value.slice(0, length);
519 children.splice(index + 1, 0, tail);
520 index++;
521 }
523​
524function remarkEndAutolinksAtScriptPunctuation(this: Processor): Transformer<Root> {
525 return (tree, file) => {
526 const source = String(file);
527 if (!SCRIPT_PUNCTUATION.test(source)) return;
528 const visit = (node: RootContent) => {
529 if (node.type === "paragraph" || node.type === "heading" || node.type === "tableCell") {
530 const offsets = scriptPunctuationOffsets(node, source);
531 if (offsets.length > 0) reparseAtScriptPunctuation(this, node, source, offsets);
532 splitAtScriptPunctuation(node, source);
533 } else if ("children" in node) {
534 (node.children as RootContent[]).forEach(visit);
535 }
536 };
537 tree.children.forEach(visit);
538 };
540​
541function remarkLinkAbsoluteFilePaths(): Transformer<Root> {
542 return (tree) => {
543 // Raw `<a>` tags are sibling html nodes, so text inside one is not under a link node.
544 let rawAnchorDepth = 0;
545 const visit = (node: Root | RootContent) => {
546 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
547 node.children = node.children.flatMap((child): typeof node.children => {
548 if (child.type === "html") {
549 for (const [tag] of child.value.matchAll(RAW_HTML_TAG_PATTERN)) {
550 if (/^<a[\s/>]/i.test(tag)) rawAnchorDepth += 1;
551 else if (/^<\/a[\s>]/i.test(tag)) rawAnchorDepth = Math.max(0, rawAnchorDepth - 1);
552 }
553 }
554 if (child.type !== "text" || rawAnchorDepth > 0) {
555 visit(child);
556 return [child];
557 }
558 const parts: PhrasingContent[] = [];
559 let offset = 0;
560 for (const { index, path } of absoluteFilePathMatches(child.value)) {
561 if (index > offset) parts.push({ type: "text", value: child.value.slice(offset, index) });
562 parts.push({ type: "link", url: path, children: [{ type: "text", value: path }] });
563 offset = index + path.length;
564 }
565 if (offset === 0) return [child];
566 if (offset < child.value.length)
567 parts.push({ type: "text", value: child.value.slice(offset) });
568 return parts;
569 });
570 };
571 visit(tree);
572 };
574​
575function remarkPreserveCodeMeta() {
576 return (tree: MarkdownAstNode) => {
577 const visit = (node: MarkdownAstNode) => {
578 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
579 node.data = {
580 ...node.data,
581 hProperties: {
582 ...node.data?.hProperties,
583 dataCodeMeta: node.meta.trim(),
584 },
585 };
586 }
587 node.children?.forEach(visit);
588 };
589​
590 visit(tree);
591 };
593​
594function remarkNormalizeLinksAndTagInlineCode() {
595 return (tree: MarkdownAstNode) => {
596 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
597 if (
598 (node.type === "link" || node.type === "definition") &&
599 typeof node.url === "string" &&
600 /^[A-Za-z]:[\\/]/.test(node.url)
601 ) {
602 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
603 }
604 if (node.type === "inlineCode" && !insideLink) {
605 node.data = {
606 ...node.data,
607 hProperties: {
608 ...node.data?.hProperties,
609 dataInlineCode: "",
610 },
611 };
612 }
613 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
614 node.children?.forEach((child) => visit(child, childInsideLink));
615 };
616​
617 visit(tree, false);
618 };
620​
621export function remarkAssistantInsights(this: Processor) {
622 return (tree: Root, file: { value: unknown }) => {
623 const source = String(file.value);
624 if (!source.includes("★ Insight")) return;
625 const protectedRanges: { start: number; end: number; code: boolean }[] = [];
626 const inspect = (node: RootContent | PhrasingContent) => {
627 const start = node.position?.start.offset;
628 const end = node.position?.end.offset;
629 if (start !== undefined && end !== undefined) {
630 const code =
631 node.type === "code" ||
632 node.type === "html" ||
633 (node.type === "inlineCode" && node.position?.start.line !== node.position?.end.line);
634 if (code || node.type === "list" || node.type === "blockquote")
635 protectedRanges.push({ start, end, code });
636 }
637 if ("children" in node) node.children.forEach(inspect);
638 };
639 tree.children.forEach(inspect);
640 const starts = new Set<number>();
641 const offsets: { original: number; rewritten: number; prefix: number }[] = [];
642 let indent: string | undefined;
643 let original = 0;
644 let rewritten = 0;
645 const lines = source.split(/(?<=\n)|(?<=\r)(?!\n)/u).map((line, index) => {
646 const value = line.replace(/[\r\n]+$/u, "");
647 const blocked = protectedRanges.some(
648 (range) =>
649 original >= range.start && original < range.end && (indent === undefined || range.code),
650 );
651 const opening =
652 indent === undefined && !blocked
653 ? /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u.exec(value)
654 : null;
655 const closing =
656 indent !== undefined && !blocked ? /^( {0,3})(`?)─{3,}\2[ \t]*$/u.exec(value) : null;
657 let prefix = 0;
658 let output = line;
659 if (opening) {
660 indent = opening[1] ?? "";
661 starts.add(index + 1);
662 output = ">" + line.slice(value.length);
663 } else if (closing && closing[1] === indent) {
664 indent = undefined;
665 output = line.slice(value.length);
666 } else if (indent !== undefined) {
667 prefix = 2;
668 output = "> " + line;
669 }
670 offsets.push({ original, rewritten, prefix });
671 original += line.length;
672 rewritten += output.length;
673 return output;
674 });
675 if (starts.size === 0) return;
676 const parsed = this.parse(lines.join("")) as Root;
677 const restorePosition = (node: RootContent | PhrasingContent) => {
678 if (node.position) {
679 for (const point of [node.position.start, node.position.end]) {
680 const offset = offsets[point.line - 1];
681 if (!offset) continue;
682 point.column = Math.max(1, point.column - offset.prefix);
683 if (point.offset !== undefined)
684 point.offset += offset.original - offset.rewritten - offset.prefix;
685 }
686 }
687 if ("children" in node) node.children.forEach(restorePosition);
688 };
689 for (const node of parsed.children) {
690 if (node.type === "blockquote" && starts.has(node.position?.start.line ?? 0)) {
691 node.data = { ...node.data, hProperties: { dataAlert: "insight" } };
692 }
693 restorePosition(node);
694 }
695 tree.children = parsed.children;
696 };
698​
699const imageSourceProcessor = unified()
700 .use(remarkParse)
701 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
702 .use(remarkRehype, { allowDangerousHtml: true })
703 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
704​
705interface ImageSourceNode {
706 readonly type: string;
707 readonly tagName?: string;
708 readonly properties?: ChatMarkdownImageProperties;
709 readonly children?: ReadonlyArray<ImageSourceNode>;
711​
712/**
713 * Collect the fallback and every theme variant so images are available to all viewers.
714 */
715export function chatMarkdownImageSources(markdown: string): Array<string> {
716 const sources: Array<string> = [];
717 const visit = (node: ImageSourceNode) => {
718 if (node.type === "element" && node.tagName === "img") {
719 const properties = node.properties;
720 const fallback = chatMarkdownImageSource(properties);
721 if (fallback) sources.push(fallback.classifiedSrc);
722 for (const [theme, variant] of [
723 ["dark", properties?.dataDarkSrc],
724 ["light", properties?.dataLightSrc],
725 ] as const) {
726 if (typeof variant !== "string") continue;
727 const source = chatMarkdownImageSource(properties, theme);
728 if (source) sources.push(source.classifiedSrc);
729 }
730 }
731 node.children?.forEach(visit);
732 };
733 visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode);
734 return sources;
736​
737const linkDestinationProcessor = unified().use(remarkParse).use(remarkKeepWindowsPaths);
738​
739// An angle destination cannot hold an unescaped `<` or `>`, or end on a lone backslash.
740const ANGLE_DESTINATION_CONTENT = /^(?:[^\\<>]|\\.)*$/;
741​
742/** Reads a destination from `extractMarkdownLinkHrefs` as the renderer's parser does. */
743export function decodeMarkdownLinkEscapes(href: string): string {
744 // Only the parser knows character references, so destinations that may have one go through it.
745 if (href.includes("&")) {
746 // The extractor drops angle brackets, and only that form keeps an unmatched `)` in the path.
747 const destination = ANGLE_DESTINATION_CONTENT.test(href) ? `<${href}>` : href;
748 const paragraph = linkDestinationProcessor.parse(`[](${destination})`).children[0];
749 const link = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined;
750 if (link?.type === "link") return link.url;
751 }
752 return isWindowsAbsolutePath(href) ? href : href.replace(/\\([!-/:-@[-`{-~])/g, "$1");