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

pullRequestMarkdown.ts

179 lines6.4 KB

1import { sourceControlClients, type ReferenceAutolink } from "./sourceControlClients.ts";
2​
3/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
4export type PullRequestBodySegment =
5 | {
6 readonly id: string;
7 readonly kind: "markdown";
8 readonly text: string;
9 /** Where `text` starts in the body, so an edit made to it can be written back. */
10 readonly sourceOffset: number;
11 }
12 | {
13 readonly id: string;
14 readonly kind: "attachment";
15 readonly url: string;
16 readonly media: "video" | "image" | "unknown";
17 };
18​
19// `.` stops at the `\r` of a CRLF body, which is how GitHub stores one written in its web editor.
20const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)\r?$/u;
21/**
22 * How far a `<video>` tag may reach for its closing tag. Real embeds are one to three lines,
23 * and the bound keeps an unclosed tag from making each one rescan the rest of the body.
24 */
25const VIDEO_TAG_MAX_LINES = 8;
26​
27const INDENTED_CODE_PATTERN = /^(?: {4}|\t)/u;
28const BARE_URL_PATTERN = /^<?(https?:\/\/\S+?)>?$/u;
29const IMAGE_EXTENSION_PATTERN = /\.(?:png|jpe?g|gif|webp|avif|heic|heif|svg)(?:$|[?#])/iu;
30const MARKDOWN_LINK_PATTERN = /^\[[^\]]*\]\((https?:\/\/[^\s)]+)\)$/u;
31const VIDEO_EXTENSION_PATTERN = /\.(?:mp4|webm|mov|m4v|ogv)(?:$|[?#])/iu;
32​
33const VIDEO_TAG_SRC_PATTERN = /<(?:video|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/iu;
34​
35const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;
36const VIDEO_TAG_END_PATTERN = /<\/video>\s*$/iu;
37​
38function isWebUrl(url: string): boolean {
39 try {
40 const parsed = new URL(url);
41 return parsed.protocol === "https:" || parsed.protocol === "http:";
42 } catch {
43 return false;
44 }
46​
47function attachmentFromLine(
48 line: string,
49): { url: string; media: "video" | "image" | "unknown" } | null {
50 const url =
51 BARE_URL_PATTERN.exec(line.trim())?.[1] ?? MARKDOWN_LINK_PATTERN.exec(line.trim())?.[1];
52 if (url === undefined || !isWebUrl(url)) return null;
53 if (VIDEO_EXTENSION_PATTERN.test(url) || sourceControlClients.mediaUrl(url)?.kind === "video") {
54 return { url, media: "video" };
55 }
56 if (IMAGE_EXTENSION_PATTERN.test(url)) return { url, media: "image" };
57 return null;
59​
60export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodySegment> {
61 const segments: PullRequestBodySegment[] = [];
62 const markdown: string[] = [];
63 let markdownStart = 0;
64 let openFence: string | null = null;
65​
66 // Blank lines around a run are dropped, but never leading spaces: four of them open an
67 // indented code block, so trimming a run would silently turn code into prose.
68 const flushMarkdown = () => {
69 const joined = markdown.join("\n");
70 const text = joined.replace(/^\n+/u, "");
71 const sourceOffset = markdownStart + joined.length - text.length;
72 markdown.length = 0;
73 if (text.trim().length > 0) {
74 segments.push({
75 id: `markdown:${segments.length}`,
76 kind: "markdown",
77 text: text.replace(/\s+$/u, ""),
78 sourceOffset,
79 });
80 }
81 };
82​
83 const lines = body.split("\n");
84 let lineStart = 0;
85 for (let index = 0; index < lines.length; lineStart += lines[index]!.length + 1, index += 1) {
86 const line = lines[index]!;
87 if (markdown.length === 0) markdownStart = lineStart;
88 const fenceMatch = FENCE_PATTERN.exec(line);
89 if (fenceMatch !== null) {
90 const fence = fenceMatch[1]!;
91 // A fence closes only on the same marker, at least as long as the one that opened it,
92 // and with nothing after it: `~~~` cannot end a ``` block, and ```` ```ts ```` is an
93 // info string opening a nested fence, not a close.
94 const closes =
95 openFence !== null &&
96 fence[0] === openFence[0] &&
97 fence.length >= openFence.length &&
98 fenceMatch[2]!.trim().length === 0;
99 if (openFence === null) {
100 openFence = fence;
101 } else if (closes) {
102 openFence = null;
103 }
104 markdown.push(line);
105 continue;
106 }
107 if (openFence !== null || INDENTED_CODE_PATTERN.test(line)) {
108 markdown.push(line);
109 continue;
110 }
111​
112 const bareAttachment = attachmentFromLine(line);
113 if (bareAttachment !== null) {
114 flushMarkdown();
115 segments.push({ id: `attachment:${segments.length}`, kind: "attachment", ...bareAttachment });
116 continue;
117 }
118​
119 if (!STANDALONE_VIDEO_TAG_PATTERN.test(line)) {
120 markdown.push(line);
121 continue;
122 }
123 const lastCandidate = Math.min(index + VIDEO_TAG_MAX_LINES, lines.length) - 1;
124 let cursor = index;
125 while (cursor < lastCandidate && !VIDEO_TAG_END_PATTERN.test(lines[cursor]!)) {
126 cursor += 1;
127 }
128 const source = VIDEO_TAG_END_PATTERN.test(lines[cursor]!)
129 ? VIDEO_TAG_SRC_PATTERN.exec(lines.slice(index, cursor + 1).join("\n"))?.[1]
130 : undefined;
131 if (source !== undefined && isWebUrl(source)) {
132 flushMarkdown();
133 segments.push({
134 id: `attachment:${segments.length}`,
135 kind: "attachment",
136 url: source,
137​
138 media: "video",
139 });
140 for (; index < cursor; index += 1) lineStart += lines[index]!.length + 1;
141 } else {
142 // Unclosed, or nothing linkable in it: prose. Only this line is consumed, so the
143 // lines that were looked at are still parsed on their own terms.
144 markdown.push(line);
145 }
146 }
147​
148 flushMarkdown();
149 return segments;
151​
152/**
153 * Finds the references the change request's host links in plain text, resolved against the change
154 * request's repository. Null when the host links none.
155 */
156export function changeRequestReferenceAutolinker(
157 changeRequest: { readonly provider: string; readonly url: string } | null | undefined,
158): ((text: string) => ReadonlyArray<ReferenceAutolink>) | null {
159 if (!changeRequest) return null;
160 const find = sourceControlClients.get(changeRequest.provider).referenceAutolinks;
161 const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link
162 .repositoryUrl;
163 return find === undefined || repositoryUrl === undefined
164 ? null
165 : (text) => find(text, repositoryUrl);
167​
168/**
169 * Forges link uploads root-relative, as GitCafe's `/api/attachments/<id>`. In a change request
170 * body that always means the forge's origin, never a path on the machine rendering it.
171 */
172export function resolveChangeRequestMediaUrl(url: string, changeRequestUrl: string): string {
173 if (!/^\/(?![/\\])/u.test(url)) return url;
174 try {
175 return new URL(url, changeRequestUrl).href;
176 } catch {
177 return url;
178 }