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

openPullRequestLink.ts

331 lines13.7 KB

1import type {
2 EnvironmentId,
3 LocalApi,
4 ScopedThreadRef,
5 ThreadLinkedPullRequest,
6} from "@t3tools/contracts";
7import { useNavigate } from "@tanstack/react-router";
8import * as Schema from "effect/Schema";
9import { type MouseEvent, useCallback } from "react";
10​
11import { pullRequestHostOf, type SourceControlProviderKind } from "@t3tools/contracts";
12​
13import { stackedThreadToast, toastManager } from "../components/ui/toast";
14import { readLocalApi } from "../localApi";
15import { useRightPanelStore } from "../rightPanelStore";
16import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
17​
18import { useProjects, useServerConfigs } from "../state/entities";
19import { usePrimaryEnvironmentId } from "../state/environments";
20​
21export class PullRequestLinkOpenError extends Schema.TaggedErrorClass<PullRequestLinkOpenError>()(
22 "PullRequestLinkOpenError",
23 {
24 targetOrigin: Schema.NullOr(Schema.String),
25 cause: Schema.Defect(),
26 },
27) {
28 static fromCause(targetUrl: string, cause: unknown): PullRequestLinkOpenError {
29 let targetOrigin: string | null = null;
30 try {
31 targetOrigin = new URL(targetUrl).origin;
32 } catch {
33 // Keep malformed URLs out of diagnostics while preserving the open failure below.
34 }
35 return new PullRequestLinkOpenError({ targetOrigin, cause });
36 }
37​
38 override get message(): string {
39 return this.targetOrigin === null
40 ? "Unable to open pull request link."
41 : `Unable to open pull request link at ${this.targetOrigin}.`;
42 }
44​
45export async function openPullRequestLink(
46 shell: Pick<LocalApi["shell"], "openExternal">,
47 targetUrl: string,
48): Promise<void> {
49 try {
50 await shell.openExternal(targetUrl);
51 } catch (cause) {
52 throw PullRequestLinkOpenError.fromCause(targetUrl, cause);
53 }
55​
56/**
57 * A change request the page can open, named the way the page names one: the host below which the
58 * repository is addressed, the repository path as that host writes it, and the number.
59 *
60 * The two strings are what `pullRequestHostOf` and the project's `repositoryIdentity` produce
61 * from a git remote — lower case, no port, the full path below the host — because the page matches
62 * a link against those. Anything else opens nothing.
63 */
64export interface ChangeRequestLink {
65 readonly host: string;
66 readonly repository: string;
67 readonly number: number;
69​
70/** The host itself, one of its subdomains, or an install named after the provider. */
71function isHostOf(hostname: string, apex: string, label?: string): boolean {
72 if (hostname === apex || hostname.endsWith(`.${apex}`)) return true;
73 return label !== undefined && hostname.startsWith(`${label}.`);
75​
76/**
77 * The repository and number behind a change request URL on a host the page can read, or null for
78 * anything else — an issue, a commit, a repository root, a host this cannot tell apart from an
79 * ordinary link. Null means the system browser, so a doubtful match is worse than no match: it
80 * takes the reader out of their browser and into a page that cannot find the change request.
81 *
82 * Each host is recognised by the path shape it alone uses, guarded by a hostname it could
83 * plausibly be served from, since self-hosted installs are named whatever their admin chose:
84 * GitLab's `/-/` marker is unique enough to trust on any hostname, while `/pull/` is generic
85 * enough that it is only believed from a GitHub-ish host.
86 */
87export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | null {
88 let url: URL;
89 try {
90 url = new URL(targetUrl);
91 } catch {
92 return null;
93 }
94 // `javascript:`, `mailto:` and friends have no host to speak of and nothing to open.
95 if (url.protocol !== "https:" && url.protocol !== "http:") return null;
96 // Nothing here tries to tell a lookalike hostname from a real one — `github.com.evil.test`,
97 // `github.com-evil.test` and the rest are an open set, and blocking spellings of it costs real
98 // hosts (`gitlab.com.br` is a registrable domain, not a disguise). What a claim is worth is
99 // decided where it is used: only a link matching a repository this workspace has checked out
100 // opens the page, and everything else stays the ordinary link it was.
101 const host = url.hostname.toLowerCase();
102​
103 // GitHub, and any Enterprise install: /{owner}/{repo}/pull/{n}
104 if (isHostOf(host, "github.com", "github")) {
105 const match = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u.exec(url.pathname);
106 return claim(host, match);
107 }
108 // GitLab, self-hosted included: /{group}/[{subgroup}/...]{repo}/-/merge_requests/{n}. The `/-/`
109 // separator is GitLab's own, so the hostname is not asked about.
110 const gitlab = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
111 if (gitlab) return claim(host, gitlab);
112 // Bitbucket Cloud: /{workspace}/{repo}/pull-requests/{n}
113 if (isHostOf(host, "bitbucket.org", "bitbucket")) {
114 const match = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u.exec(url.pathname);
115 return claim(host, match);
116 }
117 // Azure DevOps, both the current host and the per-organisation one it replaced. `_git` is part
118 // of the repository path there, as it is in the remote URL the identity is read from.
119 if (isHostOf(host, "dev.azure.com") || host.endsWith(".visualstudio.com")) {
120 const match = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u.exec(url.pathname);
121 return claim(host, match);
122 }
123 return null;
125​
126/** Match a stored PR without requiring its project to remain available. */
127export function matchesLinkedPullRequestUrl(
128 linkedPullRequest: ThreadLinkedPullRequest,
129 targetUrl: string,
130): boolean {
131 const linked = parseChangeRequestUrl(linkedPullRequest.url);
132 const target = parseChangeRequestUrl(targetUrl);
133 return (
134 linked !== null &&
135 target !== null &&
136 linked.host === target.host &&
137 linked.repository === target.repository &&
138 linked.number === target.number
139 );
141​
142/** The repository root behind a recognised change-request URL, without PR-specific state. */
143export function changeRequestRepositoryUrl(targetUrl: string): string | null {
144 const changeRequest = parseChangeRequestUrl(targetUrl);
145 if (changeRequest === null) return null;
146 const url = new URL(targetUrl);
147 const repositoryPath =
148 /^(.*?)\/-\/merge_requests\/\d+(?:\/|$)/iu.exec(url.pathname)?.[1] ??
149 /^(.*?)(?:\/pull\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(
150 url.pathname,
151 )?.[1];
152 if (!repositoryPath) return null;
153 url.pathname = repositoryPath;
154 url.search = "";
155 url.hash = "";
156 return url.toString();
158​
159function claim(host: string, match: RegExpExecArray | null): ChangeRequestLink | null {
160 const repository = match?.[1];
161 const number = Number(match?.[2]);
162 return repository && Number.isSafeInteger(number) && number > 0
163 ? { host, repository: repository.toLowerCase(), number }
164 : null;
166​
167/**
168 * Returns a click handler that opens a pull request URL in the system browser.
169 *
170 * Stops event propagation/default so activating the link does not also trigger
171 * an enclosing row or trigger (e.g. opening the branch dropdown), and surfaces a
172 * toast when the local API is unavailable or the open fails.
173 */
174/**
175 * The project a link belongs to, or nothing. Matched the way the server matches: the repository
176 * identity is the full path below the host where one was recorded — which is what nested GitLab
177 * groups and Azure project paths need — and the host is the first segment of the canonical
178 * remote, so github.com and an Enterprise install stay apart.
179 */
180export function findProjectForChangeRequest(
181 projects: ReadonlyArray<EnvironmentProject>,
182 link: ChangeRequestLink,
183): EnvironmentProject | undefined {
184 return projects.find((project) => {
185 const identity = project.repositoryIdentity;
186 if (!identity) return false;
187 const kind = identity.provider as SourceControlProviderKind | undefined;
188 if (kind === undefined) return false;
189 const repository =
190 identity.displayName ??
191 (identity.owner && identity.name ? `${identity.owner}/${identity.name}` : null);
192 return (
193 repository !== null &&
194 repository.toLowerCase() === link.repository.toLowerCase() &&
195 pullRequestHostOf(identity, kind) === link.host.toLowerCase()
196 );
197 });
199​
200/**
201 * Opens a change request link on the page, and says whether it did. Anything else — another
202 * organisation's repository, a host nothing here is checked out from, a link that merely looks
203 * like one — is left alone for the caller to handle as the ordinary link it is.
204 *
205 * Resolving the project here rather than on the page is what makes recognising a URL safe: a
206 * lookalike hostname matches no project and stays a link, and the page is handed the project
207 * rather than a host to narrow its whole list by.
208 *
209 * Given a thread, the link opens beside it in the right panel instead of taking the whole app to
210 * the pull requests page: a reader following a link the agent wrote is reading the thread, and
211 * should still be reading it afterwards. Any change request opens there, not only the thread's
212 * own, since the panel is told which one to show.
213 */
214export function shouldOpenPullRequestExternally(
215 event: Pick<MouseEvent<HTMLElement>, "metaKey" | "ctrlKey">,
216): boolean {
217 return event.metaKey || event.ctrlKey;
219​
220export function useOpenChangeRequestLink(
221 threadRef?: ScopedThreadRef,
222): (
223 event: Pick<
224 MouseEvent<HTMLElement>,
225 "preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey"
226 >,
227 targetUrl: string,
228 targetThreadRef?: ScopedThreadRef,
229) => boolean {
230 const navigate = useNavigate();
231 const allProjects = useProjects();
232 const serverConfigs = useServerConfigs();
233 const primaryEnvironmentId = usePrimaryEnvironmentId();
234 return useCallback(
235 (event, targetUrl, targetThreadRef) => {
236 if (shouldOpenPullRequestExternally(event)) return false;
237 const resolvedThreadRef = targetThreadRef ?? threadRef;
238 const parsed = parseChangeRequestUrl(targetUrl);
239 if (parsed === null) return false;
240 const reads = (environmentId: string) =>
241 serverConfigs.get(environmentId as EnvironmentId)?.environment.capabilities.pullRequests ===
242 true;
243 // Beside a thread the panel reads on that thread's environment, so a project from another
244 // one could not be read there whatever its remote says: two environments can hold the same
245 // repository, and handing the panel the wrong one's id opens a surface that never loads.
246 //
247 // The page has no such tie — it lists every server at once — so the link is resolved
248 // against all of them, the primary first where two hold the same repository.
249 const projects = resolvedThreadRef
250 ? allProjects.filter((project) => project.environmentId === resolvedThreadRef.environmentId)
251 : allProjects
252 .filter((project) => reads(project.environmentId))
253 .toSorted(
254 (left, right) =>
255 Number(right.environmentId === primaryEnvironmentId) -
256 Number(left.environmentId === primaryEnvironmentId),
257 );
258 const project = findProjectForChangeRequest(projects, parsed);
259 if (project === undefined || !reads(project.environmentId)) return false;
260 event.preventDefault();
261 event.stopPropagation();
262 if (resolvedThreadRef) {
263 useRightPanelStore.getState().openPullRequest(resolvedThreadRef, {
264 projectId: project.id,
265 // The identity's own spelling, not the one read out of the URL: the panel asks the
266 // provider for this repository, while matching a link only ever compares lower case.
267 repository: project.repositoryIdentity?.displayName ?? parsed.repository,
268 number: parsed.number,
269 });
270 return true;
271 }
272 void navigate({
273 to: "/pull-requests",
274 search: {
275 involvement: "all",
276 // Every state, so the pull request being opened is also in the list behind it whether
277 // it is open, merged or closed.
278 state: "all",
279 repository: parsed.repository,
280 number: parsed.number,
281 selectedProjectId: project.id,
282 // Named so the page opens the right one of two servers holding this project.
283 selectedEnvironmentId: project.environmentId,
284 },
285 });
286 return true;
287 },
288 [allProjects, navigate, primaryEnvironmentId, serverConfigs, threadRef],
289 );
291​
292export function useOpenPrLink(threadRef?: ScopedThreadRef) {
293 const openChangeRequest = useOpenChangeRequestLink(threadRef);
294 return useCallback(
295 (event: MouseEvent<HTMLElement>, prUrl: string, targetThreadRef?: ScopedThreadRef) => {
296 event.stopPropagation();
297 const openInBrowser = shouldOpenPullRequestExternally(event);
298 const isAnchor =
299 event.currentTarget instanceof HTMLAnchorElement && event.currentTarget.href.length > 0;
300 // A real link already knows how to cmd/ctrl+click. Leave its default
301 // action alone so the browser (or Electron's window-open handler) opens
302 // the host. Buttons have no href, so they still go through openExternal.
303 if (openInBrowser && isAnchor) return false;
304​
305 event.preventDefault();
306 if (!openInBrowser && openChangeRequest(event, prUrl, targetThreadRef)) return true;
307​
308 const api = readLocalApi();
309 if (!api) {
310 toastManager.add({
311 type: "error",
312 title: "Link opening is unavailable.",
313 });
314 return false;
315 }
316​
317 void openPullRequestLink(api.shell, prUrl).catch((error) => {
318 console.error(error);
319 toastManager.add(
320 stackedThreadToast({
321 type: "error",
322 title: "Unable to open pull request link",
323 description: error instanceof Error ? error.message : "An error occurred.",
324 }),
325 );
326 });
327 return false;
328 },
329 [openChangeRequest],
330 );