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