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

threadPullRequests.ts

347 lines13.4 KB

1import type {
2 RepositoryIdentity,
3 SourceControlProviderKind,
4 ThreadLinkedPullRequest,
5 ThreadPullRequestKey,
6 ThreadPullRequestLink,
7} from "@t3tools/contracts";
8​
9import { pullRequestHostOf } from "@t3tools/contracts";
10import { parseChangeRequestUrl } from "./changeRequestUrl.ts";
11import { canonicalRepositoryKey, sourceControlRepositorySelector } from "./sourceControl.ts";
12​
13type ThreadPullRequestKeySource = ThreadPullRequestKey & {
14 readonly authority?: string;
15 readonly url?: string;
16};
17​
18/** Normalize stored links, recovering Forgejo HTTP ports from old links' URLs. */
19export function normalizeThreadPullRequestKey(
20 key: ThreadPullRequestKeySource,
21): ThreadPullRequestKey {
22 const parsed = key.url === undefined ? null : parseChangeRequestUrl(key.url);
23 const authority =
24 key.authority ??
25 (parsed?.repository === key.repository.trim().toLowerCase() && parsed.number === key.number
26 ? parsed.authority
27 : undefined);
28 const canonical = canonicalRepositoryKey(
29 `${(authority ?? key.host).trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,
30 );
31 const separator = canonical.indexOf("/");
32 return {
33 host: canonical.slice(0, separator),
34 repository: canonical.slice(separator + 1),
35 number: key.number,
36 };
38​
39/** Legacy Azure selectors omit the organization and project; recover those from the PR URL. */
40export function legacyThreadPullRequestKey(
41 linked: Pick<ThreadLinkedPullRequest, "repository" | "number" | "url">,
42 fallbackHost?: string,
43): ThreadPullRequestKey {
44 const parsed = parseChangeRequestUrl(linked.url);
45 if (parsed !== null && parsed.number === linked.number) {
46 const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);
47 if (parsed.authority !== undefined || canonical.startsWith("dev.azure.com/")) {
48 return normalizeThreadPullRequestKey(parsed);
49 }
50 }
51 let host = fallbackHost;
52 if (host === undefined) {
53 try {
54 host = new URL(linked.url).hostname;
55 } catch {
56 host = "unknown";
57 }
58 }
59 return {
60 host: host.trim().toLowerCase() || "unknown",
61 repository: linked.repository.trim().toLowerCase(),
62 number: linked.number,
63 };
65​
66/** Identity comparison for links: host-level, case-insensitive on host and repository. */
67export function threadPullRequestKeysEqual(
68 left: ThreadPullRequestKeySource,
69 right: ThreadPullRequestKeySource,
70): boolean {
71 return threadPullRequestKeyOf(left) === threadPullRequestKeyOf(right);
73​
74export function threadPullRequestKeyOf(key: ThreadPullRequestKeySource): string {
75 const normalized = normalizeThreadPullRequestKey(key);
76 return `${normalized.host}/${normalized.repository}#${normalized.number}`;
78​
79/** Links a user should see. Tombstoned stack members stay in the array only so the
80 * sync reactor does not re-add them. */
81export function visibleThreadPullRequests(
82 links: ReadonlyArray<ThreadPullRequestLink>,
83): ReadonlyArray<ThreadPullRequestLink> {
84 return links.filter((link) => link.source !== "stack-dismissed");
86​
87function isOpen(link: ThreadPullRequestLink): boolean {
88 // Unsynced links are treated as open: they were just linked, and hiding them
89 // behind a terminal PR until the first sync would make the link look lost.
90 return link.snapshot === null || link.snapshot.state === "open";
92​
93function latestUpdatedAt(link: ThreadPullRequestLink): number {
94 const value = link.snapshot?.updatedAt ?? link.linkedAt;
95 const ms = Date.parse(value);
96 return Number.isNaN(ms) ? 0 : ms;
98​
99/** The single pull request a one-slot surface (sidebar badge, tab icon, copy link) shows. */
100export type ThreadCurrentPullRequest =
101 | { readonly kind: "single"; readonly link: ThreadPullRequestLink }
102 | {
103 readonly kind: "stack";
104 readonly open: ReadonlyArray<ThreadPullRequestLink>;
105 /** Highest layer of the open set; the one "View PR" and copy-link target. */
106 readonly top: ThreadPullRequestLink;
107 };
108​
109/**
110 * Prefer open work and the highest open layer within a chain. A completed chain still
111 * points at its top; unrelated terminal links use the most recently updated request.
112 */
113export function resolveThreadCurrentPullRequest(
114 links: ReadonlyArray<ThreadPullRequestLink>,
115): ThreadCurrentPullRequest | null {
116 const visible = visibleThreadPullRequests(links);
117 if (visible.length === 0) return null;
118 const open = visible.filter(isOpen);
119 if (open.length === 1) return { kind: "single", link: open[0]! };
120 const chains = resolveThreadPullRequestChains(visible);
121 if (open.length > 1) {
122 // `.reverse()` on a copy, not `.toReversed()`: this runs on Hermes, which has no ES2023
123 // array methods, and a TypeError here is fatal on every mobile launch that renders a stack.
124 const openChains = chains
125 .map((chain) => [...chain.layers].reverse().filter(isOpen))
126 .filter((layers) => layers.length > 0)
127 .sort(
128 (left, right) =>
129 Math.max(...right.map((link) => Date.parse(link.linkedAt))) -
130 Math.max(...left.map((link) => Date.parse(link.linkedAt))),
131 );
132 const ordered = openChains.flat();
133 return { kind: "stack", open: ordered, top: ordered[0]! };
134 }
135 if (chains.length === 1) {
136 return { kind: "single", link: chains[0]!.layers.at(-1)! };
137 }
138 const terminal = [...visible].sort(
139 (left, right) => latestUpdatedAt(right) - latestUpdatedAt(left),
140 );
141 return { kind: "single", link: terminal[0]! };
143​
144/** The one link a legacy `linkedPullRequest` consumer should see, or null. */
145export function resolveThreadCurrentPullRequestLink(
146 links: ReadonlyArray<ThreadPullRequestLink>,
147): ThreadPullRequestLink | null {
148 const current = resolveThreadCurrentPullRequest(links);
149 if (current === null) return null;
150 return current.kind === "single" ? current.link : current.top;
152​
153/** Legacy clients can only route links belonging to the thread's own repository. */
154export function legacyLinkedPullRequestOf(
155 links: ReadonlyArray<ThreadPullRequestLink>,
156 projectId: ThreadLinkedPullRequest["projectId"],
157 identity: RepositoryIdentity | null | undefined,
158): ThreadLinkedPullRequest | null {
159 if (!identity) return null;
160 // A local-path remote has no host segment and no provider, so there is no host to match.
161 const host = pullRequestHostOf(identity, identity.provider as SourceControlProviderKind);
162 if (typeof host !== "string") return null;
163 const repository = sourceControlRepositorySelector(identity);
164 if (repository === null) return null;
165 const azureKey =
166 identity.provider === "azure-devops"
167 ? canonicalRepositoryKey(identity.canonicalKey.toLowerCase())
168 : null;
169 const link = resolveThreadCurrentPullRequestLink(
170 links.filter((link) => {
171 if (azureKey !== null) {
172 const key = legacyThreadPullRequestKey(link, link.host);
173 return canonicalRepositoryKey(`${key.host}/${key.repository}`) === azureKey;
174 }
175 const parsed = parseChangeRequestUrl(link.url);
176 if (parsed?.authority !== undefined) {
177 try {
178 const remote = new URL(identity.locator.remoteUrl);
179 if (remote.protocol === "http:" || remote.protocol === "https:") {
180 return (
181 parsed.authority === remote.host && parsed.repository === repository.toLowerCase()
182 );
183 }
184 } catch {
185 // SSH web ports are resolved by the provider's configured login.
186 }
187 return parsed.host === host && parsed.repository === repository.toLowerCase();
188 }
189 return (
190 link.host.toLowerCase() === host.toLowerCase() &&
191 link.repository.toLowerCase() === repository.toLowerCase()
192 );
193 }),
194 );
195 if (link === null) return null;
196 return {
197 projectId,
198 repository: azureKey === null ? link.repository : repository,
199 number: link.number,
200 url: link.url,
201 };
203​
204export interface ThreadPullRequestChain {
205 readonly kind: "native" | "derived";
206 /** Bottom to top. */
207 readonly layers: ReadonlyArray<ThreadPullRequestLink>;
209​
210/**
211 * Groups a thread's links into stacks. Native stacks come from the host and win; the rest
212 * are chained by matching one link's base branch to another's head branch within the same
213 * repository. A link that chains to nothing is a one-layer chain.
214 */
215export function resolveThreadPullRequestChains(
216 links: ReadonlyArray<ThreadPullRequestLink>,
217): ReadonlyArray<ThreadPullRequestChain> {
218 const visible = visibleThreadPullRequests(links);
219 const chains: Array<ThreadPullRequestChain> = [];
220 const placed = new Set<string>();
221​
222 const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();
223 for (const link of visible) {
224 if (link.stack === null) continue;
225 const key = normalizeThreadPullRequestKey(link);
226 const stackKey = `${key.host}/${key.repository}#stack:${link.stack.id}`;
227 const members = nativeStacks.get(stackKey) ?? [];
228 members.push(link);
229 nativeStacks.set(stackKey, members);
230 }
231 for (const members of nativeStacks.values()) {
232 const order = new Map(members[0]!.stack!.layers.map((layer, index) => [layer.number, index]));
233 members.sort((left, right) => (order.get(left.number) ?? 0) - (order.get(right.number) ?? 0));
234 for (const member of members) placed.add(threadPullRequestKeyOf(member));
235 chains.push({ kind: "native", layers: members });
236 }
237​
238 const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
239 const branchKey = (link: ThreadPullRequestLink, branch: string) => {
240 const key = normalizeThreadPullRequestKey(link);
241 return `${key.host}/${key.repository}:${branch}`;
242 };
243 // Reused head names cannot identify a parent unambiguously.
244 const byHead = new Map<string, ThreadPullRequestLink | null>();
245 for (const link of remaining) {
246 if (link.snapshot === null) continue;
247 const key = branchKey(link, link.snapshot.headBranch);
248 byHead.set(key, byHead.has(key) ? null : link);
249 }
250 const hasChild = new Set<string>();
251 for (const link of remaining) {
252 if (link.snapshot === null) continue;
253 const parent = byHead.get(branchKey(link, link.snapshot.baseBranch));
254 if (parent != null && parent !== link) hasChild.add(threadPullRequestKeyOf(parent));
255 }
256 // Walk from each top (a link nothing builds on) down its base chain.
257 for (const top of remaining) {
258 if (hasChild.has(threadPullRequestKeyOf(top))) continue;
259 const layers: Array<ThreadPullRequestLink> = [];
260 let cursor: ThreadPullRequestLink | undefined = top;
261 while (cursor !== undefined && !placed.has(threadPullRequestKeyOf(cursor))) {
262 placed.add(threadPullRequestKeyOf(cursor));
263 layers.unshift(cursor);
264 cursor =
265 cursor.snapshot === null
266 ? undefined
267 : (byHead.get(branchKey(cursor, cursor.snapshot.baseBranch)) ?? undefined);
268 }
269 if (layers.length > 0) chains.push({ kind: "derived", layers });
270 }
271 // Cycles have no top. Keep those links visible without inventing a stack order.
272 for (const link of remaining) {
273 if (!placed.has(threadPullRequestKeyOf(link))) {
274 chains.push({ kind: "derived", layers: [link] });
275 }
276 }
277 return chains;
279​
280export type ThreadPullRequestBadge = {
281 readonly state: "open" | "closed" | "merged" | "draft";
282} & (
283 | {
284 readonly kind: "stack";
285 readonly layers: number;
286 }
287 | { readonly kind: "pull-request"; readonly others: number }
288);
289​
290/** Aggregate visible links' state for both stacks and unrelated linked counts. */
291export function resolveThreadPullRequestBadge(
292 pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
293): ThreadPullRequestBadge | null {
294 const visible = visibleThreadPullRequests(pullRequests ?? []);
295 if (visible.length === 0) return null;
296 const states = visible.map((link) => link.snapshot?.state ?? "open");
297 const state = visible.every((link) => link.snapshot?.state === "open" && link.snapshot.isDraft)
298 ? "draft"
299 : states.includes("open")
300 ? "open"
301 : states.every((entry) => entry === "merged")
302 ? "merged"
303 : "closed";
304 const chains = resolveThreadPullRequestChains(visible);
305 if (visible.length > 1 && chains.length === 1) {
306 return { kind: "stack", layers: visible.length, state };
307 }
308 return { kind: "pull-request", others: visible.length - 1, state };
310​
311/** Search terms for visible PR links, including the legacy single-link projection. */
312export function threadPullRequestSearchTerms(thread: {
313 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
314 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
315}): string[] {
316 if (thread.pullRequests !== undefined && thread.pullRequests.length > 0) {
317 return visibleThreadPullRequests(thread.pullRequests).flatMap((link) => [
318 `#${link.number}`,
319 `${link.repository}#${link.number}`,
320 link.url,
321 link.snapshot?.title ?? "",
322 ]);
323 }
324 const legacy = thread.linkedPullRequest;
325 return legacy ? [`#${legacy.number}`, `${legacy.repository}#${legacy.number}`, legacy.url] : [];
327​
328/** Older V2 event payloads stored one link; an explicit empty array means it was unlinked. */
329export function threadPullRequestsOf(thread: {
330 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
331 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
332}): ReadonlyArray<ThreadPullRequestLink> {
333 if (thread.pullRequests !== undefined) return thread.pullRequests;
334 const linked = thread.linkedPullRequest;
335 return linked == null
336 ? []
337 : [
338 {
339 ...legacyThreadPullRequestKey(linked),
340 url: linked.url,
341 source: "manual",
342 linkedAt: "1970-01-01T00:00:00.000Z",
343 snapshot: null,
344 stack: null,
345 },
346 ];