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

threadPullRequests.ts

342 lines12.2 KB

1import type {
2 OrchestrationV2AppThread,
3 RepositoryIdentity,
4 SourceControlProviderKind,
5 ThreadLinkedPullRequest,
6 ThreadPullRequestKey,
7 ThreadPullRequestLink,
8} from "@t3tools/contracts";
9​
10import { pullRequestHostOf } from "@t3tools/contracts";
11import { parseChangeRequestUrl } from "./changeRequestUrl.ts";
12import { canonicalRepositoryKey, sourceControlRepositorySelector } from "./sourceControl.ts";
13​
14type ThreadPullRequestKeySource = ThreadPullRequestKey & {
15 readonly authority?: string;
16 readonly url?: string;
17};
18​
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​
39export function legacyThreadPullRequestKey(
40 linked: Pick<ThreadLinkedPullRequest, "repository" | "number" | "url">,
41 fallbackHost?: string,
42): ThreadPullRequestKey {
43 const parsed = parseChangeRequestUrl(linked.url);
44 if (parsed !== null && parsed.number === linked.number) {
45 const canonical = canonicalRepositoryKey(`${parsed.host}/${parsed.repository}`);
46 if (parsed.authority !== undefined || canonical.startsWith("dev.azure.com/")) {
47 return normalizeThreadPullRequestKey(parsed);
48 }
49 }
50 let host = fallbackHost;
51 if (host === undefined) {
52 try {
53 host = new URL(linked.url).hostname;
54 } catch {
55 host = "unknown";
56 }
57 }
58 return {
59 host: host.trim().toLowerCase() || "unknown",
60 repository: linked.repository.trim().toLowerCase(),
61 number: linked.number,
62 };
64​
65export function threadPullRequestKeysEqual(
66 left: ThreadPullRequestKeySource,
67 right: ThreadPullRequestKeySource,
68): boolean {
69 return threadPullRequestKeyOf(left) === threadPullRequestKeyOf(right);
71​
72export function threadPullRequestKeyOf(key: ThreadPullRequestKeySource): string {
73 const normalized = normalizeThreadPullRequestKey(key);
74 return `${normalized.host}/${normalized.repository}#${normalized.number}`;
76​
77/** Tombstoned stack members stay in the array only so the
78 * sync reactor does not re-add them. */
79export function visibleThreadPullRequests(
80 links: ReadonlyArray<ThreadPullRequestLink>,
81): ReadonlyArray<ThreadPullRequestLink> {
82 return links.filter((link) => link.source !== "stack-dismissed");
84​
85function isOpen(link: ThreadPullRequestLink): boolean {
86 return link.snapshot === null || link.snapshot.state === "open";
88​
89function latestUpdatedAt(link: ThreadPullRequestLink): number {
90 const value = link.snapshot?.updatedAt ?? link.linkedAt;
91 const ms = Date.parse(value);
92 return Number.isNaN(ms) ? 0 : ms;
94​
95export type ThreadCurrentPullRequest =
96 | { readonly kind: "single"; readonly link: ThreadPullRequestLink }
97 | {
98 readonly kind: "stack";
99 readonly open: ReadonlyArray<ThreadPullRequestLink>;
100 readonly top: ThreadPullRequestLink;
101 };
102​
103export function resolveThreadCurrentPullRequest(
104 links: ReadonlyArray<ThreadPullRequestLink>,
105): ThreadCurrentPullRequest | null {
106 const visible = visibleThreadPullRequests(links);
107 if (visible.length === 0) return null;
108 const open = visible.filter(isOpen);
109 if (open.length === 1) return { kind: "single", link: open[0]! };
110 const chains = resolveThreadPullRequestChains(visible);
111 if (open.length > 1) {
112 // `.reverse()` on a copy, not `.toReversed()`: this runs on Hermes, which has no ES2023
113 // array methods, and a TypeError here is fatal on every mobile launch that renders a stack.
114 const openChains = chains
115 .map((chain) => [...chain.layers].reverse().filter(isOpen))
116 .filter((layers) => layers.length > 0)
117 .sort(
118 (left, right) =>
119 Math.max(...right.map((link) => Date.parse(link.linkedAt))) -
120 Math.max(...left.map((link) => Date.parse(link.linkedAt))),
121 );
122 const ordered = openChains.flat();
123 return { kind: "stack", open: ordered, top: ordered[0]! };
124 }
125 if (chains.length === 1) {
126 return { kind: "single", link: chains[0]!.layers.at(-1)! };
127 }
128 const terminal = [...visible].sort(
129 (left, right) => latestUpdatedAt(right) - latestUpdatedAt(left),
130 );
131 return { kind: "single", link: terminal[0]! };
133​
134export function resolveThreadCurrentPullRequestLink(
135 links: ReadonlyArray<ThreadPullRequestLink>,
136): ThreadPullRequestLink | null {
137 const current = resolveThreadCurrentPullRequest(links);
138 if (current === null) return null;
139 return current.kind === "single" ? current.link : current.top;
141​
142export function legacyLinkedPullRequestOf(
143 links: ReadonlyArray<ThreadPullRequestLink>,
144 projectId: ThreadLinkedPullRequest["projectId"],
145 identity: RepositoryIdentity | null | undefined,
146): ThreadLinkedPullRequest | null {
147 if (!identity) return null;
148 const host = pullRequestHostOf(identity, identity.provider as SourceControlProviderKind);
149 if (typeof host !== "string") return null;
150 const repository = sourceControlRepositorySelector(identity);
151 if (repository === null) return null;
152 const azureKey =
153 identity.provider === "azure-devops"
154 ? canonicalRepositoryKey(identity.canonicalKey.toLowerCase())
155 : null;
156 const link = resolveThreadCurrentPullRequestLink(
157 links.filter((link) => {
158 if (azureKey !== null) {
159 const key = legacyThreadPullRequestKey(link, link.host);
160 return canonicalRepositoryKey(`${key.host}/${key.repository}`) === azureKey;
161 }
162 const parsed = parseChangeRequestUrl(link.url);
163 if (parsed?.authority !== undefined) {
164 try {
165 const remote = new URL(identity.locator.remoteUrl);
166 if (remote.protocol === "http:" || remote.protocol === "https:") {
167 return (
168 parsed.authority === remote.host && parsed.repository === repository.toLowerCase()
169 );
170 }
171 } catch {}
172 return parsed.host === host && parsed.repository === repository.toLowerCase();
173 }
174 return (
175 link.host.toLowerCase() === host.toLowerCase() &&
176 link.repository.toLowerCase() === repository.toLowerCase()
177 );
178 }),
179 );
180 if (link === null) return null;
181 return {
182 projectId,
183 repository: azureKey === null ? link.repository : repository,
184 number: link.number,
185 url: link.url,
186 };
188​
189export interface ThreadPullRequestChain {
190 readonly kind: "native" | "derived";
191 readonly layers: ReadonlyArray<ThreadPullRequestLink>;
193​
194export function resolveThreadPullRequestChains(
195 links: ReadonlyArray<ThreadPullRequestLink>,
196): ReadonlyArray<ThreadPullRequestChain> {
197 const visible = visibleThreadPullRequests(links);
198 const chains: Array<ThreadPullRequestChain> = [];
199 const placed = new Set<string>();
200​
201 const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();
202 for (const link of visible) {
203 if (link.stack === null) continue;
204 const key = normalizeThreadPullRequestKey(link);
205 const stackKey = `${key.host}/${key.repository}#stack:${link.stack.id}`;
206 const members = nativeStacks.get(stackKey) ?? [];
207 members.push(link);
208 nativeStacks.set(stackKey, members);
209 }
210 for (const members of nativeStacks.values()) {
211 const order = new Map(members[0]!.stack!.layers.map((layer, index) => [layer.number, index]));
212 members.sort((left, right) => (order.get(left.number) ?? 0) - (order.get(right.number) ?? 0));
213 for (const member of members) placed.add(threadPullRequestKeyOf(member));
214 chains.push({ kind: "native", layers: members });
215 }
216​
217 const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
218 const branchKey = (link: ThreadPullRequestLink, branch: string) => {
219 const key = normalizeThreadPullRequestKey(link);
220 return `${key.host}/${key.repository}:${branch}`;
221 };
222 const byHead = new Map<string, ThreadPullRequestLink | null>();
223 for (const link of remaining) {
224 if (link.snapshot === null) continue;
225 const key = branchKey(link, link.snapshot.headBranch);
226 byHead.set(key, byHead.has(key) ? null : link);
227 }
228 const hasChild = new Set<string>();
229 for (const link of remaining) {
230 if (link.snapshot === null) continue;
231 const parent = byHead.get(branchKey(link, link.snapshot.baseBranch));
232 if (parent != null && parent !== link) hasChild.add(threadPullRequestKeyOf(parent));
233 }
234 for (const top of remaining) {
235 if (hasChild.has(threadPullRequestKeyOf(top))) continue;
236 const layers: Array<ThreadPullRequestLink> = [];
237 let cursor: ThreadPullRequestLink | undefined = top;
238 while (cursor !== undefined && !placed.has(threadPullRequestKeyOf(cursor))) {
239 placed.add(threadPullRequestKeyOf(cursor));
240 layers.unshift(cursor);
241 cursor =
242 cursor.snapshot === null
243 ? undefined
244 : (byHead.get(branchKey(cursor, cursor.snapshot.baseBranch)) ?? undefined);
245 }
246 if (layers.length > 0) chains.push({ kind: "derived", layers });
247 }
248 for (const link of remaining) {
249 if (!placed.has(threadPullRequestKeyOf(link))) {
250 chains.push({ kind: "derived", layers: [link] });
251 }
252 }
253 return chains;
255​
256export type ThreadPullRequestBadge = {
257 readonly state: "open" | "closed" | "merged" | "draft";
258} & (
259 | {
260 readonly kind: "stack";
261 readonly layers: number;
262 }
263 | { readonly kind: "pull-request"; readonly others: number }
264);
265​
266export function resolveThreadPullRequestBadge(
267 pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
268): ThreadPullRequestBadge | null {
269 const visible = visibleThreadPullRequests(pullRequests ?? []);
270 if (visible.length === 0) return null;
271 const states = visible.map((link) => link.snapshot?.state ?? "open");
272 const state = visible.every((link) => link.snapshot?.state === "open" && link.snapshot.isDraft)
273 ? "draft"
274 : states.includes("open")
275 ? "open"
276 : states.every((entry) => entry === "merged")
277 ? "merged"
278 : "closed";
279 const chains = resolveThreadPullRequestChains(visible);
280 if (visible.length > 1 && chains.length === 1) {
281 return { kind: "stack", layers: visible.length, state };
282 }
283 return { kind: "pull-request", others: visible.length - 1, state };
285​
286export function threadPullRequestSearchTerms(thread: {
287 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
288 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
289 readonly branchPullRequest?: ThreadLinkedPullRequest | null | undefined;
290}): string[] {
291 const branch = thread.branchPullRequest;
292 const terms = branch
293 ? [`#${branch.number}`, `${branch.repository}#${branch.number}`, branch.url]
294 : [];
295 if (thread.pullRequests !== undefined && thread.pullRequests.length > 0) {
296 return terms.concat(
297 visibleThreadPullRequests(thread.pullRequests).flatMap((link) => [
298 `#${link.number}`,
299 `${link.repository}#${link.number}`,
300 link.url,
301 link.snapshot?.title ?? "",
302 ]),
303 );
304 }
305 const legacy = thread.linkedPullRequest;
306 return legacy
307 ? terms.concat([`#${legacy.number}`, `${legacy.repository}#${legacy.number}`, legacy.url])
308 : terms;
310​
311/** Older V2 event payloads stored one link; an explicit empty array means it was unlinked. */
312export function threadPullRequestsOf(thread: {
313 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
314 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
315}): ReadonlyArray<ThreadPullRequestLink> {
316 if (thread.pullRequests !== undefined) return thread.pullRequests;
317 const linked = thread.linkedPullRequest;
318 return linked == null
319 ? []
320 : [
321 {
322 ...legacyThreadPullRequestKey(linked),
323 url: linked.url,
324 source: "manual",
325 linkedAt: "1970-01-01T00:00:00.000Z",
326 snapshot: null,
327 stack: null,
328 },
329 ];
331​
332export function applyThreadPullRequestLinkUpdate(
333 thread: OrchestrationV2AppThread,
334 updated: ThreadPullRequestLink,
335): OrchestrationV2AppThread {
336 return {
337 ...thread,
338 pullRequests: threadPullRequestsOf(thread).map((link) =>
339 threadPullRequestKeysEqual(link, updated) ? updated : link,
340 ),
341 };