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

threadPullRequests.ts

292 lines11.3 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​
13/** Normalize stored link identity, including Azure's SSH and browser host aliases. */
14export function normalizeThreadPullRequestKey(key: ThreadPullRequestKey): ThreadPullRequestKey {
15 const canonical = canonicalRepositoryKey(
16 `${key.host.trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,
17 );
18 const separator = canonical.indexOf("/");
19 return {
20 host: canonical.slice(0, separator),
21 repository: canonical.slice(separator + 1),
22 number: key.number,
23 };
25​
26/** Legacy Azure selectors omit the organization and project; recover those from the PR URL. */
27export function legacyThreadPullRequestKey(
28 linked: Pick<ThreadLinkedPullRequest, "repository" | "number" | "url">,
29 fallbackHost?: string,
30): ThreadPullRequestKey {
31 const parsed = parseChangeRequestUrl(linked.url);
32 if (parsed !== null && parsed.number === linked.number) {
33 const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);
34 if (canonical.startsWith("dev.azure.com/")) {
35 return normalizeThreadPullRequestKey(parsed);
36 }
37 }
38 let host = fallbackHost;
39 if (host === undefined) {
40 try {
41 host = new URL(linked.url).hostname;
42 } catch {
43 host = "unknown";
44 }
45 }
46 return {
47 host: host.trim().toLowerCase() || "unknown",
48 repository: linked.repository.trim().toLowerCase(),
49 number: linked.number,
50 };
52​
53/** Identity comparison for links: host-level, case-insensitive on host and repository. */
54export function threadPullRequestKeysEqual(
55 left: ThreadPullRequestKey,
56 right: ThreadPullRequestKey,
57): boolean {
58 return threadPullRequestKeyOf(left) === threadPullRequestKeyOf(right);
60​
61export function threadPullRequestKeyOf(key: ThreadPullRequestKey): string {
62 const normalized = normalizeThreadPullRequestKey(key);
63 return `${normalized.host}/${normalized.repository}#${normalized.number}`;
65​
66/** Links a user should see. Tombstoned stack members stay in the array only so the
67 * sync reactor does not re-add them. */
68export function visibleThreadPullRequests(
69 links: ReadonlyArray<ThreadPullRequestLink>,
70): ReadonlyArray<ThreadPullRequestLink> {
71 return links.filter((link) => link.source !== "stack-dismissed");
73​
74function isOpen(link: ThreadPullRequestLink): boolean {
75 // Unsynced links are treated as open: they were just linked, and hiding them
76 // behind a terminal PR until the first sync would make the link look lost.
77 return link.snapshot === null || link.snapshot.state === "open";
79​
80function latestUpdatedAt(link: ThreadPullRequestLink): number {
81 const value = link.snapshot?.updatedAt ?? link.linkedAt;
82 const ms = Date.parse(value);
83 return Number.isNaN(ms) ? 0 : ms;
85​
86/** The single pull request a one-slot surface (sidebar badge, tab icon, copy link) shows. */
87export type ThreadCurrentPullRequest =
88 | { readonly kind: "single"; readonly link: ThreadPullRequestLink }
89 | {
90 readonly kind: "stack";
91 readonly open: ReadonlyArray<ThreadPullRequestLink>;
92 /** Highest layer of the open set; the one "View PR" and copy-link target. */
93 readonly top: ThreadPullRequestLink;
94 };
95​
96/**
97 * Prefer open work and the highest open layer within a chain. A completed chain still
98 * points at its top; unrelated terminal links use the most recently updated request.
99 */
100export function resolveThreadCurrentPullRequest(
101 links: ReadonlyArray<ThreadPullRequestLink>,
102): ThreadCurrentPullRequest | null {
103 const visible = visibleThreadPullRequests(links);
104 if (visible.length === 0) return null;
105 const open = visible.filter(isOpen);
106 if (open.length === 1) return { kind: "single", link: open[0]! };
107 const chains = resolveThreadPullRequestChains(visible);
108 if (open.length > 1) {
109 const openChains = chains
110 .map((chain) => chain.layers.toReversed().filter(isOpen))
111 .filter((layers) => layers.length > 0)
112 .sort(
113 (left, right) =>
114 Math.max(...right.map((link) => Date.parse(link.linkedAt))) -
115 Math.max(...left.map((link) => Date.parse(link.linkedAt))),
116 );
117 const ordered = openChains.flat();
118 return { kind: "stack", open: ordered, top: ordered[0]! };
119 }
120 if (chains.length === 1) {
121 return { kind: "single", link: chains[0]!.layers.at(-1)! };
122 }
123 const terminal = [...visible].sort(
124 (left, right) => latestUpdatedAt(right) - latestUpdatedAt(left),
125 );
126 return { kind: "single", link: terminal[0]! };
128​
129/** The one link a legacy `linkedPullRequest` consumer should see, or null. */
130export function resolveThreadCurrentPullRequestLink(
131 links: ReadonlyArray<ThreadPullRequestLink>,
132): ThreadPullRequestLink | null {
133 const current = resolveThreadCurrentPullRequest(links);
134 if (current === null) return null;
135 return current.kind === "single" ? current.link : current.top;
137​
138/** Legacy clients can only route links belonging to the thread's own repository. */
139export function legacyLinkedPullRequestOf(
140 links: ReadonlyArray<ThreadPullRequestLink>,
141 projectId: ThreadLinkedPullRequest["projectId"],
142 identity: RepositoryIdentity | null | undefined,
143): ThreadLinkedPullRequest | null {
144 if (!identity) return null;
145 const host = pullRequestHostOf(identity, identity.provider as SourceControlProviderKind);
146 const repository = sourceControlRepositorySelector(identity);
147 if (repository === null) return null;
148 const azureKey =
149 identity.provider === "azure-devops"
150 ? canonicalRepositoryKey(identity.canonicalKey.toLowerCase())
151 : null;
152 const link = resolveThreadCurrentPullRequestLink(
153 links.filter((link) => {
154 if (azureKey !== null) {
155 const key = legacyThreadPullRequestKey(link, link.host);
156 return canonicalRepositoryKey(`${key.host}/${key.repository}`) === azureKey;
157 }
158 return (
159 link.host.toLowerCase() === host.toLowerCase() &&
160 link.repository.toLowerCase() === repository.toLowerCase()
161 );
162 }),
163 );
164 if (link === null) return null;
165 return {
166 projectId,
167 repository: azureKey === null ? link.repository : repository,
168 number: link.number,
169 url: link.url,
170 };
172​
173export interface ThreadPullRequestChain {
174 readonly kind: "native" | "derived";
175 /** Bottom to top. */
176 readonly layers: ReadonlyArray<ThreadPullRequestLink>;
178​
179/**
180 * Groups a thread's links into stacks. Native stacks come from the host and win; the rest
181 * are chained by matching one link's base branch to another's head branch within the same
182 * repository. A link that chains to nothing is a one-layer chain.
183 */
184export function resolveThreadPullRequestChains(
185 links: ReadonlyArray<ThreadPullRequestLink>,
186): ReadonlyArray<ThreadPullRequestChain> {
187 const visible = visibleThreadPullRequests(links);
188 const chains: Array<ThreadPullRequestChain> = [];
189 const placed = new Set<string>();
190​
191 const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();
192 for (const link of visible) {
193 if (link.stack === null) continue;
194 const stackKey = `${link.host.toLowerCase()}/${link.repository.toLowerCase()}#stack:${link.stack.id}`;
195 const members = nativeStacks.get(stackKey) ?? [];
196 members.push(link);
197 nativeStacks.set(stackKey, members);
198 }
199 for (const members of nativeStacks.values()) {
200 const order = new Map(members[0]!.stack!.layers.map((layer, index) => [layer.number, index]));
201 members.sort((left, right) => (order.get(left.number) ?? 0) - (order.get(right.number) ?? 0));
202 for (const member of members) placed.add(threadPullRequestKeyOf(member));
203 chains.push({ kind: "native", layers: members });
204 }
205​
206 const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
207 const branchKey = (link: ThreadPullRequestLink, branch: string) =>
208 `${link.host.toLowerCase()}/${link.repository.toLowerCase()}:${branch}`;
209 // Reused head names cannot identify a parent unambiguously.
210 const byHead = new Map<string, ThreadPullRequestLink | null>();
211 for (const link of remaining) {
212 if (link.snapshot === null) continue;
213 const key = branchKey(link, link.snapshot.headBranch);
214 byHead.set(key, byHead.has(key) ? null : link);
215 }
216 const hasChild = new Set<string>();
217 for (const link of remaining) {
218 if (link.snapshot === null) continue;
219 const parent = byHead.get(branchKey(link, link.snapshot.baseBranch));
220 if (parent != null && parent !== link) hasChild.add(threadPullRequestKeyOf(parent));
221 }
222 // Walk from each top (a link nothing builds on) down its base chain.
223 for (const top of remaining) {
224 if (hasChild.has(threadPullRequestKeyOf(top))) continue;
225 const layers: Array<ThreadPullRequestLink> = [];
226 let cursor: ThreadPullRequestLink | undefined = top;
227 while (cursor !== undefined && !placed.has(threadPullRequestKeyOf(cursor))) {
228 placed.add(threadPullRequestKeyOf(cursor));
229 layers.unshift(cursor);
230 cursor =
231 cursor.snapshot === null
232 ? undefined
233 : (byHead.get(branchKey(cursor, cursor.snapshot.baseBranch)) ?? undefined);
234 }
235 if (layers.length > 0) chains.push({ kind: "derived", layers });
236 }
237 // Cycles have no top. Keep those links visible without inventing a stack order.
238 for (const link of remaining) {
239 if (!placed.has(threadPullRequestKeyOf(link))) {
240 chains.push({ kind: "derived", layers: [link] });
241 }
242 }
243 return chains;
245​
246export type ThreadPullRequestBadge = {
247 readonly state: "open" | "closed" | "merged" | "draft";
248} & (
249 | {
250 readonly kind: "stack";
251 readonly layers: number;
252 }
253 | { readonly kind: "pull-request"; readonly others: number }
254);
255​
256/** Aggregate visible links' state for both stacks and unrelated linked counts. */
257export function resolveThreadPullRequestBadge(
258 pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
259): ThreadPullRequestBadge | null {
260 const visible = visibleThreadPullRequests(pullRequests ?? []);
261 if (visible.length === 0) return null;
262 const states = visible.map((link) => link.snapshot?.state ?? "open");
263 const state = visible.every((link) => link.snapshot?.state === "open" && link.snapshot.isDraft)
264 ? "draft"
265 : states.includes("open")
266 ? "open"
267 : states.every((entry) => entry === "merged")
268 ? "merged"
269 : "closed";
270 const chains = resolveThreadPullRequestChains(visible);
271 if (visible.length > 1 && chains.length === 1) {
272 return { kind: "stack", layers: visible.length, state };
273 }
274 return { kind: "pull-request", others: visible.length - 1, state };
276​
277/** Search terms for visible PR links, including the legacy single-link projection. */
278export function threadPullRequestSearchTerms(thread: {
279 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
280 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
281}): string[] {
282 if (thread.pullRequests !== undefined && thread.pullRequests.length > 0) {
283 return visibleThreadPullRequests(thread.pullRequests).flatMap((link) => [
284 `#${link.number}`,
285 `${link.repository}#${link.number}`,
286 link.url,
287 link.snapshot?.title ?? "",
288 ]);
289 }
290 const legacy = thread.linkedPullRequest;
291 return legacy ? [`#${legacy.number}`, `${legacy.repository}#${legacy.number}`, legacy.url] : [];