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

pullRequestMarkdown.ts

361 lines13.5 KB

1import { GITHUB_EMOJI_ALIASES } from "./githubEmojiAliases.ts";
2import { sourceControlClients } from "./sourceControlClients.ts";
3​
4/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
5export type PullRequestBodySegment =
6 | {
7 readonly id: string;
8 readonly kind: "markdown";
9 readonly text: string;
10 /**
11 * `sourceOffset + i` is where `text[i]` sits in the body, so an edit can be written back.
12 * Holds past the body's reference definitions, which `text` may lead with.
13 */
14 readonly sourceOffset: number;
15 }
16 | {
17 readonly id: string;
18 readonly kind: "attachment";
19 readonly url: string;
20 readonly media: "video" | "image" | "unknown";
21 }
22 | {
23 readonly id: string;
24 readonly kind: "table";
25 readonly rows: ReadonlyArray<ReadonlyArray<PullRequestBodyTableCell>>;
26 };
27​
28type PullRequestBodyTableCell = {
29 readonly header: boolean;
30 readonly segments: ReadonlyArray<PullRequestBodySegment>;
31};
32​
33// `.` stops at the `\r` of a CRLF body, which is how GitHub stores one written in its web editor.
34const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)\r?$/u;
35/**
36 * How far a `<video>` tag may reach for its closing tag. Real embeds are one to three lines,
37 * and the bound keeps an unclosed tag from making each one rescan the rest of the body.
38 */
39const VIDEO_TAG_MAX_LINES = 8;
40​
41// A tab after up to three spaces still reaches the fourth column.
42const INDENTED_CODE_PATTERN = /^(?: {4}| {0,3}\t)/u;
43const BARE_URL_PATTERN = /^<?(https?:\/\/\S+?)>?$/u;
44const IMAGE_EXTENSION_PATTERN = /\.(?:png|jpe?g|gif|webp|avif|heic|heif|svg)(?:$|[?#])/iu;
45const MARKDOWN_LINK_PATTERN = /^\[[^\]]*\]\((https?:\/\/[^\s)]+)\)$/u;
46const VIDEO_EXTENSION_PATTERN = /\.(?:mp4|webm|mov|m4v|ogv)(?:$|[?#])/iu;
47​
48const VIDEO_TAG_SRC_PATTERN = /<(?:video|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/iu;
49​
50const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;
51const VIDEO_TAG_END_PATTERN = /<\/video>\s*$/iu;
52​
53/** Bounded like `VIDEO_TAG_MAX_LINES`; room for a before/after table with several rows. */
54const TABLE_MAX_LINES = 64;
55const TABLE_START_PATTERN = /^\s*<table\b/iu;
56const TABLE_END_PATTERN = /<\/table>\s*$/iu;
57const TABLE_OPEN_PATTERN = /<table\b/giu;
58const TABLE_CLOSE_PATTERN = /<\/table\s*>/giu;
59/**
60 * Quoted attribute values may hold `>`. The alternatives start on disjoint characters and an
61 * unquoted run stops at the next `<`, so a run of unterminated tags stays linear.
62 */
63const TABLE_STRUCTURE_TAG_PATTERN =
64 /<(\/?)(table|thead|tbody|tfoot|tr|td|th)\b((?:[^<>"']|"[^"]*"|'[^']*')*)>/giu;
65/** Rows are laid out independently, so a spanning cell would shift the cells after it. */
66const CELL_SPAN_PATTERN = /\b(?:col|row)span\b/iu;
67​
68function isWebUrl(url: string): boolean {
69 try {
70 const parsed = new URL(url);
71 return parsed.protocol === "https:" || parsed.protocol === "http:";
72 } catch {
73 return false;
74 }
76​
77function attachmentFromLine(
78 line: string,
79): { url: string; media: "video" | "image" | "unknown" } | null {
80 const url =
81 BARE_URL_PATTERN.exec(line.trim())?.[1] ?? MARKDOWN_LINK_PATTERN.exec(line.trim())?.[1];
82 if (url === undefined || !isWebUrl(url)) return null;
83 if (VIDEO_EXTENSION_PATTERN.test(url) || sourceControlClients.mediaUrl(url)?.kind === "video") {
84 return { url, media: "video" };
85 }
86 if (IMAGE_EXTENSION_PATTERN.test(url)) return { url, media: "image" };
87 return null;
89​
90type TableRows = ReadonlyArray<ReadonlyArray<PullRequestBodyTableCell>>;
91​
92/**
93 * Cells of a table made only of rows and cells, or null when anything else is in it: a caption,
94 * text between cells, a nested table. Cell contents are split on their own, so tables never nest.
95 */
96function tableRows(html: string, htmlOffset: number): TableRows | null {
97 const rows: PullRequestBodyTableCell[][] = [];
98 let row: PullRequestBodyTableCell[] | null = null;
99 let cell: { tag: string; contentStart: number } | null = null;
100 let opened = false;
101 let closed = false;
102 let cursor = 0;
103 for (const match of html.matchAll(TABLE_STRUCTURE_TAG_PATTERN)) {
104 const closing = match[1] === "/";
105 const tag = match[2]!.toLowerCase();
106 if (cell !== null) {
107 if (!closing || tag !== cell.tag) return null;
108 const content = html.slice(cell.contentStart, match.index);
109 // Indented HTML would render as a code block once the cell is markdown on its own.
110 if (content.split("\n").some((line) => INDENTED_CODE_PATTERN.test(line) && line.trim()))
111 return null;
112 row!.push({
113 header: tag === "th",
114 segments: splitBodyAt(content, htmlOffset + cell.contentStart),
115 });
116 cell = null;
117 } else {
118 if (html.slice(cursor, match.index).trim().length > 0) return null;
119 const tableOpen = opened && !closed;
120 if (tag === "table") {
121 if (closing ? !tableOpen || row !== null : opened) return null;
122 opened = true;
123 closed = closing;
124 } else if (tag === "tr") {
125 if (!tableOpen || closing === (row === null)) return null;
126 if (closing) rows.push(row!);
127 row = closing ? null : [];
128 } else if (tag === "td" || tag === "th") {
129 if (closing || row === null || CELL_SPAN_PATTERN.test(match[3]!)) return null;
130 cell = { tag, contentStart: match.index + match[0].length };
131 } else if (!tableOpen || row !== null) {
132 return null;
133 }
134 }
135 cursor = match.index + match[0].length;
136 }
137 if (!closed || html.slice(cursor).trim().length > 0) return null;
138 return rows.filter((cells) => cells.length > 0);
140​
141/**
142 * The table opening at `start`, through its matching close. `end` is the last line looked at
143 * even when the table is not usable, so the caller never re-reads an inner table on its own.
144 */
145function mediaTableAt(
146 lines: ReadonlyArray<string>,
147 start: number,
148 startOffset: number,
149): { end: number; rows: TableRows | null } {
150 const lastCandidate = Math.min(start + TABLE_MAX_LINES, lines.length) - 1;
151 let depth = 0;
152 let end = start;
153 for (; ; end += 1) {
154 const line = lines[end]!;
155 depth +=
156 (line.match(TABLE_OPEN_PATTERN)?.length ?? 0) -
157 (line.match(TABLE_CLOSE_PATTERN)?.length ?? 0);
158 if (depth <= 0 || end === lastCandidate) break;
159 }
160 if (depth !== 0 || !TABLE_END_PATTERN.test(lines[end]!)) return { end, rows: null };
161 // Lifting attachment links out of a table's cells would tear the table apart.
162 const rows = tableRows(lines.slice(start, end + 1).join("\n"), startOffset);
163 const hasMedia = rows?.some((cells) =>
164 cells.some((cell) => cell.segments.some((segment) => segment.kind === "attachment")),
165 );
166 return { end, rows: hasMedia ? rows : null };
168​
169/**
170 * Each markdown segment renders as its own document, so it leads with the body's definitions.
171 * Leading, they win over a later redefinition in the segment, as the first one does in the body.
172 */
173function withDefinitions(
174 segment: PullRequestBodySegment,
175 definitions: string,
176): PullRequestBodySegment {
177 if (segment.kind === "attachment") return segment;
178 if (segment.kind === "table") {
179 return {
180 ...segment,
181 rows: segment.rows.map((cells) =>
182 cells.map((cell) => ({
183 ...cell,
184 segments: cell.segments.map((inner) => withDefinitions(inner, definitions)),
185 })),
186 ),
187 };
188 }
189 if (!segment.text.includes("[")) return segment;
190 return {
191 ...segment,
192 text: definitions + segment.text,
193 sourceOffset: segment.sourceOffset - definitions.length,
194 };
196​
197/**
198 * The first definition of each label in a body, each on one line so it stands outside the quote or
199 * list it was written in, as the client's Markdown parser reads them.
200 */
201export type FindReferenceDefinitions = (body: string) => ReadonlyArray<string>;
202​
203export function splitPullRequestBody(
204 body: string,
205 findDefinitions: FindReferenceDefinitions,
206): ReadonlyArray<PullRequestBodySegment> {
207 const segments = splitBodyAt(body, 0);
208 // One markdown segment is the whole body, which resolves its own references.
209 const whole = segments.length === 1 && segments[0]!.kind === "markdown";
210 if (whole || !body.includes("]:")) return segments;
211 const definitions = findDefinitions(body);
212 if (definitions.length === 0) return segments;
213 const leading = `${definitions.join("\n")}\n\n`;
214 return segments.map((segment) => withDefinitions(segment, leading));
216​
217/** `baseOffset` is where `body` starts in the whole body, so a table cell's edits write back. */
218function splitBodyAt(body: string, baseOffset: number): ReadonlyArray<PullRequestBodySegment> {
219 const segments: PullRequestBodySegment[] = [];
220 const markdown: string[] = [];
221 let markdownStart = 0;
222 let openFence: string | null = null;
223​
224 // Blank lines around a run are dropped, but never leading spaces: four of them open an
225 // indented code block, so trimming a run would silently turn code into prose.
226 const flushMarkdown = () => {
227 const joined = markdown.join("\n");
228 const text = joined.replace(/^(?:\r?\n)+/u, "");
229 const sourceOffset = markdownStart + joined.length - text.length;
230 markdown.length = 0;
231 if (text.trim().length > 0) {
232 segments.push({
233 id: `markdown:${segments.length}`,
234 kind: "markdown",
235 text: text.replace(/\s+$/u, ""),
236 sourceOffset,
237 });
238 }
239 };
240​
241 const lines = body.split("\n");
242 let tableScannedThrough = -1;
243 let lineStart = baseOffset;
244 for (let index = 0; index < lines.length; lineStart += lines[index]!.length + 1, index += 1) {
245 const line = lines[index]!;
246 if (markdown.length === 0) markdownStart = lineStart;
247 const fenceMatch = FENCE_PATTERN.exec(line);
248 // ```` ```npm test``` ```` is a code span, not an opener that would flip every later fence.
249 // A span that runs past this line is left an opener, so its lines stay out of media.
250 const isInlineCode =
251 openFence === null &&
252 fenceMatch?.[1]![0] === "`" &&
253 (fenceMatch[2]!.match(/`+/gu) ?? []).some((run) => run.length === fenceMatch[1]!.length);
254 if (fenceMatch !== null && !isInlineCode) {
255 const fence = fenceMatch[1]!;
256 // A fence closes only on the same marker, at least as long as the one that opened it,
257 // and with nothing after it: `~~~` cannot end a ``` block, and ```` ```ts ```` is an
258 // info string opening a nested fence, not a close.
259 const closes =
260 openFence !== null &&
261 fence[0] === openFence[0] &&
262 fence.length >= openFence.length &&
263 fenceMatch[2]!.trim().length === 0;
264 if (openFence === null) {
265 openFence = fence;
266 } else if (closes) {
267 openFence = null;
268 }
269 markdown.push(line);
270 continue;
271 }
272 if (openFence !== null || INDENTED_CODE_PATTERN.test(line)) {
273 markdown.push(line);
274 continue;
275 }
276​
277 if (index > tableScannedThrough && TABLE_START_PATTERN.test(line)) {
278 const table = mediaTableAt(lines, index, lineStart);
279 tableScannedThrough = table.end;
280 if (table.rows !== null) {
281 flushMarkdown();
282 segments.push({ id: `table:${segments.length}`, kind: "table", rows: table.rows });
283 for (; index < table.end; index += 1) lineStart += lines[index]!.length + 1;
284 continue;
285 }
286 }
287​
288 const bareAttachment = attachmentFromLine(line);
289 if (bareAttachment !== null) {
290 flushMarkdown();
291 segments.push({ id: `attachment:${segments.length}`, kind: "attachment", ...bareAttachment });
292 continue;
293 }
294​
295 if (!STANDALONE_VIDEO_TAG_PATTERN.test(line)) {
296 markdown.push(line);
297 continue;
298 }
299 const lastCandidate = Math.min(index + VIDEO_TAG_MAX_LINES, lines.length) - 1;
300 let cursor = index;
301 while (cursor < lastCandidate && !VIDEO_TAG_END_PATTERN.test(lines[cursor]!)) {
302 cursor += 1;
303 }
304 const source = VIDEO_TAG_END_PATTERN.test(lines[cursor]!)
305 ? VIDEO_TAG_SRC_PATTERN.exec(lines.slice(index, cursor + 1).join("\n"))?.[1]
306 : undefined;
307 if (source !== undefined && isWebUrl(source)) {
308 flushMarkdown();
309 segments.push({
310 id: `attachment:${segments.length}`,
311 kind: "attachment",
312 url: source,
313​
314 media: "video",
315 });
316 for (; index < cursor; index += 1) lineStart += lines[index]!.length + 1;
317 } else {
318 // Unclosed, or nothing linkable in it: prose. Only this line is consumed, so the
319 // lines that were looked at are still parsed on their own terms.
320 markdown.push(line);
321 }
322 }
323​
324 flushMarkdown();
325 return segments;
327let githubEmojiByAlias: ReadonlyMap<string, string> | undefined;
328const githubEmojiAlias = /:([a-z\d_+-]+)(?=:)/gu;
329​
330/** GitHub's `:alias:` emoji in `text`; a colon closes one alias only, so `:tada:tada:` has one. */
331export function githubEmojiAliases(
332 text: string,
333): ReadonlyArray<{ readonly index: number; readonly text: string; readonly emoji: string }> {
334 githubEmojiByAlias ??= new Map(
335 GITHUB_EMOJI_ALIASES.trim()
336 .split("\n")
337 .map((line) => {
338 const space = line.indexOf(" ");
339 return [line.slice(0, space), line.slice(space + 1)] as const;
340 }),
341 );
342 const found: { index: number; text: string; emoji: string }[] = [];
343 let end = 0;
344 for (const match of text.matchAll(githubEmojiAlias)) {
345 const emoji = githubEmojiByAlias.get(match[1]!);
346 if (emoji === undefined || match.index < end) continue;
347 end = match.index + match[0].length + 1;
348 found.push({ index: match.index, text: `${match[0]}:`, emoji });
349 }
350 return found;
352​
353export function expandGithubEmojiAliases(text: string): string {
354 let expanded = "";
355 let start = 0;
356 for (const alias of githubEmojiAliases(text)) {
357 expanded += text.slice(start, alias.index) + alias.emoji;
358 start = alias.index + alias.text.length;
359 }
360 return start === 0 ? text : expanded + text.slice(start);