Open History to see the last commit
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;
15}
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("");
28}
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);
35}
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 "&":
49 return "&";
50 case "'":
51 return "'";
52 case ">":
53 return ">";
54 case "<":
55 return "<";
56 case " ":
57 return "\u00a0";
58 case """:
59 return '"';
60 default:
61 return entity;
62 }
63 },
64 );
65}
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;
77}
78
79function markdownDestination(url: string): string {
80 return `<${url.replace(/&/g, "\\&").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\|/g, "%7C").replace(/\n/g, "")}>`;
81}
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));
97}
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;
105}
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 };
126}
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 );
178}
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);
208}
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 `})`;
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 "";
236}
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 return applyMarkdownEdits(markdown, edits);
283}
284
285// Start only at the beginning of a backtick run to avoid retrying every suffix.
286const INLINE_CODE_SPAN = /(?<!`)`+([^`\r\n]+)`+/g;
287
288export function markdownWithInlineFileLinks(markdown: string, fileLink: RegExp): string {
289 return transformNativeMarkdown(markdown, fileLink, false);
290}
291
292function transformNativeMarkdown(
293 markdown: string,
294 fileLink: RegExp | undefined,
295 tableBreaks: boolean,
296): string {
297 const breakTables = tableBreaks && mayHaveTableUnderText(markdown);
298 let linkFiles = false;
299 if (fileLink) {
300 for (const [, code] of markdown.matchAll(INLINE_CODE_SPAN)) {
301 if (fileLink.test(code!.trim())) {
302 linkFiles = true;
303 break;
304 }
305 }
306 }
307 if (!linkFiles && !breakTables) return markdown;
308 const edits: MarkdownEdit[] = [];
309 const fileEdits: MarkdownEdit[] = [];
310 let rewritesPipe = false;
311 const visit = (node: MarkdownNode) => {
312 if (linkFiles && node.type === "inlineCode") {
313 const start = node.position?.start.offset;
314 const end = node.position?.end.offset;
315 const escaped = node.value.replace(/[\\[\]&]/g, "\\$&");
316 if (
317 start !== undefined &&
318 end !== undefined &&
319 fileLink?.test(node.value) &&
320 !/[<>]/.test(node.value)
321 ) {
322 const edit = {
323 start,
324 end,
325 content: `[${escaped}](<${escaped}>)`,
326 };
327 edits.push(edit);
328 fileEdits.push(edit);
329 if (node.value.includes("|")) rewritesPipe = true;
330 }
331 } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
332 node.children.forEach((child, index) => {
333 const previous = node.children[index - 1];
334 const start = child.position?.start;
335 if (
336 breakTables &&
337 child.type === "table" &&
338 previous?.type === "paragraph" &&
339 start?.offset !== undefined &&
340 previous.position?.end.line === start.line - 1
341 ) {
342 let lineStart = start.offset;
343 while (lineStart > 0 && !/[\r\n]/.test(markdown[lineStart - 1]!)) lineStart -= 1;
344 // Replace only the container prefix, leaving cell edits disjoint from the table break.
345 const [, header = "", , ending = "\n", markers = ""] =
346 /^([ \t>]*)([^\r\n]*)(\r\n|\r|\n)([ \t>]*)/.exec(markdown.slice(lineStart)) ?? [];
347 edits.push({
348 start: lineStart,
349 end: lineStart + header.length,
350 content: `${markers.trimEnd()}${ending}${markers}`,
351 });
352 }
353 visit(child);
354 });
355 };
356 visit(parser.parse(markdown));
357 // Rewritten pipes can change table structure, so preserve the original pass ordering.
358 if (breakTables && rewritesPipe)
359 return markdownWithTableBreaks(applyMarkdownEdits(markdown, fileEdits));
360 return applyMarkdownEdits(markdown, edits);
361}
362
363// A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.
364function isTableDelimiterRow(line: string): boolean {
365 if (!line.includes("-")) return false;
366 const row = line.replace(/^[ \t>]+/, "").trim();
367 return row
368 .replace(/^\||\|$/g, "")
369 .split("|")
370 .every((cell) => /^:?-+:?$/.test(cell.trim()));
371}
372
373function mayHaveTableUnderText(markdown: string): boolean {
374 if (!markdown.includes("|")) return false;
375 const lines = markdown.split(/\r\n|\r|\n/);
376 for (let index = 2; index < lines.length; index += 1) {
377 if (isTableDelimiterRow(lines[index]!) && /[^\s>]/.test(lines[index - 2]!)) return true;
378 }
379 return false;
380}
381
382/** md4c starts tables only at paragraph starts; insert breaks to match GFM. */
383export function markdownWithTableBreaks(markdown: string): string {
384 return transformNativeMarkdown(markdown, undefined, true);
385}
386
387// `>` covers a destination continued on a blockquote line.
388const WINDOWS_DESTINATION = /\](?:\(|:)[\s>]*<?(?:[A-Za-z]:[\\/]|\\\\)/;
389
390interface DestinationToken {
391 readonly start: { readonly offset: number };
392 readonly end: { readonly offset: number };
393}
394
395/**
396 * Markdown reads `C:\work\.t3` as `C:\work.t3`. Web keeps authored Windows destinations
397 * literally (see `remarkKeepWindowsPaths` in shared), so escape their backslashes to give
398 * both parsers here the same path. `\&` stays an escape, as `markdownWithHtml` emits it.
399 * Expects authored Markdown: already escaped output would be escaped twice.
400 */
401function markdownWithWindowsPathDestinations(markdown: string): string {
402 // Skips the extra parse for the common message that has no Windows destination.
403 if (!WINDOWS_DESTINATION.test(markdown)) return markdown;
404 const edits: MarkdownEdit[] = [];
405 function record(
406 this: { resume(): string; sliceSerialize(token: DestinationToken): string },
407 token: DestinationToken,
408 ) {
409 this.resume();
410 const authored = this.sliceSerialize(token);
411 if (!isWindowsAbsolutePath(authored) || !authored.includes("\\") || /[<>]/.test(authored))
412 return;
413 const start = token.start.offset;
414 const end = token.end.offset;
415 const escaped = authored.replace(/\\(?!&)/g, "\\\\");
416 // A bare destination ends at an unescaped `)`, so wrap it to keep `\)` inside.
417 const angled = markdown[start - 1] === "<";
418 edits.push({ start, end, content: angled ? escaped : `<${escaped}>` });
419 }
420 unified()
421 .use(remarkParse)
422 .use(remarkGfm)
423 .use(function (this: Processor) {
424 (this.data().fromMarkdownExtensions ??= []).push({
425 exit: { resourceDestinationString: record, definitionDestinationString: record },
426 });
427 })
428 .parse(markdown);
429 return applyMarkdownEdits(markdown, edits);
430}
431
432// HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first.
433export function markdownForNativeParsing(markdown: string): string {
434 return markdownWithWindowsPathDestinations(markdownWithHtml(markdown));
435}
436
437export function parseMarkdownDocument(markdown: string): Root {
438 return parser.parse(markdownForNativeParsing(markdown));
439}
440
441export function markdownForNativeRendering(markdown: string, fileLink: RegExp): string {
442 return transformNativeMarkdown(markdownForNativeParsing(markdown), fileLink, true);
443}
444
445/** Native media slots only cover standalone images; nested file embeds must become links. */
446export function markdownWithFileEmbeds(
447 markdown: string,
448 label: (href: string, standalone: boolean) => string | null,
449): { markdown: string; fileHrefs: ReadonlySet<string> } {
450 const fileHrefs = new Set<string>();
451 if (!markdown.includes("![")) return { markdown, fileHrefs };
452 const root = parser.parse(markdown);
453 const topLevelBlocks = new Set<MarkdownNode>(root.children);
454 const definitions = new Map<string, string>();
455 const collect = (node: MarkdownNode) => {
456 if (node.type === "definition") {
457 const identifier = node.identifier.toUpperCase();
458 if (!definitions.has(identifier)) definitions.set(identifier, node.url);
459 }
460 if ("children" in node) node.children.forEach(collect);
461 };
462 collect(root);
463 const edits: Array<{ start: number; end: number; content: string }> = [];
464 const visit = (node: MarkdownNode, standalone = false, insideLink = false) => {
465 if (node.type === "image" || node.type === "imageReference") {
466 const href =
467 node.type === "image" ? node.url : definitions.get(node.identifier.toUpperCase());
468 const name = href === undefined ? null : label(href, standalone);
469 const start = node.position?.start.offset;
470 const end = node.position?.end.offset;
471 if (href !== undefined && name !== null && start !== undefined && end !== undefined) {
472 const text = name.replace(/[\\[\]`*_~|&<>]/g, "\\$&");
473 const url = href.replace(/[\\&]/g, "\\$&").replace(/</g, "%3C").replace(/>/g, "%3E");
474 edits.push({ start, end, content: insideLink ? text : `[${text}](<${url}>)` });
475 fileHrefs.add(href);
476 }
477 }
478 if ("children" in node)
479 node.children.forEach((child) =>
480 visit(
481 child,
482 node.type === "paragraph" && node.children.length === 1 && topLevelBlocks.has(node),
483 insideLink || node.type === "link" || node.type === "linkReference",
484 ),
485 );
486 };
487 visit(root);
488 const parts: string[] = [];
489 let offset = 0;
490 for (const edit of edits) {
491 parts.push(markdown.slice(offset, edit.start), edit.content);
492 offset = edit.end;
493 }
494 parts.push(markdown.slice(offset));
495 return { markdown: parts.join(""), fileHrefs };
496}