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