Open History to see the last commit
1import type {
2 OrchestrationV2AppThread,
3 ThreadLinkedPullRequest,
4 ThreadPullRequestKey,
5 ThreadPullRequestLink,
6} from "@t3tools/contracts";
7import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
8
9import type { SourceControlDefinitionRegistry } from "./definition.ts";
10
11type ThreadPullRequestKeySource = ThreadPullRequestKey & {
12 readonly authority?: string;
13 readonly url?: string;
14};
15
16function isOpen(link: ThreadPullRequestLink): boolean {
17 return link.snapshot === null || link.snapshot.state === "open";
18}
19
20function latestUpdatedAt(link: ThreadPullRequestLink): number {
21 const value = link.snapshot?.updatedAt ?? link.linkedAt;
22 const ms = Date.parse(value);
23 return Number.isNaN(ms) ? 0 : ms;
24}
25
26export type ThreadCurrentPullRequest =
27 | { readonly kind: "single"; readonly link: ThreadPullRequestLink }
28 | {
29 readonly kind: "stack";
30 readonly open: ReadonlyArray<ThreadPullRequestLink>;
31 readonly top: ThreadPullRequestLink;
32 };
33
34function layersFromTop(chain: ThreadPullRequestChain): Array<ThreadPullRequestLink> {
35 // `.sort()` on a fresh array, not `.toSorted()`: this runs on Hermes, which has no ES2023
36 // array methods, and a TypeError here is fatal on every mobile launch that renders a stack.
37 return chain.layers
38 .map((link, index) => ({ link, index, depth: chain.depths[index]! }))
39 .sort((left, right) => right.depth - left.depth || right.index - left.index)
40 .map((entry) => entry.link);
41}
42
43export interface ThreadPullRequestChain {
44 readonly kind: "native" | "derived";
45 readonly layers: ReadonlyArray<ThreadPullRequestLink>;
46 /** One per layer: 0 for the base, parent's depth + 1 above it. Siblings share a depth. */
47 readonly depths: ReadonlyArray<number>;
48}
49
50export type ThreadPullRequestBadge = {
51 readonly state: "open" | "closed" | "merged" | "draft";
52} & (
53 | {
54 readonly kind: "stack";
55 readonly layers: number;
56 }
57 | { readonly kind: "pull-request"; readonly others: number }
58);
59
60/**
61 * Thread pull request identity reads a link's URL through the hosts in `registry`, so each side
62 * binds these once to its own registry.
63 */
64export function makeThreadPullRequests(
65 registry: Pick<
66 SourceControlDefinitionRegistry,
67 "parseChangeRequestUrl" | "canonicalRepositoryKey" | "findByRepositoryKey"
68 >,
69) {
70 const parse = (url: string) => registry.parseChangeRequestUrl(url)?.link ?? null;
71
72 function normalizeThreadPullRequestKey(key: ThreadPullRequestKeySource): ThreadPullRequestKey {
73 const parsed = key.url === undefined ? null : parse(key.url);
74 const authority =
75 key.authority ??
76 (parsed?.repository === key.repository.trim().toLowerCase() && parsed.number === key.number
77 ? parsed.authority
78 : undefined);
79 const canonical = registry.canonicalRepositoryKey(
80 `${(authority ?? key.host).trim().toLowerCase()}/${key.repository.trim().toLowerCase()}`,
81 );
82 const separator = canonical.indexOf("/");
83 return {
84 host: canonical.slice(0, separator),
85 repository: canonical.slice(separator + 1),
86 number: key.number,
87 };
88 }
89
90 function legacyThreadPullRequestKey(
91 linked: Pick<ThreadLinkedPullRequest, "repository" | "number" | "url">,
92 fallbackHost?: string,
93 ): ThreadPullRequestKey {
94 const parsed = parse(linked.url);
95 if (parsed !== null && parsed.number === linked.number) {
96 if (
97 parsed.authority !== undefined ||
98 registry.findByRepositoryKey(`${parsed.host}/${parsed.repository}`) !== undefined
99 ) {
100 return normalizeThreadPullRequestKey(parsed);
101 }
102 }
103 let host = fallbackHost;
104 if (host === undefined) {
105 try {
106 host = new URL(linked.url).hostname;
107 } catch {
108 host = "unknown";
109 }
110 }
111 return {
112 host: host.trim().toLowerCase() || "unknown",
113 repository: linked.repository.trim().toLowerCase(),
114 number: linked.number,
115 };
116 }
117
118 function threadPullRequestKeysEqual(
119 left: ThreadPullRequestKeySource,
120 right: ThreadPullRequestKeySource,
121 ): boolean {
122 return threadPullRequestKeyOf(left) === threadPullRequestKeyOf(right);
123 }
124
125 // Clients re-derive chains for every link on each render, and normalizing parses the
126 // link's URL. Links are immutable and keep their identity until they change.
127 const normalizedKeys = new WeakMap<ThreadPullRequestKeySource, ThreadPullRequestKey>();
128
129 function normalizedKeyOf(key: ThreadPullRequestKeySource): ThreadPullRequestKey {
130 let normalized = normalizedKeys.get(key);
131 if (normalized === undefined) {
132 normalized = normalizeThreadPullRequestKey(key);
133 normalizedKeys.set(key, normalized);
134 }
135 return normalized;
136 }
137
138 function threadPullRequestKeyOf(key: ThreadPullRequestKeySource): string {
139 const normalized = normalizedKeyOf(key);
140 return `${normalized.host}/${normalized.repository}#${normalized.number}`;
141 }
142
143 function resolveThreadCurrentPullRequest(
144 links: ReadonlyArray<ThreadPullRequestLink>,
145 ): ThreadCurrentPullRequest | null {
146 const visible = visibleThreadPullRequests(links);
147 if (visible.length === 0) return null;
148 const open = visible.filter(isOpen);
149 if (open.length === 1) return { kind: "single", link: open[0]! };
150 const chains = resolveThreadPullRequestChains(visible);
151 if (open.length > 1) {
152 const openChains = chains
153 .map((chain) => layersFromTop(chain).filter(isOpen))
154 .filter((layers) => layers.length > 0);
155 const ordered =
156 openChains.length === 1
157 ? openChains[0]!
158 : openChains
159 .map((layers) => ({
160 layers,
161 newestLinkedAt: Math.max(...layers.map((link) => Date.parse(link.linkedAt))),
162 }))
163 .sort((left, right) => right.newestLinkedAt - left.newestLinkedAt)
164 .flatMap((chain) => chain.layers);
165 return { kind: "stack", open: ordered, top: ordered[0]! };
166 }
167 if (chains.length === 1) {
168 return { kind: "single", link: layersFromTop(chains[0]!)[0]! };
169 }
170 let latest = visible[0]!;
171 let latestTimestamp = latestUpdatedAt(latest);
172 for (let index = 1; index < visible.length; index++) {
173 const link = visible[index]!;
174 const timestamp = latestUpdatedAt(link);
175 if (timestamp > latestTimestamp) {
176 latest = link;
177 latestTimestamp = timestamp;
178 }
179 }
180 return { kind: "single", link: latest };
181 }
182
183 function resolveThreadCurrentPullRequestLink(
184 links: ReadonlyArray<ThreadPullRequestLink>,
185 ): ThreadPullRequestLink | null {
186 const current = resolveThreadCurrentPullRequest(links);
187 if (current === null) return null;
188 return current.kind === "single" ? current.link : current.top;
189 }
190
191 function resolveThreadPullRequestChains(
192 links: ReadonlyArray<ThreadPullRequestLink>,
193 ): ReadonlyArray<ThreadPullRequestChain> {
194 const visible = visibleThreadPullRequests(links);
195 const chains: Array<ThreadPullRequestChain> = [];
196 const placed = new Set<string>();
197
198 const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();
199 for (const link of visible) {
200 if (link.stack === null) continue;
201 const key = normalizedKeyOf(link);
202 const stackKey = `${key.host}/${key.repository}#stack:${link.stack.id}`;
203 const members = nativeStacks.get(stackKey) ?? [];
204 members.push(link);
205 nativeStacks.set(stackKey, members);
206 }
207 for (const members of nativeStacks.values()) {
208 // Saved snapshots can lag behind newer members of the same stack.
209 const memberNumbers = new Set(members.map((member) => member.number));
210 let layers = members[0]!.stack!.layers;
211 let coverage = layers.filter((layer) => memberNumbers.has(layer.number)).length;
212 for (const member of members.slice(1)) {
213 const candidate = member.stack!.layers;
214 const candidateCoverage = candidate.filter((layer) =>
215 memberNumbers.has(layer.number),
216 ).length;
217 if (
218 candidateCoverage > coverage ||
219 (candidateCoverage === coverage && candidate.length > layers.length)
220 ) {
221 layers = candidate;
222 coverage = candidateCoverage;
223 }
224 }
225 const order = new Map(layers.map((layer, index) => [layer.number, index]));
226 members.sort(
227 (left, right) =>
228 (order.get(left.number) ?? layers.length) - (order.get(right.number) ?? layers.length),
229 );
230 for (const member of members) placed.add(threadPullRequestKeyOf(member));
231 chains.push({ kind: "native", layers: members, depths: members.map((_, index) => index) });
232 }
233
234 const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
235 const branchKey = (link: ThreadPullRequestLink, branch: string) => {
236 const key = normalizedKeyOf(link);
237 return `${key.host}/${key.repository}:${branch}`;
238 };
239 const byHead = new Map<string, ThreadPullRequestLink | null>();
240 for (const link of remaining) {
241 if (link.snapshot === null) continue;
242 const key = branchKey(link, link.snapshot.headBranch);
243 byHead.set(key, byHead.has(key) ? null : link);
244 }
245 const parentOf = (link: ThreadPullRequestLink) => {
246 if (link.snapshot === null) return undefined;
247 const parent = byHead.get(branchKey(link, link.snapshot.baseBranch));
248 return parent == null || parent === link ? undefined : parent;
249 };
250 const children = new Map<string, Array<ThreadPullRequestLink>>();
251 for (const link of remaining) {
252 const parent = parentOf(link);
253 if (parent === undefined) continue;
254 const key = threadPullRequestKeyOf(parent);
255 const siblings = children.get(key) ?? [];
256 siblings.push(link);
257 children.set(key, siblings);
258 }
259 for (const base of remaining) {
260 if (parentOf(base) !== undefined) continue;
261 const layers: Array<ThreadPullRequestLink> = [];
262 const depths: Array<number> = [];
263 const pending: Array<{ readonly link: ThreadPullRequestLink; readonly depth: number }> = [
264 { link: base, depth: 0 },
265 ];
266 for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
267 const key = threadPullRequestKeyOf(next.link);
268 // Two links with one identity would otherwise share a child list and expand forever.
269 if (placed.has(key)) continue;
270 placed.add(key);
271 layers.push(next.link);
272 depths.push(next.depth);
273 const below = children.get(key) ?? [];
274 for (let index = below.length - 1; index >= 0; index -= 1) {
275 pending.push({ link: below[index]!, depth: next.depth + 1 });
276 }
277 }
278 if (layers.length > 0) chains.push({ kind: "derived", layers, depths });
279 }
280 for (const link of remaining) {
281 if (!placed.has(threadPullRequestKeyOf(link))) {
282 chains.push({ kind: "derived", layers: [link], depths: [0] });
283 }
284 }
285 return chains;
286 }
287
288 function resolveThreadPullRequestBadge(
289 pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
290 ): ThreadPullRequestBadge | null {
291 const visible = visibleThreadPullRequests(pullRequests ?? []);
292 if (visible.length === 0) return null;
293 const states = visible.map((link) => link.snapshot?.state ?? "open");
294 const state = visible.every((link) => link.snapshot?.state === "open" && link.snapshot.isDraft)
295 ? "draft"
296 : states.includes("open")
297 ? "open"
298 : states.every((entry) => entry === "merged")
299 ? "merged"
300 : "closed";
301 const chains = resolveThreadPullRequestChains(visible);
302 if (visible.length > 1 && chains.length === 1) {
303 return { kind: "stack", layers: visible.length, state };
304 }
305 return { kind: "pull-request", others: visible.length - 1, state };
306 }
307
308 /** Older V2 event payloads stored one link; an explicit empty array means it was unlinked. */
309 function threadPullRequestsOf(thread: {
310 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
311 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
312 }): ReadonlyArray<ThreadPullRequestLink> {
313 if (thread.pullRequests !== undefined) return thread.pullRequests;
314 const linked = thread.linkedPullRequest;
315 return linked == null
316 ? []
317 : [
318 {
319 ...legacyThreadPullRequestKey(linked),
320 url: linked.url,
321 source: "manual",
322 linkedAt: "1970-01-01T00:00:00.000Z",
323 snapshot: null,
324 stack: null,
325 },
326 ];
327 }
328
329 function applyThreadPullRequestLinkUpdate(
330 thread: OrchestrationV2AppThread,
331 updated: ThreadPullRequestLink,
332 ): OrchestrationV2AppThread {
333 return {
334 ...thread,
335 pullRequests: threadPullRequestsOf(thread).map((link) =>
336 threadPullRequestKeysEqual(link, updated) ? updated : link,
337 ),
338 };
339 }
340
341 return {
342 normalizeThreadPullRequestKey,
343 legacyThreadPullRequestKey,
344 threadPullRequestKeysEqual,
345 threadPullRequestKeyOf,
346 resolveThreadCurrentPullRequest,
347 resolveThreadCurrentPullRequestLink,
348 resolveThreadPullRequestChains,
349 resolveThreadPullRequestBadge,
350 threadPullRequestsOf,
351 applyThreadPullRequestLinkUpdate,
352 };
353}
354
355export interface PullRequestListLine {
356 readonly link: ThreadPullRequestLink;
357 readonly depth: number;
358 readonly chainKey: string;
359 readonly stack: { readonly kind: ThreadPullRequestChain["kind"]; readonly size: number } | null;
360}
361
362function chainKeyOf(chain: ThreadPullRequestChain): string {
363 const bottom = chain.layers[0]!;
364 return `${bottom.host}/${bottom.repository}#${bottom.number}`;
365}
366
367export function pullRequestListLines(
368 chains: ReadonlyArray<ThreadPullRequestChain>,
369): ReadonlyArray<PullRequestListLine> {
370 const ordered = [...chains].sort(
371 (left, right) =>
372 Math.max(...right.layers.map(latestUpdatedAt)) -
373 Math.max(...left.layers.map(latestUpdatedAt)),
374 );
375 return ordered.flatMap((chain) => {
376 const chainKey = chainKeyOf(chain);
377 return chain.layers.map((link, index) => ({
378 link,
379 depth: chain.depths[index]!,
380 chainKey,
381 stack:
382 index === 0 && chain.layers.length > 1
383 ? { kind: chain.kind, size: chain.layers.length }
384 : null,
385 }));
386 });
387}