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

pullRequestMarkdown.logic.ts

143 lines5.8 KB

1/** `id` is positional on purpose: the same attachment can be embedded twice in one body. */
2export type PullRequestBodySegment =
3 | { readonly id: string; readonly kind: "markdown"; readonly text: string }
4 | {
5 readonly id: string;
6 readonly kind: "attachment";
7 readonly url: string;
8 /**
9 * What the reader can be told the upload is. The uuid says nothing on its own — the type
10 * only appears in the signed redirect GitHub answers with — but the shape does: GitHub
11 * writes a dropped image into the body as an `<img>` tag, so a bare attachment link on its
12 * own line is what it does with a video. Anything else keeps the neutral name.
13 */
14 readonly media: "video" | "unknown";
15 };
16​
17const FENCE_PATTERN = /^\s{0,3}((?:`{3,})|(?:~{3,}))(.*)$/u;
18/**
19 * How far a `<video>` tag may reach for its closing tag. Real embeds are one to three lines,
20 * and the bound keeps an unclosed tag from making each one rescan the rest of the body.
21 */
22const VIDEO_TAG_MAX_LINES = 8;
23/** Four spaces open an indented code block, so its contents stay verbatim markdown. */
24const INDENTED_CODE_PATTERN = /^(?: {4}|\t)/u;
25const BARE_URL_PATTERN = /^<?(https?:\/\/\S+?)>?$/u;
26const VIDEO_EXTENSION_PATTERN = /\.(?:mp4|webm|mov|m4v|ogv)(?:$|[?#])/iu;
27/** A dropped video becomes a bare asset link; a dropped image becomes an `<img>` tag. */
28const GITHUB_ASSET_PATTERN = /^https:\/\/github\.com\/user-attachments\/assets\/[\w-]+$/iu;
29const VIDEO_TAG_SRC_PATTERN = /<(?:video|source)\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/iu;
30/** Only a tag that owns its line is an embed; inline, it is prose the renderer should keep. */
31const STANDALONE_VIDEO_TAG_PATTERN = /^\s*<video\b/iu;
32const VIDEO_TAG_END_PATTERN = /<\/video>\s*$/iu;
33​
34/** Anything else — `javascript:`, `data:`, a relative path — is not an upload to link out to. */
35function isWebUrl(url: string): boolean {
36 try {
37 const parsed = new URL(url);
38 return parsed.protocol === "https:" || parsed.protocol === "http:";
39 } catch {
40 return false;
41 }
43​
44function attachmentFromLine(line: string): { url: string; media: "video" | "unknown" } | null {
45 const url = BARE_URL_PATTERN.exec(line.trim())?.[1];
46 if (url === undefined || !isWebUrl(url)) return null;
47 if (VIDEO_EXTENSION_PATTERN.test(url) || GITHUB_ASSET_PATTERN.test(url)) {
48 return { url, media: "video" };
49 }
50 return null;
52​
53/**
54 * Splits a pull request body into markdown runs and the uploads embedded in it, which the
55 * markdown renderer drops: `<video>` is not in its sanitizer's schema, and a bare attachment
56 * link arrives as prose. Two shapes are recognised, both of which GitHub produces itself: a
57 * `<video>` (or `<source>`) tag, and a bare link on its own line to a video file or an
58 * uploaded attachment. Fenced code is copied through untouched so a snippet that happens to
59 * contain a link is never lifted out of it.
60 */
61export function splitPullRequestBody(body: string): ReadonlyArray<PullRequestBodySegment> {
62 const segments: PullRequestBodySegment[] = [];
63 const markdown: string[] = [];
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 text = markdown.join("\n").replace(/^\n+/u, "").replace(/\s+$/u, "");
70 markdown.length = 0;
71 if (text.trim().length > 0) {
72 segments.push({ id: `markdown:${segments.length}`, kind: "markdown", text });
73 }
74 };
75​
76 const lines = body.split("\n");
77 for (let index = 0; index < lines.length; index += 1) {
78 const line = lines[index]!;
79 const fenceMatch = FENCE_PATTERN.exec(line);
80 if (fenceMatch !== null) {
81 const fence = fenceMatch[1]!;
82 // A fence closes only on the same marker, at least as long as the one that opened it,
83 // and with nothing after it: `~~~` cannot end a ``` block, and ```` ```ts ```` is an
84 // info string opening a nested fence, not a close.
85 const closes =
86 openFence !== null &&
87 fence[0] === openFence[0] &&
88 fence.length >= openFence.length &&
89 fenceMatch[2]!.trim().length === 0;
90 if (openFence === null) {
91 openFence = fence;
92 } else if (closes) {
93 openFence = null;
94 }
95 markdown.push(line);
96 continue;
97 }
98 if (openFence !== null || INDENTED_CODE_PATTERN.test(line)) {
99 markdown.push(line);
100 continue;
101 }
102​
103 const bareAttachment = attachmentFromLine(line);
104 if (bareAttachment !== null) {
105 flushMarkdown();
106 segments.push({ id: `attachment:${segments.length}`, kind: "attachment", ...bareAttachment });
107 continue;
108 }
109​
110 if (!STANDALONE_VIDEO_TAG_PATTERN.test(line)) {
111 markdown.push(line);
112 continue;
113 }
114 // A tag can span lines, so look ahead for its close — bounded, and without building the
115 // joined text until one is actually found.
116 const lastCandidate = Math.min(index + VIDEO_TAG_MAX_LINES, lines.length) - 1;
117 let cursor = index;
118 while (cursor < lastCandidate && !VIDEO_TAG_END_PATTERN.test(lines[cursor]!)) {
119 cursor += 1;
120 }
121 const source = VIDEO_TAG_END_PATTERN.test(lines[cursor]!)
122 ? VIDEO_TAG_SRC_PATTERN.exec(lines.slice(index, cursor + 1).join("\n"))?.[1]
123 : undefined;
124 if (source !== undefined && isWebUrl(source)) {
125 flushMarkdown();
126 segments.push({
127 id: `attachment:${segments.length}`,
128 kind: "attachment",
129 url: source,
130 // The author wrote the tag, so this one is a video whatever the URL looks like.
131 media: "video",
132 });
133 index = cursor;
134 } else {
135 // Unclosed, or nothing linkable in it: prose. Only this line is consumed, so the
136 // lines that were looked at are still parsed on their own terms.
137 markdown.push(line);
138 }
139 }
140​
141 flushMarkdown();
142 return segments;