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

markdownDocument.ts

554 lines21.5 KB

1import type { Root, RootContent } from "mdast";
2import { unified, type Processor } from "unified";
3import remarkParse from "remark-parse";
4import remarkGfm from "remark-gfm";
5import { remarkKeepWindowsProsePaths } from "@t3tools/shared/markdownWindowsPaths";
6import { absoluteFilePathMatches, parseMarkdownFileLink } from "@t3tools/shared/markdownLinks";
7import { isWindowsAbsolutePath } from "@t3tools/shared/path";
8​
9const parser = unified().use(remarkParse).use(remarkGfm).use(remarkKeepWindowsProsePaths);
10export type MarkdownNode = Root | RootContent;
11​
12interface MarkdownEdit {
13 readonly start: number;
14 readonly end: number;
15 readonly content: string;
17​
18function applyMarkdownEdits(markdown: string, edits: MarkdownEdit[]): string {
19 if (edits.length === 0) return markdown;
20 const parts: string[] = [];
21 let offset = 0;
22 // AST traversal emits disjoint edits in source order.
23 for (const edit of edits) {
24 parts.push(markdown.slice(offset, edit.start), edit.content);
25 offset = edit.end;
26 }
27 parts.push(markdown.slice(offset));
28 return parts.join("");
30​
31function decodeCodePoint(codePoint: number, entity: string): string {
32 if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
33 return entity;
34 }
35 return String.fromCodePoint(codePoint);
37​
38export function decodeHtmlEntities(value: string): string {
39 return value.replace(
40 /&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
41 (entity, decimal: string | undefined, hexadecimal: string | undefined) => {
42 if (decimal) {
43 return decodeCodePoint(Number.parseInt(decimal, 10), entity);
44 }
45 if (hexadecimal) {
46 return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
47 }
48 switch (entity.toLowerCase()) {
49 case "&amp;":
50 return "&";
51 case "&apos;":
52 return "'";
53 case "&gt;":
54 return ">";
55 case "&lt;":
56 return "<";
57 case "&nbsp;":
58 return "\u00a0";
59 case "&quot;":
60 return '"';
61 default:
62 return entity;
63 }
64 },
65 );
67​
68const HTML_TAG = /<!--[\s\S]*?-->|<\/?[a-z](?:[^>"']|"[^"]*"|'[^']*')*>/gi;
69​
70function attribute(tag: string, name: string): string | null {
71 const attributes = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g;
72 for (const match of tag.matchAll(attributes)) {
73 if (match[1]?.toLowerCase() === name) {
74 return decodeHtmlEntities(match[2] ?? match[3] ?? match[4] ?? "");
75 }
76 }
77 return null;
79​
80function markdownDestination(url: string): string {
81 return `<${url.replace(/&/g, "\\&").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\|/g, "%7C").replace(/\n/g, "")}>`;
83​
84const ANCHOR_TAG = /^<\/?a[\s/>]/i;
85​
86/** Replacements for the anchor tags still ahead, and how many emitted links are open. */
87type AnchorState = { readonly pending: string[]; open: number };
88​
89// Code spans keep their text; an odd trailing backslash would escape the closing "]".
90function escapeLinkLabel(text: string): string {
91 return text
92 .replace(/(`+)[\s\S]*?\1|\\*[[\]]/g, (match) =>
93 match.startsWith("`") || match.length % 2 === 0
94 ? match
95 : `${match.slice(0, -1)}\\${match.slice(-1)}`,
96 )
97 .replace(/\\+$/, (slashes) => (slashes.length % 2 ? `${slashes}\\` : slashes));
99​
100// An unescaped "!" before the inserted "[" would turn the link into an image.
101function bangBefore(text: string, index: number): boolean {
102 if (text[index - 1] !== "!") return false;
103 let backslashes = 0;
104 while (text[index - 2 - backslashes] === "\\") backslashes += 1;
105 return backslashes % 2 === 0;
107​
108/**
109 * Pairs `<a>` tags in order. Only a closed anchor with an http(s) or mailto href becomes a
110 * Markdown link; any other anchor keeps its text unlinked.
111 */
112function anchorMarkdown(tags: readonly string[]): AnchorState {
113 const replacements = tags.map(() => "");
114 const open: Array<{ index: number; href: string | undefined }> = [];
115 tags.forEach((tag, index) => {
116 if (tag[1] !== "/") {
117 const href = attribute(tag, "href")?.trim();
118 open.push({ index, href: href && /^(?:https?|mailto):/i.test(href) ? href : undefined });
119 return;
120 }
121 const opening = open.pop();
122 if (!opening?.href) return;
123 replacements[opening.index] = "[";
124 replacements[index] = `](${markdownDestination(opening.href)})`;
125 });
126 return { pending: replacements, open: 0 };
128​
129export function markdownHtmlTags(content: string): RegExpExecArray[] {
130 // An HTML block such as <details> can also contain Markdown fences and code spans.
131 const codeRanges: Array<{ start: number; end: number }> = [];
132 const tags = [...content.matchAll(HTML_TAG)];
133 let tagIndex = 0;
134 const delimiters = [...content.matchAll(/`+|~{3,}/g)].filter((delimiter) => {
135 while (tags[tagIndex] && tags[tagIndex]!.index + tags[tagIndex]![0].length <= delimiter.index)
136 tagIndex += 1;
137 const tag = tags[tagIndex];
138 return !tag || delimiter.index < tag.index;
139 });
140 for (let index = 0; index < delimiters.length; index += 1) {
141 const opening = delimiters[index]!;
142 const lineStart = content.lastIndexOf("\n", opening.index - 1) + 1;
143 const fenced =
144 opening[0].length >= 3 && /^ {0,3}$/.test(content.slice(lineStart, opening.index));
145 if (opening[0][0] === "~" && !fenced) continue;
146 let closingIndex = -1;
147 for (let candidate = index + 1; candidate < delimiters.length; candidate += 1) {
148 const closing = delimiters[candidate]!;
149 if (!fenced && closing[0] === opening[0]) {
150 closingIndex = candidate;
151 break;
152 }
153 if (!fenced || closing[0][0] !== opening[0][0] || closing[0].length < opening[0].length)
154 continue;
155 const start = content.lastIndexOf("\n", closing.index - 1) + 1;
156 const nextLine = content.indexOf("\n", closing.index);
157 const end = nextLine === -1 ? content.length : nextLine;
158 if (
159 /^ {0,3}$/.test(content.slice(start, closing.index)) &&
160 /^\s*$/.test(content.slice(closing.index + closing[0].length, end))
161 ) {
162 closingIndex = candidate;
163 break;
164 }
165 }
166 if (closingIndex === -1) {
167 if (!fenced) continue;
168 // An unclosed fence runs to the end of the content, so no later opener matters.
169 codeRanges.push({ start: opening.index, end: content.length });
170 break;
171 }
172 const closing = delimiters[closingIndex]!;
173 codeRanges.push({ start: opening.index, end: closing.index + closing[0].length });
174 index = closingIndex;
175 }
176 return tags.filter(
177 (tag) => !codeRanges.some((range) => tag.index >= range.start && tag.index < range.end),
178 );
180​
181/**
182 * Called only for parsed HTML nodes, so Markdown code examples keep their literal tags.
183 * `anchors` is shared across sibling inline HTML nodes because each of those carries a single tag.
184 */
185export function markdownHtmlContent(
186 content: string,
187 options: { readonly anchors?: AnchorState; readonly inTableCell?: boolean } = {},
188): string {
189 const tags = markdownHtmlTags(content);
190 const anchors =
191 options.anchors ??
192 anchorMarkdown(tags.map((tag) => tag[0]).filter((tag) => ANCHOR_TAG.test(tag)));
193 let result = "";
194 let end = 0;
195 for (const match of tags) {
196 const text = content.slice(end, match.index);
197 result += anchors.open > 0 ? escapeLinkLabel(text) : text;
198 const replacement = htmlTagMarkdown(match[0], anchors, options);
199 if (replacement === "[" && bangBefore(result, result.length))
200 result = `${result.slice(0, -1)}\\!`;
201 result +=
202 anchors.open > 0 && /[\s[]/.test(result.at(-1) ?? "")
203 ? replacement.replace(/^ /, "")
204 : replacement;
205 end = match.index + match[0].length;
206 }
207 const text = content.slice(end);
208 return result + (anchors.open > 0 ? escapeLinkLabel(text) : text);
210​
211function htmlTagMarkdown(
212 tag: string,
213 anchors: AnchorState,
214 options: { readonly inTableCell?: boolean },
215): string {
216 if (tag.startsWith("<!--")) return "";
217 if (ANCHOR_TAG.test(tag)) {
218 const replacement = anchors.pending.shift() ?? "";
219 if (replacement === "[") anchors.open += 1;
220 else if (replacement) anchors.open -= 1;
221 return replacement;
222 }
223 if (/^<img\b/i.test(tag)) {
224 const src = attribute(tag, "src");
225 if (!src) return "";
226 const alt = (attribute(tag, "alt") ?? "").replace(/[\\[\]&]/g, "\\$&");
227 return `![${alt}](${markdownDestination(src)})`;
228 }
229 // A raw newline would end the table row; both parsers decode this reference to one inside the cell.
230 const cellBreak = "&#10;";
231 // A blank line inside an open link label would end the paragraph before its "]".
232 const blockBreak = anchors.open > 0 ? " " : options.inTableCell ? cellBreak : "\n\n";
233 if (/^<summary\b/i.test(tag)) return `${blockBreak}**`;
234 if (/^<\/summary\s*>/i.test(tag)) return `**${blockBreak}`;
235 if (/^<br\b/i.test(tag)) return options.inTableCell ? cellBreak : " \n";
236 if (/^<\/?(?:p|div|details)\b/i.test(tag)) return blockBreak;
237 return "";
239​
240export function markdownWithHtml(markdown: string): string {
241 if (!/<(?:!--|\/?[a-z])/i.test(markdown)) return markdown;
242 const edits: Array<{ start: number; end: number; content: string }> = [];
243 const visit = (node: MarkdownNode, inTableCell: boolean, inLink: boolean) => {
244 if (!("children" in node)) return;
245 inTableCell ||= node.type === "tableCell";
246 const children: readonly MarkdownNode[] = node.children;
247 // Inline HTML arrives one tag per node, so anchors pair across phrasing siblings.
248 const anchors =
249 node.type === "root" || node.type === "blockquote" || node.type === "listItem"
250 ? undefined
251 : anchorMarkdown(
252 children.flatMap((child) =>
253 child.type === "html"
254 ? markdownHtmlTags(child.value)
255 .map((tag) => tag[0])
256 .filter((tag) => ANCHOR_TAG.test(tag))
257 : [],
258 ),
259 );
260 for (const child of children) {
261 const start = child.position?.start.offset;
262 const end = child.position?.end.offset;
263 const linkLabel = inLink || (anchors?.open ?? 0) > 0;
264 if (child.type === "text") {
265 if (linkLabel && start !== undefined && end !== undefined) {
266 const content = escapeLinkLabel(markdown.slice(start, end));
267 if (content !== markdown.slice(start, end)) edits.push({ start, end, content });
268 }
269 continue;
270 }
271 if (child.type !== "html") {
272 visit(child, inTableCell, linkLabel);
273 continue;
274 }
275 const content = markdownHtmlContent(child.value, { anchors, inTableCell });
276 if (start === undefined || end === undefined) continue;
277 // Text before an outermost link is never edited, so this edit cannot overlap another.
278 if (content.startsWith("[") && !linkLabel && bangBefore(markdown, start))
279 edits.push({ start: start - 1, end: start, content: "\\!" });
280 edits.push({ start, end, content });
281 }
282 };
283 visit(parser.parse(markdown), false, false);
284 return applyMarkdownEdits(markdown, edits);
286​
287/** Reference definitions as authored, one line each, so a Windows destination keeps its backslashes. */
288export function markdownReferenceDefinitions(markdown: string): string[] {
289 if (!markdown.includes("]:")) return [];
290 // Flattened as the renderer does it: a raw HTML block hides the definitions inside it.
291 const flattened = markdownWithHtml(markdown);
292 const definitions: string[] = [];
293 const visit = (node: MarkdownNode, quotes: number) => {
294 if (node.type === "definition") {
295 // A wrapped definition drops its indent and the enclosing quotes' markers, not a literal ">".
296 const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "g");
297 definitions.push(
298 flattened.slice(node.position?.start.offset, node.position?.end.offset).replace(wrap, " "),
299 );
300 }
301 if (!("children" in node)) return;
302 for (const child of node.children) visit(child, quotes + (node.type === "blockquote" ? 1 : 0));
303 };
304 visit(parser.parse(flattened), 0);
305 return definitions;
307​
308/**
309 * A reply split into folds and cards renders each fragment as its own document, so each one
310 * carries the reply's definitions. The first definition of a label wins, so the fragment's own
311 * lead: the renderer then prefers them by its own label matching, with none reimplemented here.
312 */
313export function withReferenceDefinitions(
314 fragment: string,
315 replyDefinitions: ReadonlyArray<string>,
316): string {
317 if (replyDefinitions.length === 0 || !fragment.includes("[")) return fragment;
318 const definitions = new Set([...markdownReferenceDefinitions(fragment), ...replyDefinitions]);
319 return `${[...definitions].join("\n")}\n\n${fragment}`;
321​
322// Start only at the beginning of a backtick run to avoid retrying every suffix.
323const INLINE_CODE_SPAN = /(?<!`)`+([^`\r\n]+)`+/g;
324​
325export function markdownWithInlineFileLinks(markdown: string, fileLink: RegExp): string {
326 return transformNativeMarkdown(markdown, fileLink, false);
328​
329function transformNativeMarkdown(
330 markdown: string,
331 fileLink: RegExp | undefined,
332 tableBreaks: boolean,
333): string {
334 const breakTables = tableBreaks && mayHaveTableUnderText(markdown);
335 let linkFiles = false;
336 if (fileLink) {
337 for (const [, code] of markdown.matchAll(INLINE_CODE_SPAN)) {
338 if (fileLink.test(code!.trim())) {
339 linkFiles = true;
340 break;
341 }
342 }
343 }
344 const linkProseFiles = fileLink !== undefined && absoluteFilePathMatches(markdown).length > 0;
345 if (!linkFiles && !linkProseFiles && !breakTables) return markdown;
346 const edits: MarkdownEdit[] = [];
347 const fileEdits: MarkdownEdit[] = [];
348 let rewritesPipe = false;
349 const visit = (node: MarkdownNode) => {
350 if (linkFiles && node.type === "inlineCode") {
351 const start = node.position?.start.offset;
352 const end = node.position?.end.offset;
353 const escaped = node.value.replace(/[\\[\]&]/g, "\\$&");
354 if (
355 start !== undefined &&
356 end !== undefined &&
357 fileLink?.test(node.value) &&
358 parseMarkdownFileLink(node.value) !== null &&
359 !/[<>]/.test(node.value)
360 ) {
361 const edit = {
362 start,
363 end,
364 content: `[${escaped}](<${escaped}>)`,
365 };
366 edits.push(edit);
367 fileEdits.push(edit);
368 if (node.value.includes("|")) rewritesPipe = true;
369 }
370 } else if (
371 linkProseFiles &&
372 node.type === "text" &&
373 node.position?.start.offset !== undefined
374 ) {
375 const start = node.position.start.offset;
376 const raw = markdown.slice(start, node.position.end.offset);
377 for (const { index, path } of absoluteFilePathMatches(raw)) {
378 // Source offsets stay valid for paths whose own text needs no Markdown decoding.
379 if (raw !== node.value && /[\\&]/.test(path)) continue;
380 const escaped = path.replace(/[\\[\]&]/g, "\\$&");
381 const edit = {
382 start: start + index,
383 end: start + index + path.length,
384 content: `[${escaped}](<${escaped}>)`,
385 };
386 edits.push(edit);
387 fileEdits.push(edit);
388 }
389 } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
390 node.children.forEach((child, index) => {
391 const previous = node.children[index - 1];
392 const start = child.position?.start;
393 if (
394 breakTables &&
395 child.type === "table" &&
396 previous?.type === "paragraph" &&
397 start?.offset !== undefined &&
398 previous.position?.end.line === start.line - 1
399 ) {
400 let lineStart = start.offset;
401 while (lineStart > 0 && !/[\r\n]/.test(markdown[lineStart - 1]!)) lineStart -= 1;
402 // Replace only the container prefix, leaving cell edits disjoint from the table break.
403 const [, header = "", , ending = "\n", markers = ""] =
404 /^([ \t>]*)([^\r\n]*)(\r\n|\r|\n)([ \t>]*)/.exec(markdown.slice(lineStart)) ?? [];
405 edits.push({
406 start: lineStart,
407 end: lineStart + header.length,
408 content: `${markers.trimEnd()}${ending}${markers}`,
409 });
410 }
411 visit(child);
412 });
413 };
414 visit(parser.parse(markdown));
415 // Rewritten pipes can change table structure, so preserve the original pass ordering.
416 if (breakTables && rewritesPipe)
417 return markdownWithTableBreaks(applyMarkdownEdits(markdown, fileEdits));
418 return applyMarkdownEdits(markdown, edits);
420​
421// A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.
422function isTableDelimiterRow(line: string): boolean {
423 if (!line.includes("-")) return false;
424 const row = line.replace(/^[ \t>]+/, "").trim();
425 return row
426 .replace(/^\||\|$/g, "")
427 .split("|")
428 .every((cell) => /^:?-+:?$/.test(cell.trim()));
430​
431function mayHaveTableUnderText(markdown: string): boolean {
432 if (!markdown.includes("|")) return false;
433 const lines = markdown.split(/\r\n|\r|\n/);
434 for (let index = 2; index < lines.length; index += 1) {
435 if (isTableDelimiterRow(lines[index]!) && /[^\s>]/.test(lines[index - 2]!)) return true;
436 }
437 return false;
439​
440/** md4c starts tables only at paragraph starts; insert breaks to match GFM. */
441export function markdownWithTableBreaks(markdown: string): string {
442 return transformNativeMarkdown(markdown, undefined, true);
444​
445// `>` covers a destination continued on a blockquote line.
446const WINDOWS_DESTINATION = /\](?:\(|:)[\s>]*<?(?:[A-Za-z]:[\\/]|\\\\)/;
447​
448interface DestinationToken {
449 readonly start: { readonly offset: number };
450 readonly end: { readonly offset: number };
452​
453/**
454 * Markdown reads `C:\work\.t3` as `C:\work.t3`. Web keeps authored Windows destinations
455 * literally (see `remarkKeepWindowsPaths` in shared), so escape their backslashes to give
456 * both parsers here the same path. `\&` stays an escape, as `markdownWithHtml` emits it.
457 * Expects authored Markdown: already escaped output would be escaped twice.
458 */
459function markdownWithWindowsPathDestinations(markdown: string): string {
460 // Skips the extra parse for the common message that has no Windows destination.
461 if (!WINDOWS_DESTINATION.test(markdown)) return markdown;
462 const edits: MarkdownEdit[] = [];
463 function record(
464 this: { resume(): string; sliceSerialize(token: DestinationToken): string },
465 token: DestinationToken,
466 ) {
467 this.resume();
468 const authored = this.sliceSerialize(token);
469 if (!isWindowsAbsolutePath(authored) || !authored.includes("\\") || /[<>]/.test(authored))
470 return;
471 const start = token.start.offset;
472 const end = token.end.offset;
473 const escaped = authored.replace(/\\(?!&)/g, "\\\\");
474 // A bare destination ends at an unescaped `)`, so wrap it to keep `\)` inside.
475 const angled = markdown[start - 1] === "<";
476 edits.push({ start, end, content: angled ? escaped : `<${escaped}>` });
477 }
478 unified()
479 .use(remarkParse)
480 .use(remarkGfm)
481 .use(function (this: Processor) {
482 (this.data().fromMarkdownExtensions ??= []).push({
483 exit: { resourceDestinationString: record, definitionDestinationString: record },
484 });
485 })
486 .parse(markdown);
487 return applyMarkdownEdits(markdown, edits);
489​
490// HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first.
491export function markdownForNativeParsing(markdown: string): string {
492 return markdownWithWindowsPathDestinations(markdownWithHtml(markdown));
494​
495export function parseMarkdownDocument(markdown: string): Root {
496 return parser.parse(markdownForNativeParsing(markdown));
498​
499export function markdownForNativeRendering(markdown: string, fileLink: RegExp): string {
500 return transformNativeMarkdown(markdownForNativeParsing(markdown), fileLink, true);
502​
503/** Native media slots only cover standalone images; nested file embeds must become links. */
504export function markdownWithFileEmbeds(
505 markdown: string,
506 label: (href: string, standalone: boolean) => string | null,
507): { markdown: string; fileHrefs: ReadonlySet<string> } {
508 const fileHrefs = new Set<string>();
509 if (!markdown.includes("![")) return { markdown, fileHrefs };
510 const root = parser.parse(markdown);
511 const topLevelBlocks = new Set<MarkdownNode>(root.children);
512 const definitions = new Map<string, string>();
513 const collect = (node: MarkdownNode) => {
514 if (node.type === "definition") {
515 const identifier = node.identifier.toUpperCase();
516 if (!definitions.has(identifier)) definitions.set(identifier, node.url);
517 }
518 if ("children" in node) node.children.forEach(collect);
519 };
520 collect(root);
521 const edits: Array<{ start: number; end: number; content: string }> = [];
522 const visit = (node: MarkdownNode, standalone = false, insideLink = false) => {
523 if (node.type === "image" || node.type === "imageReference") {
524 const href =
525 node.type === "image" ? node.url : definitions.get(node.identifier.toUpperCase());
526 const name = href === undefined ? null : label(href, standalone);
527 const start = node.position?.start.offset;
528 const end = node.position?.end.offset;
529 if (href !== undefined && name !== null && start !== undefined && end !== undefined) {
530 const text = name.replace(/[\\[\]`*_~|&<>]/g, "\\$&");
531 const url = href.replace(/[\\&]/g, "\\$&").replace(/</g, "%3C").replace(/>/g, "%3E");
532 edits.push({ start, end, content: insideLink ? text : `[${text}](<${url}>)` });
533 fileHrefs.add(href);
534 }
535 }
536 if ("children" in node)
537 node.children.forEach((child) =>
538 visit(
539 child,
540 node.type === "paragraph" && node.children.length === 1 && topLevelBlocks.has(node),
541 insideLink || node.type === "link" || node.type === "linkReference",
542 ),
543 );
544 };
545 visit(root);
546 const parts: string[] = [];
547 let offset = 0;
548 for (const edit of edits) {
549 parts.push(markdown.slice(offset, edit.start), edit.content);
550 offset = edit.end;
551 }
552 parts.push(markdown.slice(offset));
553 return { markdown: parts.join(""), fileHrefs };