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

openPullRequestLink.ts

389 lines15.9 KB

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