Open History to see the last commit
1import { githubEmojiAliases } from "@t3tools/client-runtime/pull-request-markdown";
2import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients";
3import remarkGfm from "remark-gfm";
4import remarkParse from "remark-parse";
5import { unified } from "unified";
6
7import { splitLeadingBom } from "../../lib/markdownDocument";
8
9type MarkdownNode = {
10 readonly type: string;
11 readonly position?:
12 | {
13 readonly start: { readonly offset?: number | undefined };
14 readonly end: { readonly offset?: number | undefined };
15 }
16 | undefined;
17 readonly children?: readonly MarkdownNode[] | undefined;
18};
19
20const parser = unified().use(remarkParse).use(remarkGfm);
21const HTML_BLOCK_PARENTS = new Set(["root", "blockquote", "listItem", "footnoteDefinition"]);
22const UNLINKED_TYPES = new Set([
23 "link",
24 "linkReference",
25 "image",
26 "imageReference",
27 "code",
28 "inlineCode",
29 "html",
30 "definition",
31]);
32
33/**
34 * Rewrites the references `autolinks` finds in the markdown's prose as markdown links, and GitHub's
35 * `:alias:` emoji as the emoji, because the native renderer takes markdown text. Text is searched
36 * as written, escapes included. The result drops a leading BOM, which the native parser would read
37 * as text. `sourceOffset` maps an offset in the result back to `markdown`.
38 */
39export function nativePullRequestMarkdown(
40 markdown: string,
41 autolinks: ((text: string) => ReadonlyArray<ReferenceAutolink>) | null,
42 githubEmoji: boolean,
43): { readonly markdown: string; readonly sourceOffset: (offset: number) => number } {
44 const [bom, source] = splitLeadingBom(markdown);
45 const unchanged = { markdown: source, sourceOffset: (offset: number) => bom.length + offset };
46 if (autolinks === null && !githubEmoji) return unchanged;
47 const edits: { start: number; end: number; value: string }[] = [];
48 const visit = (node: MarkdownNode, inLink: boolean) => {
49 // Only a bracketed label is prose; an autolink's text is its destination.
50 const labelled = source[node.position?.start.offset ?? -1] === "[";
51 if (node.type === "link" && labelled && !inLink) {
52 node.children?.forEach((child) => visit(child, true));
53 return;
54 }
55 if (UNLINKED_TYPES.has(node.type)) return;
56 if (node.type === "text") {
57 const start = node.position?.start.offset;
58 const end = node.position?.end.offset;
59 if (start === undefined || end === undefined) return;
60 const text = source.slice(start, end);
61 const found: { start: number; end: number; value: string }[] = [];
62 for (const link of inLink ? [] : (autolinks?.(text) ?? [])) {
63 found.push({
64 start: start + link.index,
65 end: start + link.index + link.text.length,
66 value: `[${link.label}](${link.url})`,
67 });
68 }
69 for (const alias of githubEmoji ? githubEmojiAliases(text) : []) {
70 // Keycap emoji start with `*`, which the native parser would read as emphasis.
71 const value = alias.emoji.replaceAll("*", "\\*");
72 found.push({
73 start: start + alias.index,
74 end: start + alias.index + alias.text.length,
75 value,
76 });
77 }
78 found.sort((left, right) => left.start - right.start);
79 for (const edit of found) {
80 if (edit.start >= (edits.at(-1)?.end ?? 0)) edits.push(edit);
81 }
82 } else if (node.children !== undefined) {
83 let protectedHtmlDepth = 0;
84 for (const child of node.children) {
85 if (child.type === "html" && !HTML_BLOCK_PARENTS.has(node.type)) {
86 const start = child.position?.start.offset;
87 const end = child.position?.end.offset;
88 const tag = start === undefined || end === undefined ? "" : source.slice(start, end);
89 const match = /^<(\/)?(?:a|code|pre|script|style)(?=[\s>])/iu.exec(tag);
90 if (match) {
91 protectedHtmlDepth = Math.max(0, protectedHtmlDepth + (match[1] ? -1 : 1));
92 }
93 } else if (protectedHtmlDepth === 0) visit(child, inLink);
94 }
95 }
96 };
97 visit(parser.parse(markdown), false);
98 if (edits.length === 0) return unchanged;
99 let rewritten = "";
100 let cursor = 0;
101 // Where each edit ends in the result, and how far `markdown` is ahead from there on.
102 const shifts: { end: number; delta: number }[] = [];
103 for (const edit of edits) {
104 rewritten += source.slice(cursor, edit.start) + edit.value;
105 cursor = edit.end;
106 shifts.push({ end: rewritten.length, delta: bom.length + edit.end - rewritten.length });
107 }
108 rewritten += source.slice(cursor);
109 return {
110 markdown: rewritten,
111 sourceOffset(offset) {
112 let delta = bom.length;
113 for (const shift of shifts) {
114 if (shift.end > offset) break;
115 delta = shift.delta;
116 }
117 return offset + delta;
118 },
119 };
120}