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 .sort(
156 (left, right) =>
157 Math.max(...right.map((link) => Date.parse(link.linkedAt))) -
158 Math.max(...left.map((link) => Date.parse(link.linkedAt))),
159 );
160 const ordered = openChains.flat();
161 return { kind: "stack", open: ordered, top: ordered[0]! };
162 }
163 if (chains.length === 1) {
164 return { kind: "single", link: layersFromTop(chains[0]!)[0]! };
165 }
166 const terminal = [...visible].sort(
167 (left, right) => latestUpdatedAt(right) - latestUpdatedAt(left),
168 );
169 return { kind: "single", link: terminal[0]! };
170 }
171
172 function resolveThreadCurrentPullRequestLink(
173 links: ReadonlyArray<ThreadPullRequestLink>,
174 ): ThreadPullRequestLink | null {
175 const current = resolveThreadCurrentPullRequest(links);
176 if (current === null) return null;
177 return current.kind === "single" ? current.link : current.top;
178 }
179
180 function resolveThreadPullRequestChains(
181 links: ReadonlyArray<ThreadPullRequestLink>,
182 ): ReadonlyArray<ThreadPullRequestChain> {
183 const visible = visibleThreadPullRequests(links);
184 const chains: Array<ThreadPullRequestChain> = [];
185 const placed = new Set<string>();
186
187 const nativeStacks = new Map<string, Array<ThreadPullRequestLink>>();
188 for (const link of visible) {
189 if (link.stack === null) continue;
190 const key = normalizedKeyOf(link);
191 const stackKey = `${key.host}/${key.repository}#stack:${link.stack.id}`;
192 const members = nativeStacks.get(stackKey) ?? [];
193 members.push(link);
194 nativeStacks.set(stackKey, members);
195 }
196 for (const members of nativeStacks.values()) {
197 // Saved snapshots can lag behind newer members of the same stack.
198 const memberNumbers = new Set(members.map((member) => member.number));
199 let layers = members[0]!.stack!.layers;
200 let coverage = layers.filter((layer) => memberNumbers.has(layer.number)).length;
201 for (const member of members.slice(1)) {
202 const candidate = member.stack!.layers;
203 const candidateCoverage = candidate.filter((layer) =>
204 memberNumbers.has(layer.number),
205 ).length;
206 if (
207 candidateCoverage > coverage ||
208 (candidateCoverage === coverage && candidate.length > layers.length)
209 ) {
210 layers = candidate;
211 coverage = candidateCoverage;
212 }
213 }
214 const order = new Map(layers.map((layer, index) => [layer.number, index]));
215 members.sort(
216 (left, right) =>
217 (order.get(left.number) ?? layers.length) - (order.get(right.number) ?? layers.length),
218 );
219 for (const member of members) placed.add(threadPullRequestKeyOf(member));
220 chains.push({ kind: "native", layers: members, depths: members.map((_, index) => index) });
221 }
222
223 const remaining = visible.filter((link) => !placed.has(threadPullRequestKeyOf(link)));
224 const branchKey = (link: ThreadPullRequestLink, branch: string) => {
225 const key = normalizedKeyOf(link);
226 return `${key.host}/${key.repository}:${branch}`;
227 };
228 const byHead = new Map<string, ThreadPullRequestLink | null>();
229 for (const link of remaining) {
230 if (link.snapshot === null) continue;
231 const key = branchKey(link, link.snapshot.headBranch);
232 byHead.set(key, byHead.has(key) ? null : link);
233 }
234 const parentOf = (link: ThreadPullRequestLink) => {
235 if (link.snapshot === null) return undefined;
236 const parent = byHead.get(branchKey(link, link.snapshot.baseBranch));
237 return parent == null || parent === link ? undefined : parent;
238 };
239 const children = new Map<string, Array<ThreadPullRequestLink>>();
240 for (const link of remaining) {
241 const parent = parentOf(link);
242 if (parent === undefined) continue;
243 const key = threadPullRequestKeyOf(parent);
244 const siblings = children.get(key) ?? [];
245 siblings.push(link);
246 children.set(key, siblings);
247 }
248 for (const base of remaining) {
249 if (parentOf(base) !== undefined) continue;
250 const layers: Array<ThreadPullRequestLink> = [];
251 const depths: Array<number> = [];
252 const pending: Array<{ readonly link: ThreadPullRequestLink; readonly depth: number }> = [
253 { link: base, depth: 0 },
254 ];
255 for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
256 const key = threadPullRequestKeyOf(next.link);
257 // Two links with one identity would otherwise share a child list and expand forever.
258 if (placed.has(key)) continue;
259 placed.add(key);
260 layers.push(next.link);
261 depths.push(next.depth);
262 const below = children.get(key) ?? [];
263 for (let index = below.length - 1; index >= 0; index -= 1) {
264 pending.push({ link: below[index]!, depth: next.depth + 1 });
265 }
266 }
267 if (layers.length > 0) chains.push({ kind: "derived", layers, depths });
268 }
269 for (const link of remaining) {
270 if (!placed.has(threadPullRequestKeyOf(link))) {
271 chains.push({ kind: "derived", layers: [link], depths: [0] });
272 }
273 }
274 return chains;
275 }
276
277 function resolveThreadPullRequestBadge(
278 pullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined,
279 ): ThreadPullRequestBadge | null {
280 const visible = visibleThreadPullRequests(pullRequests ?? []);
281 if (visible.length === 0) return null;
282 const states = visible.map((link) => link.snapshot?.state ?? "open");
283 const state = visible.every((link) => link.snapshot?.state === "open" && link.snapshot.isDraft)
284 ? "draft"
285 : states.includes("open")
286 ? "open"
287 : states.every((entry) => entry === "merged")
288 ? "merged"
289 : "closed";
290 const chains = resolveThreadPullRequestChains(visible);
291 if (visible.length > 1 && chains.length === 1) {
292 return { kind: "stack", layers: visible.length, state };
293 }
294 return { kind: "pull-request", others: visible.length - 1, state };
295 }
296
297 /** Older V2 event payloads stored one link; an explicit empty array means it was unlinked. */
298 function threadPullRequestsOf(thread: {
299 readonly pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
300 readonly linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
301 }): ReadonlyArray<ThreadPullRequestLink> {
302 if (thread.pullRequests !== undefined) return thread.pullRequests;
303 const linked = thread.linkedPullRequest;
304 return linked == null
305 ? []
306 : [
307 {
308 ...legacyThreadPullRequestKey(linked),
309 url: linked.url,
310 source: "manual",
311 linkedAt: "1970-01-01T00:00:00.000Z",
312 snapshot: null,
313 stack: null,
314 },
315 ];
316 }
317
318 function applyThreadPullRequestLinkUpdate(
319 thread: OrchestrationV2AppThread,
320 updated: ThreadPullRequestLink,
321 ): OrchestrationV2AppThread {
322 return {
323 ...thread,
324 pullRequests: threadPullRequestsOf(thread).map((link) =>
325 threadPullRequestKeysEqual(link, updated) ? updated : link,
326 ),
327 };
328 }
329
330 return {
331 normalizeThreadPullRequestKey,
332 legacyThreadPullRequestKey,
333 threadPullRequestKeysEqual,
334 threadPullRequestKeyOf,
335 resolveThreadCurrentPullRequest,
336 resolveThreadCurrentPullRequestLink,
337 resolveThreadPullRequestChains,
338 resolveThreadPullRequestBadge,
339 threadPullRequestsOf,
340 applyThreadPullRequestLinkUpdate,
341 };
342}
343
344export interface PullRequestListLine {
345 readonly link: ThreadPullRequestLink;
346 readonly depth: number;
347 readonly chainKey: string;
348 readonly stack: { readonly kind: ThreadPullRequestChain["kind"]; readonly size: number } | null;
349}
350
351function chainKeyOf(chain: ThreadPullRequestChain): string {
352 const bottom = chain.layers[0]!;
353 return `${bottom.host}/${bottom.repository}#${bottom.number}`;
354}
355
356export function pullRequestListLines(
357 chains: ReadonlyArray<ThreadPullRequestChain>,
358): ReadonlyArray<PullRequestListLine> {
359 const ordered = [...chains].sort(
360 (left, right) =>
361 Math.max(...right.layers.map(latestUpdatedAt)) -
362 Math.max(...left.layers.map(latestUpdatedAt)),
363 );
364 return ordered.flatMap((chain) => {
365 const chainKey = chainKeyOf(chain);
366 return chain.layers.map((link, index) => ({
367 link,
368 depth: chain.depths[index]!,
369 chainKey,
370 stack:
371 index === 0 && chain.layers.length > 1
372 ? { kind: chain.kind, size: chain.layers.length }
373 : null,
374 }));
375 });
376}