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

issueLinks.ts

189 lines7.2 KB

1import {
2 IssueTrackerKind,
3 issueTrackerBindingScopes,
4 type IssueRef,
5 type IssueTrackerConnectionList,
6 type RepositoryIdentity,
7} from "@t3tools/contracts";
8import {
9 LINEAR_HOST,
10 LINEAR_KIND,
11 parseLinearIssueUrl,
12} from "@t3tools/issue-tracker-linear/shared/issueUrl";
13​
14import { sourceControlClients } from "./sourceControlClients.ts";
15import type { EnvironmentProject } from "./state/shell.ts";
16​
17type LinkProject = Pick<EnvironmentProject, "id" | "environmentId" | "repositoryIdentity">;
18​
19const issueBindingsByRepository = new WeakMap<
20 RepositoryIdentity,
21 ReturnType<typeof sourceControlClients.issueBindings>
22>();
23​
24/** The hosts and scopes a project's git-host tracker is bound to, the way the server resolves them. */
25function projectIssueBindings(project: LinkProject) {
26 const identity = project.repositoryIdentity;
27 if (identity == null) return [];
28 const cached = issueBindingsByRepository.get(identity);
29 if (cached !== undefined) return cached;
30 const bindings = sourceControlClients
31 .issueBindings(identity)
32 .map((binding) => ({ ...binding, scope: binding.scope.toLowerCase() }));
33 issueBindingsByRepository.set(identity, bindings);
34 return bindings;
36​
37function linkAuthority(url: string): string | null {
38 try {
39 return new URL(url).host.toLowerCase();
40 } catch {
41 return null;
42 }
44​
45/** A host whose hostname does not name it, such as GitHub Enterprise Server, is vouched for by a project on it. */
46function parseIssueLink(
47 url: string,
48 authority: string | null,
49 projects: ReadonlyArray<LinkProject>,
50) {
51 const parsed = sourceControlClients.parseIssueUrl(url);
52 if (parsed !== null || authority === null) return parsed;
53 const hostname = new URL(url).hostname.toLowerCase();
54 for (const project of projects) {
55 const bindings = projectIssueBindings(project);
56 if (!bindings.some((binding) => binding.host === hostname || binding.host === authority))
57 continue;
58 const known = sourceControlClients.parseIssueUrl(url, project.repositoryIdentity?.provider);
59 if (known !== null) return known;
60 }
61 return null;
63​
64function parseStandaloneIssueLink(url: string) {
65 try {
66 const link = parseLinearIssueUrl(new URL(url));
67 return link === null ? null : { tracker: LINEAR_KIND, link };
68 } catch {
69 return null;
70 }
72​
73/** Whether `url` is a standalone tracker's issue link, which only bindings can resolve. */
74export function isStandaloneIssueLink(url: string): boolean {
75 return parseStandaloneIssueLink(url) !== null;
77​
78/** A cheap pre-check, so text without such a link never asks for the bindings. */
79export function mayContainStandaloneIssueLink(text: string): boolean {
80 return text.includes(`${LINEAR_HOST}/`);
82​
83/**
84 * A standalone tracker link resolves through the project bound to its scope, else any bound to
85 * the tracker, and only through an account whose credential reaches the workspace it names: team
86 * keys repeat across workspaces, so a link elsewhere stays an ordinary link.
87 */
88function resolveStandaloneIssueLink<Project extends LinkProject>(
89 url: string,
90 projects: ReadonlyArray<Project>,
91 trackers: IssueTrackerConnectionList | undefined,
92 preferredProjectId: string | undefined,
93): { readonly project: Project; readonly ref: IssueRef } | null {
94 const parsed = trackers === undefined ? null : parseStandaloneIssueLink(url);
95 if (parsed === null || trackers === undefined) return null;
96 const { tracker, link } = parsed;
97 const accounts = new Set(
98 [...trackers.trackers, ...(trackers.accounts ?? [])]
99 .filter(
100 (connection) =>
101 connection.tracker === tracker &&
102 connection.account !== null &&
103 connection.workspace?.toLowerCase() === link.workspace.toLowerCase(),
104 )
105 .map((connection) => connection.accountId ?? null),
106 );
107 if (accounts.size === 0) return null;
108 const bindings = { ...trackers.bindings, ...trackers.accountBindings };
109 const onTracker = projects.flatMap((project) => {
110 const binding = bindings[project.id];
111 return binding?.tracker === tracker && accounts.has(binding.accountId ?? null)
112 ? [{ project, binding }]
113 : [];
114 });
115 const preferFirst = (candidates: typeof onTracker) =>
116 candidates.find((candidate) => candidate.project.id === preferredProjectId) ?? candidates[0];
117 const scope = link.scope.toLowerCase();
118 const boundScope = (candidate: (typeof onTracker)[number]) =>
119 issueTrackerBindingScopes(candidate.binding).find((key) => key.toLowerCase() === scope);
120 const own = preferFirst(onTracker.filter((candidate) => boundScope(candidate) !== undefined));
121 const lender = own ?? preferFirst(onTracker);
122 if (lender === undefined) return null;
123 return {
124 project: lender.project,
125 ref: {
126 projectId: lender.project.id,
127 tracker: lender.binding.tracker,
128 host: link.host,
129 scope: (own && boundScope(own)) ?? link.scope,
130 key: link.key,
131 },
132 };
134​
135/**
136 * The reference an issue link resolves to, and the project it is read through: the project whose
137 * tracker binding is that host and scope, else any project on the same tracker and host lending
138 * its credentials for a read-only view. The same rule as the server's `IssueService.resolveUrl`,
139 * applied on the client so a lookalike hostname matches no project and stays an ordinary link.
140 */
141export function resolveIssueLinkTarget<Project extends LinkProject>(input: {
142 readonly url: string;
143 /** The projects of the environment the link is read in. */
144 readonly projects: ReadonlyArray<Project>;
145 readonly preferredProjectId?: string | undefined;
146 /** The environment's standalone trackers and bindings; without them only git-host links resolve. */
147 readonly trackers?: IssueTrackerConnectionList | undefined;
148}): { readonly project: Project; readonly ref: IssueRef } | null {
149 // A link names its server's port; a binding does only when its remote or web URL did.
150 const authority = linkAuthority(input.url);
151 const parsed = parseIssueLink(input.url, authority, input.projects);
152 if (parsed === null)
153 return resolveStandaloneIssueLink(
154 input.url,
155 input.projects,
156 input.trackers,
157 input.preferredProjectId,
158 );
159 const { definition, link } = parsed;
160 const onHost = input.projects.flatMap((project) =>
161 projectIssueBindings(project)
162 .filter(
163 (binding) =>
164 binding.tracker === definition.kind &&
165 (binding.host === link.host || binding.host === authority),
166 )
167 .map((binding) => ({ project, binding })),
168 );
169 const onAuthority = onHost.filter((candidate) => candidate.binding.host === authority);
170 const bound = onAuthority.length > 0 ? onAuthority : onHost;
171 const preferFirst = (candidates: typeof bound) =>
172 candidates.find((candidate) => candidate.project.id === input.preferredProjectId) ??
173 candidates[0];
174 const own =
175 preferFirst(bound.filter((candidate) => candidate.binding.scope === link.scope)) ??
176 preferFirst(bound.filter((candidate) => candidate.binding.scope === link.scopeAlias));
177 const lender = own ?? preferFirst(bound);
178 if (lender === undefined) return null;
179 return {
180 project: lender.project,
181 ref: {
182 projectId: lender.project.id,
183 tracker: IssueTrackerKind.make(lender.binding.tracker),
184 host: lender.binding.host,
185 scope: own === undefined ? link.scope : lender.binding.scope,
186 key: link.key,
187 },
188 };