Open History to see the last commit
1import { markdownLinkDestinationScanner } from "@t3tools/shared/markdownLinks";
2import * as Effect from "effect/Effect";
3import { Atom } from "effect/reactivity";
4import { GITHUB_EMOJI_ALIASES } from "./githubEmojiAliases.ts";
5import { sourceControlClients } from "./sourceControlClients.ts";
6
7/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
8export type PullRequestBodySegment =
9 | {
10 readonly id: string;
11 readonly kind: "markdown";
12 readonly text: string;
13 /**
14 * `sourceOffset + i` is where `text[i]` sits in the body, so an edit can be written back.
15 * Holds past the body's reference definitions, which `text` may lead with.
16 */
17 readonly sourceOffset: number;
18 }
19 | {
20 readonly id: string;
21 readonly kind: "attachment";
22 readonly url: string;
23 readonly media: "video" | "image" | "unknown";
24 readonly label?: string;
25 }
26 | {
27 readonly id: string;
28 readonly kind: "table";
29 readonly rows: ReadonlyArray<ReadonlyArray<PullRequestBodyTableCell>>;
30 };
31
32type PullRequestBodyTableCell = {
33 readonly header: boolean;
34 readonly segments: ReadonlyArray<PullRequestBodySegment>;
35};
36
37// `.` stops at the `\r` of a CRLF body, which is how GitHub stores one written in its web editor.
38// The marker is the whole run, so a line that is no fence is given up on in one pass.
39// A fence may open right after a list marker: `- ```ts` starts code inside the item.
40const FENCE_PATTERN = /^\s{0,3}(?:(?:[-+*]|\d{1,9}[.)]) {1,4})?(`{3,}(?!`)|~{3,}(?!~))(.*)\r?$/u;
41const LIST_ITEM_PATTERN = /^\s{0,3}(?:[-+*]|\d{1,9}[.)]) /u;
42
43/** Tabs advance to the next multiple of four, as Markdown measures indentation. */
44function indentColumns(line: string): number {
45 let column = 0;
46 for (const char of /^[ \t]*/u.exec(line)![0]) column += char === "\t" ? 4 - (column % 4) : 1;
47 return column;
48}
49
50/**
51 * How far a `<video>` tag may reach for its closing tag. Real embeds are one to three lines,
52 * and the bound keeps an unclosed tag from making each one rescan the rest of the body.
53 */
54const VIDEO_TAG_MAX_LINES = 8;
55
56// A tab after up to three spaces still reaches the fourth column.
57const INDENTED_CODE_PATTERN = /^(?: {4}| {0,3}\t)/u;
58const HTML_COMMENT_START_PATTERN = /^ {0,3}<!--/u;
59const BARE_URL_PATTERN = /^<?(https?:\/\/\S+?)>?$/u;
60const IMAGE_EXTENSION_PATTERN = /\.(?:png|jpe?g|gif|webp|avif|heic|heif|svg)$/iu;
61// A destination unescapes backslashed ASCII punctuation and decodes character references
62// (`&`); a link with a reference stays Markdown so its parser decodes it.
63const MARKDOWN_DESTINATION_TOKEN_PATTERN =
64 /\\([!-/:-@[-`{-~])|&(?:#\d{1,7}|#[xX][\da-fA-F]{1,6}|[A-Za-z][A-Za-z\d]{1,31});/gu;
65const VIDEO_EXTENSION_PATTERN = /\.(?:mp4|webm|mov|m4v|ogv)$/iu;
66
67// Stops at the next `<`, so matching stays linear in the length of the line.
68const VIDEO_SOURCE_TAG_PATTERN = /<(?:video|source)(?=[\s/>])((?:[^<>"']|"[^"]*"|'[^']*')*)>/giu;
69const HTML_ATTRIBUTE_PATTERN = /([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>`]+)))?/gu;
70const HTML_AMPERSAND_REFERENCE_PATTERN = /&(?:amp|AMP|#0*38|#[xX]0*26);/gu;
71
72function videoTagSource(html: string): string | undefined {
73 for (const tag of html.matchAll(VIDEO_SOURCE_TAG_PATTERN)) {
74 for (const attribute of tag[1]!.matchAll(HTML_ATTRIBUTE_PATTERN)) {
75 if (attribute[1]!.toLowerCase() !== "src") continue;
76 const value = attribute[2] ?? attribute[3] ?? attribute[4];
77 if (value) return value.replace(HTML_AMPERSAND_REFERENCE_PATTERN, "&");
78 }
79 }
80 return undefined;
81}
82
83const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;
84const VIDEO_TAG_END_PATTERN = /<\/video>\s*$/iu;
85const VIDEO_TAG_CLOSE_PATTERN = /<\/video>/iu;
86
87/** Bounded like `VIDEO_TAG_MAX_LINES`; room for a before/after table with several rows. */
88const TABLE_MAX_LINES = 64;
89const TABLE_START_PATTERN = /^\s*<table\b/iu;
90const TABLE_END_PATTERN = /<\/table>\s*$/iu;
91const TABLE_OPEN_PATTERN = /<table\b/giu;
92const TABLE_CLOSE_PATTERN = /<\/table\s*>/giu;
93/**
94 * Quoted attribute values may hold `>`. The alternatives start on disjoint characters and an
95 * unquoted run stops at the next `<`, so a run of unterminated tags stays linear.
96 */
97const TABLE_STRUCTURE_TAG_PATTERN =
98 /<(\/?)(table|thead|tbody|tfoot|tr|td|th)\b((?:[^<>"']|"[^"]*"|'[^']*')*)>/giu;
99/** Rows are laid out independently, so a spanning cell would shift the cells after it. */
100const CELL_SPAN_PATTERN = /\b(?:col|row)span\b/iu;
101
102function webUrl(url: string): URL | null {
103 try {
104 const parsed = new URL(url);
105 return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed : null;
106 } catch {
107 return null;
108 }
109}
110
111/** Index just past the code span opened at `start`, or past the backtick run when none closes it. */
112function codeSpanEnd(text: string, start: number): number {
113 let open = start;
114 while (text[open] === "`") open += 1;
115 for (let index = open; index < text.length;) {
116 if (text[index] !== "`") {
117 index += 1;
118 continue;
119 }
120 let close = index;
121 while (text[close] === "`") close += 1;
122 if (close - index === open - start) return close;
123 index = close;
124 }
125 return open;
126}
127
128function standaloneMarkdownLink(trimmed: string): { label: string; url: string } | null {
129 if (!trimmed.startsWith("[")) return null;
130 // A label may nest balanced brackets; an escaped `\]` or one inside a code span never closes it.
131 let closeBracket = -1;
132 for (let index = 1, depth = 0; index < trimmed.length && closeBracket < 0; index += 1) {
133 const character = trimmed[index];
134 if (character === "\\") index += 1;
135 else if (character === "`") index = codeSpanEnd(trimmed, index) - 1;
136 else if (character === "[") depth += 1;
137 else if (character === "]" && depth-- === 0) closeBracket = index;
138 }
139 if (closeBracket < 0 || trimmed[closeBracket + 1] !== "(") return null;
140 const destination = markdownLinkDestinationScanner(trimmed)(closeBracket + 1);
141 if (destination === null || destination.end !== trimmed.length) return null;
142 let hasCharacterReference = false;
143 const url = trimmed
144 .slice(destination.hrefStart, destination.hrefEnd)
145 .replace(MARKDOWN_DESTINATION_TOKEN_PATTERN, (token, escaped: string | undefined) => {
146 if (escaped !== undefined) return escaped;
147 hasCharacterReference = true;
148 return token;
149 });
150 return url && !hasCharacterReference ? { label: trimmed.slice(1, closeBracket), url } : null;
151}
152
153function attachmentFromLine(
154 line: string,
155): Omit<Extract<PullRequestBodySegment, { kind: "attachment" }>, "id" | "kind"> | null {
156 const trimmed = line.trim();
157 const link = standaloneMarkdownLink(trimmed);
158 const url = link?.url ?? BARE_URL_PATTERN.exec(trimmed)?.[1];
159 if (url === undefined) return null;
160 // Only the path names the file: `report?file=demo.mp4` is a page, not a video.
161 const path = webUrl(url)?.pathname;
162 if (path === undefined) return null;
163 const media = VIDEO_EXTENSION_PATTERN.test(path)
164 ? "video"
165 : IMAGE_EXTENSION_PATTERN.test(path)
166 ? "image"
167 : sourceControlClients.mediaUrl(url)?.kind;
168 if (media === undefined) return null;
169 const label = link?.label.trim();
170 return label ? { url, media, label } : { url, media };
171}
172
173export function makePullRequestMediaKindAtom(
174 fetchMedia: (
175 url: string,
176 options: { headers: Record<string, string>; signal: AbortSignal },
177 ) => Promise<Pick<Response, "ok" | "headers" | "body">>,
178) {
179 return Atom.family((url: string | null) =>
180 Atom.make(
181 Effect.promise(async (signal) => {
182 if (url === null) return null;
183 try {
184 const response = await fetchMedia(url, { headers: { Range: "bytes=0-0" }, signal });
185 void response.body?.cancel().catch(() => undefined);
186 if (!response.ok) return null;
187 const type = response.headers.get("content-type")?.trim().toLowerCase();
188 if (type?.startsWith("image/")) return "image" as const;
189 if (type?.startsWith("video/")) return "video" as const;
190 return null;
191 } catch {
192 return null;
193 }
194 }),
195 ),
196 );
197}
198
199type TableRows = ReadonlyArray<ReadonlyArray<PullRequestBodyTableCell>>;
200
201/**
202 * Cells of a table made only of rows and cells, or null when anything else is in it: a caption,
203 * text between cells, a nested table. Cell contents are split on their own, so tables never nest.
204 */
205function tableRows(html: string, htmlOffset: number): TableRows | null {
206 const rows: PullRequestBodyTableCell[][] = [];
207 let row: PullRequestBodyTableCell[] | null = null;
208 let cell: { tag: string; contentStart: number } | null = null;
209 let opened = false;
210 let closed = false;
211 let cursor = 0;
212 for (const match of html.matchAll(TABLE_STRUCTURE_TAG_PATTERN)) {
213 const closing = match[1] === "/";
214 const tag = match[2]!.toLowerCase();
215 if (cell !== null) {
216 if (!closing || tag !== cell.tag) return null;
217 const content = html.slice(cell.contentStart, match.index);
218 // Indented HTML would render as a code block once the cell is markdown on its own.
219 if (content.split("\n").some((line) => INDENTED_CODE_PATTERN.test(line) && line.trim()))
220 return null;
221 row!.push({
222 header: tag === "th",
223 segments: splitBodyAt(content, htmlOffset + cell.contentStart),
224 });
225 cell = null;
226 } else {
227 if (html.slice(cursor, match.index).trim().length > 0) return null;
228 const tableOpen = opened && !closed;
229 if (tag === "table") {
230 if (closing ? !tableOpen || row !== null : opened) return null;
231 opened = true;
232 closed = closing;
233 } else if (tag === "tr") {
234 if (!tableOpen || closing === (row === null)) return null;
235 if (closing) rows.push(row!);
236 row = closing ? null : [];
237 } else if (tag === "td" || tag === "th") {
238 if (closing || row === null || CELL_SPAN_PATTERN.test(match[3]!)) return null;
239 cell = { tag, contentStart: match.index + match[0].length };
240 } else if (!tableOpen || row !== null) {
241 return null;
242 }
243 }
244 cursor = match.index + match[0].length;
245 }
246 if (!closed || html.slice(cursor).trim().length > 0) return null;
247 return rows.filter((cells) => cells.length > 0);
248}
249
250/**
251 * The table opening at `start`, through its matching close. `end` is the last line looked at
252 * even when the table is not usable, so the caller never re-reads an inner table on its own.
253 */
254function mediaTableAt(
255 lines: ReadonlyArray<string>,
256 start: number,
257 startOffset: number,
258): { end: number; rows: TableRows | null } {
259 const lastCandidate = Math.min(start + TABLE_MAX_LINES, lines.length) - 1;
260 let depth = 0;
261 let end = start;
262 for (; ; end += 1) {
263 const line = lines[end]!;
264 depth +=
265 (line.match(TABLE_OPEN_PATTERN)?.length ?? 0) -
266 (line.match(TABLE_CLOSE_PATTERN)?.length ?? 0);
267 if (depth <= 0 || end === lastCandidate) break;
268 }
269 if (depth !== 0 || !TABLE_END_PATTERN.test(lines[end]!)) return { end, rows: null };
270 // Lifting attachment links out of a table's cells would tear the table apart.
271 const rows = tableRows(lines.slice(start, end + 1).join("\n"), startOffset);
272 const hasMedia = rows?.some((cells) =>
273 cells.some((cell) => cell.segments.some((segment) => segment.kind === "attachment")),
274 );
275 return { end, rows: hasMedia ? rows : null };
276}
277
278/**
279 * Each markdown segment renders as its own document, so it leads with the body's definitions.
280 * Leading, they win over a later redefinition in the segment, as the first one does in the body.
281 */
282function withDefinitions(
283 segment: PullRequestBodySegment,
284 definitions: string,
285): PullRequestBodySegment {
286 if (segment.kind === "attachment") return segment;
287 if (segment.kind === "table") {
288 return {
289 ...segment,
290 rows: segment.rows.map((cells) =>
291 cells.map((cell) => ({
292 ...cell,
293 segments: cell.segments.map((inner) => withDefinitions(inner, definitions)),
294 })),
295 ),
296 };
297 }
298 if (!segment.text.includes("[")) return segment;
299 const bomLength = segment.sourceOffset === 0 && segment.text.startsWith("\uFEFF") ? 1 : 0;
300 return {
301 ...segment,
302 text: definitions + segment.text.slice(bomLength),
303 sourceOffset: segment.sourceOffset + bomLength - definitions.length,
304 };
305}
306
307/**
308 * The first definition of each label in a body, each on one line so it stands outside the quote or
309 * list it was written in, as the client's Markdown parser reads them.
310 */
311export type FindReferenceDefinitions = (body: string) => ReadonlyArray<string>;
312
313/** How much text the body's definitions may add across all the segments that lead with them. */
314const DEFINITIONS_MAX_ADDED_LENGTH = 256 * 1024;
315
316function segmentsWithReferences(segments: ReadonlyArray<PullRequestBodySegment>): number {
317 let count = 0;
318 for (const segment of segments) {
319 if (segment.kind === "markdown") count += segment.text.includes("[") ? 1 : 0;
320 else if (segment.kind === "table") {
321 for (const cells of segment.rows)
322 for (const cell of cells) count += segmentsWithReferences(cell.segments);
323 }
324 }
325 return count;
326}
327
328export function splitPullRequestBody(
329 body: string,
330 findDefinitions: FindReferenceDefinitions,
331): ReadonlyArray<PullRequestBodySegment> {
332 const segments = splitBodyAt(body, 0);
333 // One markdown segment is the whole body, which resolves its own references.
334 const whole = segments.length === 1 && segments[0]!.kind === "markdown";
335 if (whole || !body.includes("]:")) return segments;
336 const definitions = findDefinitions(body);
337 if (definitions.length === 0) return segments;
338 const leading = `${definitions.join("\n")}\n\n`;
339 // Past the budget the body renders as one document: its media stays links, its references resolve.
340 if (leading.length * segmentsWithReferences(segments) > DEFINITIONS_MAX_ADDED_LENGTH) {
341 const text = body.replace(/^(?:\r|\n)+/u, "");
342 return [
343 {
344 id: "markdown:0",
345 kind: "markdown",
346 text: text.trimEnd(),
347 sourceOffset: body.length - text.length,
348 },
349 ];
350 }
351 return segments.map((segment) => withDefinitions(segment, leading));
352}
353
354/** `baseOffset` is where `body` starts in the whole body, so a table cell's edits write back. */
355function splitBodyAt(body: string, baseOffset: number): ReadonlyArray<PullRequestBodySegment> {
356 const segments: PullRequestBodySegment[] = [];
357 const markdown: string[] = [];
358 let markdownStart = 0;
359 let openFence: {
360 readonly marker: string;
361 readonly flushLeft: boolean;
362 /** Columns of a list item the fence opened in; a less indented line ends the item and fence. */
363 readonly itemIndent: number;
364 } | null = null;
365 let openComment = false;
366
367 // Blank lines around a run are dropped, but never leading spaces: four of them open an
368 // indented code block, so trimming a run would silently turn code into prose.
369 const flushMarkdown = () => {
370 const joined = markdown.join("\n");
371 const text = joined.replace(/^(?:\r?\n)+/u, "");
372 const sourceOffset = markdownStart + joined.length - text.length;
373 markdown.length = 0;
374 if (text.trim().length > 0) {
375 segments.push({
376 id: `markdown:${segments.length}`,
377 kind: "markdown",
378 text: text.trimEnd(),
379 sourceOffset,
380 });
381 }
382 };
383
384 const lines = body.replace(/\r(?!\n)/gu, "\n").split("\n");
385 let tableScannedThrough = -1;
386 let lineStart = baseOffset;
387 for (let index = 0; index < lines.length; lineStart += lines[index]!.length + 1, index += 1) {
388 const line = lines[index]!;
389 if (markdown.length === 0) markdownStart = lineStart;
390 if (openComment) {
391 if (line.includes("-->")) {
392 openComment = false;
393 }
394 markdown.push(line);
395 continue;
396 }
397 if (
398 openFence !== null &&
399 openFence.itemIndent > 0 &&
400 line.trim() &&
401 indentColumns(line) < openFence.itemIndent
402 ) {
403 openFence = null;
404 }
405 const fenceMatch = FENCE_PATTERN.exec(line);
406 // ```` ```npm test``` ```` is a code span, not an opener that would flip every later fence.
407 // A span that runs past this line is left an opener, so its lines stay out of media.
408 const isInlineCode =
409 openFence === null &&
410 fenceMatch?.[1]![0] === "`" &&
411 (fenceMatch[2]!.match(/`+/gu) ?? []).some((run) => run.length === fenceMatch[1]!.length);
412 // A backtick fence's info string cannot hold a backtick; on a list marker that is item text.
413 const isListText =
414 openFence === null &&
415 fenceMatch?.[1]![0] === "`" &&
416 fenceMatch[2]!.includes("`") &&
417 LIST_ITEM_PATTERN.test(line);
418 if (fenceMatch !== null && !isInlineCode && !isListText) {
419 const fence = fenceMatch[1]!;
420 // A fence closes only on the same marker, at least as long as the one that opened it,
421 // and with nothing after it: `~~~` cannot end a ``` block, and ```` ```ts ```` is an
422 // info string opening a nested fence, not a close. Under a fence opened at the margin, an
423 // indented-code line is content too: a tab-indented ``` there is part of the example.
424 const closes =
425 openFence !== null &&
426 fence[0] === openFence.marker[0] &&
427 fence.length >= openFence.marker.length &&
428 fenceMatch[2]!.trim().length === 0 &&
429 !LIST_ITEM_PATTERN.test(line) &&
430 !(openFence.flushLeft && INDENTED_CODE_PATTERN.test(line)) &&
431 // A closer may sit at most three columns past its list item's content.
432 !(openFence.itemIndent > 0 && indentColumns(line) > openFence.itemIndent + 3);
433 if (openFence === null) {
434 openFence = {
435 marker: fence,
436 flushLeft: line.startsWith(fence),
437 itemIndent: LIST_ITEM_PATTERN.test(line) ? line.indexOf(fence) : 0,
438 };
439 } else if (closes) {
440 openFence = null;
441 }
442 markdown.push(line);
443 continue;
444 }
445 if (openFence !== null || INDENTED_CODE_PATTERN.test(line)) {
446 markdown.push(line);
447 continue;
448 }
449 if (HTML_COMMENT_START_PATTERN.test(line)) {
450 openComment = !line.includes("-->");
451 markdown.push(line);
452 continue;
453 }
454
455 if (index > tableScannedThrough && TABLE_START_PATTERN.test(line)) {
456 const table = mediaTableAt(lines, index, lineStart);
457 tableScannedThrough = table.end;
458 if (table.rows !== null) {
459 flushMarkdown();
460 segments.push({ id: `table:${segments.length}`, kind: "table", rows: table.rows });
461 for (; index < table.end; index += 1) lineStart += lines[index]!.length + 1;
462 continue;
463 }
464 }
465
466 const bareAttachment = attachmentFromLine(line);
467 if (bareAttachment !== null) {
468 flushMarkdown();
469 segments.push({ id: `attachment:${segments.length}`, kind: "attachment", ...bareAttachment });
470 continue;
471 }
472
473 if (!STANDALONE_VIDEO_TAG_PATTERN.test(line)) {
474 markdown.push(line);
475 continue;
476 }
477 const lastCandidate = Math.min(index + VIDEO_TAG_MAX_LINES, lines.length) - 1;
478 let cursor = index;
479 while (cursor < lastCandidate && !VIDEO_TAG_CLOSE_PATTERN.test(lines[cursor]!)) {
480 cursor += 1;
481 }
482 const source = VIDEO_TAG_END_PATTERN.test(lines[cursor]!)
483 ? videoTagSource(lines.slice(index, cursor + 1).join("\n"))
484 : undefined;
485 if (source !== undefined && webUrl(source) !== null) {
486 flushMarkdown();
487 segments.push({
488 id: `attachment:${segments.length}`,
489 kind: "attachment",
490 url: source,
491
492 media: "video",
493 });
494 for (; index < cursor; index += 1) lineStart += lines[index]!.length + 1;
495 } else {
496 // Unclosed, or nothing linkable in it: prose. Only this line is consumed, so the
497 // lines that were looked at are still parsed on their own terms.
498 markdown.push(line);
499 }
500 }
501
502 flushMarkdown();
503 return segments;
504}
505let githubEmojiByAlias: ReadonlyMap<string, string> | undefined;
506const githubEmojiAlias = /:([a-z\d_+-]+)(?=:)/gu;
507
508/** GitHub's `:alias:` emoji in `text`; a colon closes one alias only, so `:tada:tada:` has one. */
509export function githubEmojiAliases(
510 text: string,
511): ReadonlyArray<{ readonly index: number; readonly text: string; readonly emoji: string }> {
512 githubEmojiByAlias ??= new Map(
513 GITHUB_EMOJI_ALIASES.trim()
514 .split("\n")
515 .map((line) => {
516 const space = line.indexOf(" ");
517 return [line.slice(0, space), line.slice(space + 1)] as const;
518 }),
519 );
520 const found: { index: number; text: string; emoji: string }[] = [];
521 let end = 0;
522 for (const match of text.matchAll(githubEmojiAlias)) {
523 const emoji = githubEmojiByAlias.get(match[1]!);
524 if (emoji === undefined || match.index < end) continue;
525 end = match.index + match[0].length + 1;
526 found.push({ index: match.index, text: `${match[0]}:`, emoji });
527 }
528 return found;
529}
530
531export function expandGithubEmojiAliases(text: string): string {
532 let expanded = "";
533 let start = 0;
534 for (const alias of githubEmojiAliases(text)) {
535 expanded += text.slice(start, alias.index) + alias.emoji;
536 start = alias.index + alias.text.length;
537 }
538 return start === 0 ? text : expanded + text.slice(start);
539}