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

markdownDocument.ts

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