Open History to see the last commit
1import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown";
2import {
3 sourceControlClients,
4 type ReferenceAutolink,
5} from "@t3tools/client-runtime/source-control-clients";
6import type { PluggableList } from "unified";
7
8export {
9 splitPullRequestBody,
10 type PullRequestBodySegment,
11} from "@t3tools/client-runtime/pull-request-markdown";
12
13type MarkdownNode = {
14 type: string;
15 value?: string;
16 children?: MarkdownNode[];
17 url?: string;
18 data?: unknown;
19};
20
21const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]);
22
23export function remarkPullRequestAutolinks(options: {
24 readonly autolinks: (text: string) => ReadonlyArray<ReferenceAutolink>;
25}) {
26 const visit = (node: MarkdownNode): void => {
27 const children = node.children;
28 if (children === undefined) return;
29 for (let index = 0; index < children.length; index += 1) {
30 const child = children[index]!;
31 if (AUTOLINK_IGNORED_TYPES.has(child.type)) continue;
32 if (child.type !== "text" || child.value === undefined) {
33 visit(child);
34 continue;
35 }
36 const value = child.value;
37 const links = options.autolinks(value);
38 if (links.length === 0) continue;
39 const replacements: MarkdownNode[] = [];
40 let start = 0;
41 for (const link of links) {
42 if (start < link.index) {
43 replacements.push({ type: "text", value: value.slice(start, link.index) });
44 }
45 replacements.push({
46 type: "link",
47 url: link.url,
48 data: { hProperties: { dataPullRequestAutolink: link.kind } },
49 children: [{ type: "text", value: link.label }],
50 });
51 start = link.index + link.text.length;
52 }
53 if (start < value.length) replacements.push({ type: "text", value: value.slice(start) });
54 children.splice(index, 1, ...replacements);
55 index += replacements.length - 1;
56 }
57 };
58 return (tree: MarkdownNode) => visit(tree);
59}
60
61const NO_AUTOLINK_PLUGINS: PluggableList = [];
62const autolinkPlugins = new Map<string, PluggableList>();
63
64/**
65 * One plugin list per repository, so every comment of a pull request shares one markdown
66 * renderer and its parse cache instead of parsing again on each render.
67 */
68export function pullRequestAutolinkPlugins(
69 changeRequest: { readonly provider: string; readonly url: string } | null,
70): PluggableList {
71 if (changeRequest === null) return NO_AUTOLINK_PLUGINS;
72 const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link
73 .repositoryUrl;
74 if (repositoryUrl === undefined) return NO_AUTOLINK_PLUGINS;
75 const key = `${changeRequest.provider}\u0000${repositoryUrl}`;
76 let plugins = autolinkPlugins.get(key);
77 if (plugins === undefined) {
78 const autolinks = changeRequestReferenceAutolinker(changeRequest);
79 plugins = autolinks ? [[remarkPullRequestAutolinks, { autolinks }]] : NO_AUTOLINK_PLUGINS;
80 autolinkPlugins.set(key, plugins);
81 }
82 return plugins;
83}