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

pullRequestList.logic.ts

1,066 lines36.8 KB

1import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2import * as Schema from "effect/Schema";
3​
4import {
5 EnvironmentId,
6 PullRequestListEntry,
7 PullRequestListProjectError,
8 PullRequestListResult,
9 resolvePullRequestAuthorFilter,
10} from "@t3tools/contracts";
11import type {
12 ProjectId,
13 RepositoryIdentity,
14 PullRequestAction,
15 PullRequestActor,
16 PullRequestDiffStat,
17 PullRequestInvolvement,
18 PullRequestLabel,
19 PullRequestListCursors,
20 PullRequestListFilters,
21 PullRequestListState,
22 PullRequestState,
23} from "@t3tools/contracts";
24​
25import { toSortableTimestamp } from "../../lib/threadSort";
26import type { PullRequestListSort } from "./pullRequestListPreferences";
27​
28export interface EnvironmentPullRequestEntry extends PullRequestListEntry {
29 readonly environmentId: EnvironmentId;
31​
32export interface EnvironmentPullRequestStat extends PullRequestDiffStat {
33 readonly environmentId: EnvironmentId;
35​
36export interface EnvironmentPullRequestError extends PullRequestListProjectError {
37 readonly environmentId: EnvironmentId;
39​
40export type PullRequestGroupKey = "reviewRequested" | "authored" | "others";
41​
42export interface PullRequestGroup<Entry extends PullRequestListEntry = PullRequestListEntry> {
43 readonly key: PullRequestGroupKey;
44 readonly label: string;
45 readonly entries: ReadonlyArray<Entry>;
47​
48export interface PullRequestAuthorFacet {
49 readonly actor: PullRequestActor;
50 readonly count: number;
51 readonly mergedCount: number;
53​
54export interface PullRequestLabelFacet extends PullRequestLabel {
55 readonly count: number;
57​
58export type PullRequestViewers = PullRequestListResult["viewers"];
59​
60type ScopedEntry = PullRequestListEntry & { readonly environmentId?: string };
61​
62const pullRequestViewerKey = (entry: ScopedEntry): string =>
63 `${entry.environmentId ?? ""} ${entry.host}`;
64​
65const GROUP_LABELS: Record<PullRequestGroupKey, string> = {
66 reviewRequested: "Review requested",
67 authored: "Authored",
68 others: "Others",
69};
70​
71function normalize(value: string | null | undefined): string | null {
72 const trimmed = value?.trim().toLowerCase() ?? "";
73 return trimmed.length > 0 ? trimmed : null;
75​
76export function pullRequestLabelColor(color: string | null): string | null {
77 const hex = color?.trim().replace(/^#/, "") ?? "";
78 return /^[0-9a-fA-F]{6}$/.test(hex) ? `#${hex}` : null;
80​
81export function collectPullRequestListFacets(
82 entries: ReadonlyArray<PullRequestListEntry>,
83 state: PullRequestListState,
84) {
85 const authors = new Map<string, PullRequestAuthorFacet>();
86 const labels = new Map<string, PullRequestLabelFacet>();
87 const uniqueEntries = new Map(entries.map((entry) => [pullRequestEntryKey(entry), entry]));
88 for (const entry of uniqueEntries.values()) {
89 const inState = state === "all" || entry.state === state;
90 if (entry.author !== null) {
91 const key = normalize(entry.author.login);
92 if (key !== null) {
93 const held = authors.get(key);
94 authors.set(key, {
95 actor: held?.actor ?? entry.author,
96 count: (held?.count ?? 0) + Number(inState),
97 mergedCount: (held?.mergedCount ?? 0) + Number(entry.state === "merged"),
98 });
99 }
100 }
101 if (!inState) continue;
102 for (const label of entry.labels) {
103 const key = normalize(label.name);
104 if (key === null) continue;
105 const held = labels.get(key);
106 labels.set(key, {
107 ...label,
108 name: held?.name ?? label.name,
109 color: held?.color ?? label.color,
110 count: (held?.count ?? 0) + 1,
111 });
112 }
113 }
114 return {
115 authors: [...authors.values()]
116 .filter((author) => author.count > 0)
117 .toSorted(
118 (left, right) =>
119 right.mergedCount - left.mergedCount ||
120 right.count - left.count ||
121 left.actor.login.localeCompare(right.actor.login),
122 ),
123 labels: [...labels.values()].toSorted(
124 (left, right) => right.count - left.count || left.name.localeCompare(right.name),
125 ),
126 };
128​
129/**
130 * What a filter picker offers for `query`: the loaded rows that match keep their counts and lead,
131 * then whatever the host found that no loaded row carries, so a name nobody has loaded yet is
132 * still one search away.
133 */
134/** How many loaded matches come before the host's answers. */
135const HOSTED_CHOICE_ROOM = 15;
136​
137export function pullRequestAuthorChoices(
138 facets: ReadonlyArray<PullRequestAuthorFacet>,
139 hosted: ReadonlyArray<PullRequestActor>,
140 query: string,
141): ReadonlyArray<PullRequestAuthorFacet> {
142 const needle = normalize(query);
143 const loaded = facets.filter(
144 (facet) =>
145 needle === null ||
146 facet.actor.login.toLowerCase().includes(needle) ||
147 facet.actor.name?.toLowerCase().includes(needle),
148 );
149 const known = new Map(facets.map((facet) => [normalize(facet.actor.login), facet]));
150 const seen = new Set(loaded.map((facet) => normalize(facet.actor.login)));
151 const added: PullRequestAuthorFacet[] = [];
152 for (const actor of hosted) {
153 const key = normalize(actor.login);
154 if (seen.has(key)) continue;
155 seen.add(key);
156 added.push(known.get(key) ?? { actor, count: 0, mergedCount: 0 });
157 }
158 // The picker shows a short list, and loaded matches alone could fill it.
159 return [...loaded.slice(0, HOSTED_CHOICE_ROOM), ...added, ...loaded.slice(HOSTED_CHOICE_ROOM)];
161​
162/**
163 * The author a filter names, as a choice: an author picked from the host's answer is on no
164 * loaded row, so it stays shown after the search that found it clears.
165 */
166export function selectedPullRequestAuthor(
167 facets: ReadonlyArray<PullRequestAuthorFacet>,
168 hosted: ReadonlyArray<PullRequestActor>,
169 value: string | undefined,
170): PullRequestAuthorFacet | undefined {
171 if (value === undefined) return undefined;
172 const key = normalize(value);
173 return (
174 facets.find((facet) => normalize(facet.actor.login) === key) ?? {
175 actor: hosted.find((actor) => normalize(actor.login) === key) ?? {
176 login: value,
177 name: null,
178 avatarUrl: null,
179 },
180 count: 0,
181 mergedCount: 0,
182 }
183 );
185​
186export function pullRequestLabelChoices(
187 facets: ReadonlyArray<PullRequestLabelFacet>,
188 hosted: ReadonlyArray<PullRequestLabel>,
189 query: string,
190): ReadonlyArray<PullRequestLabelFacet> {
191 const needle = normalize(query);
192 const loaded = facets.filter(
193 (facet) => needle === null || facet.name.toLowerCase().includes(needle),
194 );
195 const known = new Map(facets.map((facet) => [normalize(facet.name), facet]));
196 const seen = new Set(loaded.map((facet) => normalize(facet.name)));
197 const added: PullRequestLabelFacet[] = [];
198 for (const label of hosted) {
199 const key = normalize(label.name);
200 if (seen.has(key)) continue;
201 seen.add(key);
202 added.push(known.get(key) ?? { ...label, count: 0 });
203 }
204 return [...loaded, ...added];
206​
207export function pullRequestEntryViewer(
208 entry: ScopedEntry,
209 viewers: PullRequestViewers,
210): string | null {
211 return normalize(viewers[pullRequestViewerKey(entry)] ?? viewers[entry.host]);
213​
214function isAuthoredByViewer(entry: ScopedEntry, viewers: PullRequestViewers): boolean {
215 const viewer = pullRequestEntryViewer(entry, viewers);
216 return viewer !== null && normalize(entry.author?.login) === viewer;
218​
219export function matchesPullRequestQuery(entry: PullRequestListEntry, query: string): boolean {
220 const normalizedQuery = query.trim().toLowerCase();
221 if (normalizedQuery.length === 0) return true;
222 return `#${entry.number} ${entry.title} ${entry.repository} ${entry.headBranch} ${entry.author?.login ?? ""}`
223 .toLowerCase()
224 .includes(normalizedQuery);
226​
227export function filterPullRequestsByInvolvement<Entry extends ScopedEntry>(
228 entries: ReadonlyArray<Entry>,
229 viewers: PullRequestViewers,
230 involvement: PullRequestInvolvement,
231): ReadonlyArray<Entry> {
232 if (involvement === "reviewing") {
233 return entries.filter((entry) => entry.viewerReviewRequested);
234 }
235 if (involvement === "authored") {
236 return entries.filter((entry) => isAuthoredByViewer(entry, viewers));
237 }
238 return entries;
240​
241export function narrowPullRequestsToFilters<Entry extends PullRequestListEntry>(
242 entries: ReadonlyArray<Entry>,
243 filters: {
244 readonly state: PullRequestListState;
245 readonly projectId: string | undefined;
246 readonly host: string | undefined;
247 },
248): ReadonlyArray<Entry> {
249 return entries.filter(
250 (entry) =>
251 (filters.state === "all" || entry.state === filters.state) &&
252 (filters.projectId === undefined || entry.projectId === filters.projectId) &&
253 (filters.host === undefined || entry.host === filters.host),
254 );
256​
257export function matchesPullRequestFilters(
258 entry: PullRequestListEntry,
259 filters: PullRequestListFilters,
260 viewer?: string | null,
261): boolean {
262 const labels = entry.labels.map((label) => label.name.trim().toLowerCase());
263 const holds = (label: string) => labels.includes(label.trim().toLowerCase());
264 return (
265 (filters.draft === undefined || entry.isDraft === (filters.draft === "only")) &&
266 (filters.review === undefined ||
267 (filters.review === "none"
268 ? entry.reviewDecision === undefined
269 : entry.reviewDecision === filters.review)) &&
270 (filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
271 (filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
272 (filters.author === undefined ||
273 entry.author?.login.toLowerCase() ===
274 resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase())
275 );
277​
278export function groupPullRequestsByInvolvement<Entry extends ScopedEntry>(
279 entries: ReadonlyArray<Entry>,
280 viewers: PullRequestViewers,
281): ReadonlyArray<PullRequestGroup<Entry>> {
282 const buckets: Record<PullRequestGroupKey, Entry[]> = {
283 reviewRequested: [],
284 authored: [],
285 others: [],
286 };
287 for (const entry of entries) {
288 if (isAuthoredByViewer(entry, viewers)) {
289 buckets.authored.push(entry);
290 } else if (entry.viewerReviewRequested) {
291 buckets.reviewRequested.push(entry);
292 } else {
293 buckets.others.push(entry);
294 }
295 }
296 return (["authored", "reviewRequested", "others"] as const)
297 .filter((key) => buckets[key].length > 0)
298 .map((key) => ({ key, label: GROUP_LABELS[key], entries: buckets[key] }));
300​
301export function pullRequestEntryKey(entry: ScopedEntry): string {
302 const scope = entry.environmentId === undefined ? "" : `${entry.environmentId}:`;
303 return `${scope}${entry.host}:${entry.repository}#${entry.number}`;
305​
306export interface PullRequestStatsTarget {
307 readonly environmentId: EnvironmentId;
308 readonly input: {
309 readonly refs: ReadonlyArray<{
310 readonly projectId: ProjectId;
311 readonly repository: string;
312 readonly number: number;
313 }>;
314 };
316​
317export interface PullRequestStatsBatch extends PullRequestStatsTarget {
318 readonly keys: ReadonlySet<string>;
320​
321export type PullRequestStatsPolicy = "visible" | "eager";
322​
323export interface PullRequestStatsScope {
324 readonly key: string;
325 readonly policy: PullRequestStatsPolicy;
327​
328const MAX_PULL_REQUEST_STATS_REFS = 500;
329​
330export function pullRequestStatsKeysToRequest(
331 entriesByKey: ReadonlyMap<string, EnvironmentPullRequestEntry>,
332 enteredKeys: ReadonlySet<string>,
333 batches: ReadonlyArray<PullRequestStatsBatch>,
334 statsByRow: ReadonlyMap<string, unknown>,
335): ReadonlySet<string> {
336 const requested = new Set(batches.flatMap((batch) => [...batch.keys]));
337 return new Set(
338 [...enteredKeys].filter((key) => {
339 const entry = entriesByKey.get(key);
340 return (
341 entry !== undefined &&
342 entry.additions === 0 &&
343 entry.deletions === 0 &&
344 !requested.has(key) &&
345 !statsByRow.has(pullRequestDiffStatKey(entry))
346 );
347 }),
348 );
350​
351export function pullRequestStatsBatches(
352 entriesByKey: ReadonlyMap<string, EnvironmentPullRequestEntry>,
353 keys: ReadonlySet<string>,
354): ReadonlyArray<PullRequestStatsBatch> {
355 const byEnvironment = new Map<
356 EnvironmentId,
357 Array<{
358 readonly key: string;
359 readonly ref: PullRequestStatsTarget["input"]["refs"][number];
360 }>
361 >();
362 for (const key of keys) {
363 const entry = entriesByKey.get(key);
364 if (entry === undefined) continue;
365 const rows = byEnvironment.get(entry.environmentId) ?? [];
366 rows.push({
367 key,
368 ref: {
369 projectId: entry.projectId,
370 repository: entry.repository,
371 number: entry.number,
372 },
373 });
374 byEnvironment.set(entry.environmentId, rows);
375 }
376 return [...byEnvironment].flatMap(([environmentId, rows]) => {
377 const batches: PullRequestStatsBatch[] = [];
378 for (let index = 0; index < rows.length; index += MAX_PULL_REQUEST_STATS_REFS) {
379 const batch = rows.slice(index, index + MAX_PULL_REQUEST_STATS_REFS);
380 batches.push({
381 environmentId,
382 input: { refs: batch.map((row) => row.ref) },
383 keys: new Set(batch.map((row) => row.key)),
384 });
385 }
386 return batches;
387 });
389​
390/** Size sorting needs all loaded rows' stats; other modes need only nearby rows. */
391export function pullRequestStatsRequestBatches({
392 entriesByKey,
393 candidateKeys,
394 policy,
395 activeBatches,
396 statsByRow,
397 refresh = false,
398}: {
399 readonly entriesByKey: ReadonlyMap<string, EnvironmentPullRequestEntry>;
400 readonly candidateKeys: ReadonlySet<string>;
401 readonly policy: PullRequestStatsPolicy;
402 readonly activeBatches: ReadonlyArray<PullRequestStatsBatch>;
403 readonly statsByRow: ReadonlyMap<string, unknown>;
404 readonly refresh?: boolean;
405}): ReadonlyArray<PullRequestStatsBatch> {
406 const requestedKeys = policy === "eager" ? new Set(entriesByKey.keys()) : candidateKeys;
407 const keys = refresh
408 ? requestedKeys
409 : pullRequestStatsKeysToRequest(entriesByKey, requestedKeys, activeBatches, statsByRow);
410 return pullRequestStatsBatches(entriesByKey, keys);
412​
413export function pullRequestStatsRefreshBatches({
414 requestedScope,
415 currentScope,
416 entriesByKey,
417 candidateKeys,
418 statsByRow,
419}: {
420 readonly requestedScope: PullRequestStatsScope;
421 readonly currentScope: PullRequestStatsScope;
422 readonly entriesByKey: ReadonlyMap<string, EnvironmentPullRequestEntry>;
423 readonly candidateKeys: ReadonlySet<string>;
424 readonly statsByRow: ReadonlyMap<string, unknown>;
425}): ReadonlyArray<PullRequestStatsBatch> | null {
426 if (requestedScope.key !== currentScope.key || requestedScope.policy !== currentScope.policy) {
427 return null;
428 }
429 return pullRequestStatsRequestBatches({
430 entriesByKey,
431 candidateKeys,
432 policy: requestedScope.policy,
433 activeBatches: [],
434 statsByRow,
435 refresh: true,
436 });
438​
439export function retainVisiblePullRequestStatsBatches(
440 batches: ReadonlyArray<PullRequestStatsBatch>,
441 visibleKeys: ReadonlySet<string>,
442): ReadonlyArray<PullRequestStatsBatch> {
443 return batches.filter((batch) => {
444 for (const key of batch.keys) {
445 if (visibleKeys.has(key)) return true;
446 }
447 return false;
448 });
450​
451/** Recency pagination can introduce older priority rows; grouping pages would reorder read rows. */
452export function partitionPullRequestsWithPriority<Entry extends PullRequestListEntry>(
453 entries: ReadonlyArray<Entry>,
454 authored: ReadonlyArray<Entry>,
455 reviewRequested: ReadonlyArray<Entry>,
456): ReadonlyArray<PullRequestGroup<Entry>> {
457 const authoredByKey = new Map(authored.map((entry) => [pullRequestEntryKey(entry), entry]));
458 const reviewByKey = new Map(
459 reviewRequested.flatMap((entry) => {
460 const key = pullRequestEntryKey(entry);
461 return authoredByKey.has(key) ? [] : [[key, entry] as const];
462 }),
463 );
464 const others: Entry[] = [];
465 for (const entry of entries) {
466 const key = pullRequestEntryKey(entry);
467 if (authoredByKey.has(key)) {
468 authoredByKey.set(key, entry);
469 } else if (reviewByKey.has(key)) {
470 reviewByKey.set(key, entry);
471 } else {
472 others.push(entry);
473 }
474 }
475 const byRecency = (left: Entry, right: Entry) => right.updatedAt.localeCompare(left.updatedAt);
476 return (
477 [
478 { key: "authored", entries: [...authoredByKey.values()].toSorted(byRecency) },
479 { key: "reviewRequested", entries: [...reviewByKey.values()].toSorted(byRecency) },
480 { key: "others", entries: others },
481 ] as const
482 )
483 .filter((group) => group.entries.length > 0)
484 .map((group) => ({ ...group, label: GROUP_LABELS[group.key] }));
486​
487export type PullRequestDiffStats = ReadonlyMap<
488 string,
489 { readonly additions: number; readonly deletions: number }
490>;
491​
492/** New stats queries must not blank existing counts. */
493export function mergePullRequestDiffStats(
494 previous: PullRequestDiffStats,
495 stats: ReadonlyArray<{
496 readonly environmentId: string;
497 readonly projectId: string;
498 readonly number: number;
499 readonly additions: number;
500 readonly deletions: number;
501 }>,
502): PullRequestDiffStats {
503 if (stats.length === 0) return previous;
504 const next = new Map(previous);
505 for (const stat of stats) {
506 next.set(pullRequestDiffStatKey(stat), {
507 additions: stat.additions,
508 deletions: stat.deletions,
509 });
510 }
511 return next;
513​
514export const pullRequestDiffStatKey = (row: {
515 readonly environmentId: string;
516 readonly projectId: string;
517 readonly number: number;
518}) => `${row.environmentId} ${row.projectId} ${row.number}`;
519​
520export interface MergedPullRequestList {
521 readonly viewers: PullRequestViewers;
522 readonly providers: PullRequestListResult["providers"];
523 readonly entries: ReadonlyArray<EnvironmentPullRequestEntry>;
524 readonly errors: ReadonlyArray<EnvironmentPullRequestError>;
525 readonly truncated: boolean;
526 readonly nextCursors: Readonly<Record<string, PullRequestListCursors>>;
527 readonly truncatedEnvironments: ReadonlyArray<string>;
529​
530export function mergePullRequestLists(
531 answers: ReadonlyArray<readonly [EnvironmentId, PullRequestListResult]>,
532): MergedPullRequestList | null {
533 if (answers.length === 0) return null;
534 const viewers: Record<string, string> = {};
535 const truncatedEnvironments: string[] = [];
536 const providers = new Map<string, PullRequestListResult["providers"][number]>();
537 const entries: EnvironmentPullRequestEntry[] = [];
538 const errors: EnvironmentPullRequestError[] = [];
539 const nextCursors: Record<string, PullRequestListCursors> = {};
540 let truncated = false;
541 for (const [environmentId, answer] of answers) {
542 for (const [host, login] of Object.entries(answer.viewers)) {
543 viewers[`${environmentId} ${host}`] = login;
544 }
545 for (const provider of answer.providers) {
546 const held = providers.get(provider.host);
547 providers.set(
548 provider.host,
549 held === undefined
550 ? provider
551 : {
552 ...(held.configured ? held : provider),
553 projectCount: held.projectCount + provider.projectCount,
554 searchesOnHost: held.searchesOnHost && provider.searchesOnHost,
555 configured: held.configured || provider.configured,
556 },
557 );
558 }
559 entries.push(...answer.entries.map((entry) => ({ ...entry, environmentId })));
560 errors.push(...answer.errors.map((error) => ({ ...error, environmentId })));
561 truncated ||= answer.truncated;
562 if (answer.truncated) truncatedEnvironments.push(environmentId);
563 if (Object.keys(answer.nextCursors).length > 0) {
564 nextCursors[environmentId] = answer.nextCursors;
565 }
566 }
567 return {
568 viewers,
569 providers: [...providers.values()],
570 entries: entries.toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
571 errors,
572 truncated,
573 nextCursors,
574 truncatedEnvironments,
575 };
577​
578const SNAPSHOT_MAX_ENTRIES = 99;
579​
580type SnapshotStorage = Pick<Storage, "getItem" | "setItem">;
581​
582export const pullRequestEnvironmentSetKey = (environmentIds: ReadonlyArray<string>): string =>
583 [...environmentIds].sort((left, right) => left.localeCompare(right)).join(",");
584​
585const snapshotStorageKey = (environmentSetKey: string) =>
586 `t3.pullRequests.list:${environmentSetKey}`;
587​
588export interface PullRequestPartitionsSnapshot {
589 readonly authored: ReadonlyArray<EnvironmentPullRequestEntry>;
590 readonly reviewing: ReadonlyArray<EnvironmentPullRequestEntry>;
592​
593export interface PullRequestListSnapshot {
594 readonly scope: string;
595 readonly data: MergedPullRequestList;
596 readonly partitions?: PullRequestPartitionsSnapshot | undefined;
598​
599const EnvironmentPullRequestEntrySchema = Schema.Struct({
600 ...PullRequestListEntry.fields,
601 environmentId: EnvironmentId,
602});
603​
604const EnvironmentPullRequestErrorSchema = Schema.Struct({
605 ...PullRequestListProjectError.fields,
606 environmentId: EnvironmentId,
607});
608​
609const decodeSnapshot = Schema.decodeUnknownOption(
610 Schema.Struct({
611 scope: Schema.String,
612 data: Schema.Struct({
613 ...PullRequestListResult.fields,
614 entries: Schema.Array(EnvironmentPullRequestEntrySchema),
615 errors: Schema.Array(EnvironmentPullRequestErrorSchema),
616 nextCursors: Schema.Record(Schema.String, PullRequestListResult.fields.nextCursors),
617 truncatedEnvironments: Schema.Array(Schema.String),
618 }),
619 partitions: Schema.optional(
620 Schema.Struct({
621 authored: Schema.Array(EnvironmentPullRequestEntrySchema),
622 reviewing: Schema.Array(EnvironmentPullRequestEntrySchema),
623 }),
624 ),
625 }),
626);
627​
628export function readPullRequestListSnapshot(
629 storage: SnapshotStorage | undefined,
630 environmentSetKey: string,
631): PullRequestListSnapshot | null {
632 try {
633 const raw = storage?.getItem(snapshotStorageKey(environmentSetKey));
634 if (!raw) return null;
635 const decoded = decodeSnapshot(JSON.parse(raw));
636 return decoded._tag === "Some" ? decoded.value : null;
637 } catch {
638 return null;
639 }
641​
642export function writePullRequestListSnapshot(
643 storage: SnapshotStorage | undefined,
644 environmentSetKey: string,
645 snapshot: PullRequestListSnapshot,
646): void {
647 try {
648 storage?.setItem(
649 snapshotStorageKey(environmentSetKey),
650 JSON.stringify({
651 scope: snapshot.scope,
652 data: {
653 ...snapshot.data,
654 entries: snapshot.data.entries.slice(0, SNAPSHOT_MAX_ENTRIES),
655 errors: [],
656 nextCursors: {},
657 truncatedEnvironments: [],
658 },
659 ...(snapshot.partitions === undefined
660 ? {}
661 : {
662 partitions: {
663 authored: snapshot.partitions.authored.slice(0, SNAPSHOT_MAX_ENTRIES),
664 reviewing: snapshot.partitions.reviewing.slice(0, SNAPSHOT_MAX_ENTRIES),
665 },
666 }),
667 }),
668 );
669 } catch {}
671​
672/** Retain project scope during reconnect until projects arrive. */
673export function resolveProjectScope<Id extends string>(
674 projectId: Id | undefined,
675 projects: ReadonlyArray<{ readonly id: string }>,
676 projectsKnown: boolean,
677): Id | undefined {
678 if (projectId === undefined || !projectsKnown) return projectId;
679 return projects.some((project) => project.id === projectId) ? projectId : undefined;
681​
682export function findScopedProject<
683 Project extends { readonly id: string; readonly environmentId: string },
684>(
685 projects: ReadonlyArray<Project>,
686 environmentId: string | null | undefined,
687 projectId: string | undefined,
688): Project | undefined {
689 if (projectId === undefined) return undefined;
690 const matches = projects.filter((project) => project.id === projectId);
691 if (environmentId === null || environmentId === undefined) {
692 return matches.length === 1 ? matches[0] : undefined;
693 }
694 return matches.find((project) => project.environmentId === environmentId);
696​
697export function resolveQueryEnvironmentIds<Id extends string>(
698 environmentIds: ReadonlyArray<Id>,
699 projects: ReadonlyArray<{ readonly id: string; readonly environmentId: Id }>,
700 scopedProject: { readonly environmentId: Id } | undefined,
701 scopedProjectId: string | undefined,
702 projectsKnown: boolean,
703): ReadonlyArray<Id> {
704 if (scopedProject !== undefined) {
705 return environmentIds.filter((environmentId) => environmentId === scopedProject.environmentId);
706 }
707 if (scopedProjectId === undefined || !projectsKnown) return environmentIds;
708 const holders = new Set(
709 projects
710 .filter((project) => project.id === scopedProjectId)
711 .map((project) => project.environmentId),
712 );
713 return environmentIds.filter((environmentId) => holders.has(environmentId));
715​
716/** Retain connecting environments to avoid matching another server's project id. */
717export function resolveSelectedEnvironmentId<Id extends string>(
718 namedEnvironmentId: Id | undefined,
719 knownEnvironmentIds: ReadonlySet<Id>,
720 fallbackEnvironmentId: Id | null,
721): Id | null {
722 if (namedEnvironmentId === undefined) return fallbackEnvironmentId;
723 return knownEnvironmentIds.has(namedEnvironmentId) ? namedEnvironmentId : fallbackEnvironmentId;
725​
726/** Host search also matches bodies and commits absent from visible row fields. */
727export function scorePullRequestMatch(entry: PullRequestListEntry, query: string): number {
728 const needle = query.trim().toLowerCase();
729 if (needle.length === 0) return 0;
730 const number = needle.replace(/^#/u, "");
731 if (/^\d+$/u.test(number)) return String(entry.number) === number ? 100 : 0;
732​
733 const title = entry.title.toLowerCase();
734 const terms = needle.split(/\s+/u).filter((term) => term.length > 0);
735 if (title === needle) return 90;
736 if (title.includes(needle)) return 80;
737 if (terms.length > 1 && terms.every((term) => title.includes(term))) return 70;
738 if (entry.headBranch.toLowerCase().includes(needle)) return 60;
739 if ((entry.author?.login ?? "").toLowerCase().includes(needle)) return 50;
740 if (entry.repository.toLowerCase().includes(needle)) return 40;
741 if (terms.some((term) => title.includes(term))) return 30;
742 return 10;
744​
745export function rankPullRequestMatches<Entry extends PullRequestListEntry>(
746 entries: ReadonlyArray<Entry>,
747 query: string,
748): ReadonlyArray<Entry> {
749 if (query.trim().length === 0) return entries;
750 return entries.toSorted((left, right) => {
751 const byScore = scorePullRequestMatch(right, query) - scorePullRequestMatch(left, query);
752 return byScore !== 0 ? byScore : right.updatedAt.localeCompare(left.updatedAt);
753 });
755​
756export function rankPullRequestsByMergeReadiness<Entry extends PullRequestListEntry>(
757 entries: ReadonlyArray<Entry>,
758 hasMeasuredSize: (entry: Entry) => boolean = (entry) => entry.additions + entry.deletions > 0,
759): ReadonlyArray<Entry> {
760 const tier = (entry: Entry) => {
761 if (entry.mergeability === "conflicting") return 4;
762 if (entry.state !== "open") return 3;
763 if (entry.isDraft) return 2;
764 if (entry.checksState === "passing" && entry.reviewDecision === "approved") return 0;
765 if (entry.checksState === "passing") return 1;
766 return 2;
767 };
768 return entries.toSorted((left, right) => {
769 const byTier = tier(left) - tier(right);
770 if (byTier !== 0) return byTier;
771 const measured = Number(hasMeasuredSize(right)) - Number(hasMeasuredSize(left));
772 const sized = left.additions + left.deletions - (right.additions + right.deletions);
773 return measured || sized || right.updatedAt.localeCompare(left.updatedAt);
774 });
776​
777function rankByTierThenRecency<Entry extends PullRequestListEntry>(
778 entries: ReadonlyArray<Entry>,
779 tier: (entry: Entry) => number,
780): ReadonlyArray<Entry> {
781 const timestamp = (entry: Entry) => toSortableTimestamp(entry.updatedAt);
782 return entries.toSorted((left, right) => {
783 const byTier = tier(left) - tier(right);
784 if (byTier !== 0) return byTier;
785 const leftUpdated = timestamp(left);
786 const rightUpdated = timestamp(right);
787 const measured = Number(leftUpdated === null) - Number(rightUpdated === null);
788 if (measured !== 0) return measured;
789 if (leftUpdated === null || rightUpdated === null) return 0;
790 return rightUpdated - leftUpdated;
791 });
793​
794export function rankPullRequestsBlockedOnAuthor<Entry extends PullRequestListEntry>(
795 entries: ReadonlyArray<Entry>,
796): ReadonlyArray<Entry> {
797 return rankByTierThenRecency(entries, (entry) => {
798 if (entry.state !== "open") return 6;
799 if (entry.mergeability === "conflicting") return 0;
800 if (entry.reviewDecision === "changes-requested") return 1;
801 if (entry.checksState === "failing") return 2;
802 if (entry.isDraft) return 3;
803 if (entry.checksState === "passing" && entry.reviewDecision === "approved") return 5;
804 return 4;
805 });
807​
808function rankPullRequestsBlockedOnReviewer<Entry extends PullRequestListEntry>(
809 entries: ReadonlyArray<Entry>,
810): ReadonlyArray<Entry> {
811 return rankByTierThenRecency(entries, (entry) => (entry.state === "open" ? 0 : 1));
813​
814export function sortPullRequestGroups<Entry extends PullRequestListEntry>(
815 groups: ReadonlyArray<PullRequestGroup<Entry>>,
816 sort: PullRequestListSort,
817 searchText: string,
818 hasMeasuredSize: (entry: Entry) => boolean = (entry) => entry.additions + entry.deletions > 0,
819 involvement: PullRequestInvolvement = "all",
820): ReadonlyArray<PullRequestGroup<Entry>> {
821 const sortWithinGroups = (rank: (entries: ReadonlyArray<Entry>) => ReadonlyArray<Entry>) =>
822 groups.map((group) => ({ ...group, entries: rank(group.entries) }));
823​
824 if (sort === "ready") {
825 return searchText.trim().length === 0
826 ? sortWithinGroups((entries) => rankPullRequestsByMergeReadiness(entries, hasMeasuredSize))
827 : groups;
828 }
829 if (sort === "blocked") {
830 if (searchText.trim().length > 0) return groups;
831 const role = (key: PullRequestGroupKey) =>
832 key === "others" ? involvement : key === "authored" ? "authored" : "reviewing";
833 return groups.map((group) => {
834 const groupRole = role(group.key);
835 if (groupRole === "all") return group;
836 const rank =
837 groupRole === "authored"
838 ? rankPullRequestsBlockedOnAuthor
839 : rankPullRequestsBlockedOnReviewer;
840 return { ...group, entries: rank(group.entries) };
841 });
842 }
843 if (sort === "updated") return groups;
844​
845 const timestamp = (entry: Entry) =>
846 toSortableTimestamp(entry.updatedAt) ?? toSortableTimestamp(entry.createdAt) ?? 0;
847 return sortWithinGroups((entries) =>
848 entries.toSorted((left, right) => {
849 if (sort === "newest" || sort === "oldest") {
850 const leftCreated = toSortableTimestamp(left.createdAt);
851 const rightCreated = toSortableTimestamp(right.createdAt);
852 const measured = Number(rightCreated !== null) - Number(leftCreated !== null);
853 const dated = (leftCreated ?? 0) - (rightCreated ?? 0);
854 return (
855 measured || (sort === "newest" ? -dated : dated) || timestamp(right) - timestamp(left)
856 );
857 }
858 const measured = Number(hasMeasuredSize(right)) - Number(hasMeasuredSize(left));
859 const sized = left.additions + left.deletions - (right.additions + right.deletions);
860 return (
861 measured || (sort === "largest" ? -sized : sized) || timestamp(right) - timestamp(left)
862 );
863 }),
864 );
866​
867export function withDiffStat<
868 Entry extends PullRequestListEntry & { readonly environmentId: string },
869>(
870 entry: Entry,
871 statsByRow: ReadonlyMap<string, { readonly additions: number; readonly deletions: number }>,
872): Entry {
873 if (entry.additions !== 0 || entry.deletions !== 0) return entry;
874 const stat = statsByRow.get(pullRequestDiffStatKey(entry));
875 return stat === undefined ? entry : { ...entry, ...stat };
877​
878export interface PullRequestListOverride {
879 readonly state: PullRequestState;
880 readonly isDraft?: boolean;
881 readonly updatedAt: string;
882 readonly token: number;
883 readonly at: number;
885​
886export function pullRequestOverrideAfterAction(
887 entry: Pick<PullRequestListEntry, "state" | "isDraft">,
888 action: PullRequestAction,
889 now: Date,
890 token: number,
891): PullRequestListOverride | null {
892 const stamp = { updatedAt: now.toISOString(), token, at: now.getTime() };
893 switch (action) {
894 case "close":
895 return { state: "closed", ...stamp };
896 case "reopen":
897 return { state: "open", ...stamp };
898 case "merge":
899 return { state: "merged", ...stamp };
900 case "draft":
901 return { state: entry.state, isDraft: true, ...stamp };
902 case "ready":
903 return { state: entry.state, isDraft: false, ...stamp };
904 default:
905 return null;
906 }
908​
909export function applyPullRequestOverrides<Entry extends PullRequestListEntry>(
910 entries: ReadonlyArray<Entry>,
911 overrides: ReadonlyMap<string, PullRequestListOverride>,
912 keyOf: (entry: Entry) => string,
913 state: PullRequestListState,
914): ReadonlyArray<Entry> {
915 if (overrides.size === 0 && state === "all") return entries;
916 const out: Entry[] = [];
917 for (const entry of entries) {
918 const override = overrides.get(keyOf(entry));
919 if (state !== "all" && (override?.state ?? entry.state) !== state) continue;
920 out.push(override === undefined ? entry : { ...entry, ...override });
921 }
922 return overrides.size === 0 && out.length === entries.length ? entries : out;
924​
925export function reusePullRequestEntries<Entry extends PullRequestListEntry>(
926 previous: ReadonlyArray<Entry>,
927 next: ReadonlyArray<Entry>,
928 keyOf: (entry: Entry) => string,
929): ReadonlyArray<Entry> {
930 if (previous.length === 0) return next;
931 const held = new Map(previous.map((entry) => [keyOf(entry), entry]));
932 let reused = 0;
933 const out = next.map((entry) => {
934 const before = held.get(keyOf(entry));
935 if (before !== undefined && JSON.stringify(before) === JSON.stringify(entry)) {
936 reused += 1;
937 return before;
938 }
939 return entry;
940 });
941 return reused === next.length &&
942 previous.length === next.length &&
943 previous.every((entry, index) => keyOf(entry) === keyOf(next[index]!))
944 ? previous
945 : out;
947​
948const PULL_REQUEST_OVERRIDE_TRUST_MS = 60_000;
949​
950/** Retire overrides only when returned rows agree; partial-feed absence proves nothing. */
951export function settlePullRequestOverrides<Entry extends PullRequestListEntry>(
952 overrides: ReadonlyMap<string, PullRequestListOverride>,
953 answered: ReadonlyArray<Entry>,
954 keyOf: (entry: Entry) => string,
955 now: number,
956): ReadonlyMap<string, PullRequestListOverride> {
957 if (overrides.size === 0) return overrides;
958 const byKey = new Map(answered.map((entry) => [keyOf(entry), entry]));
959 const kept = new Map<string, PullRequestListOverride>();
960 for (const [key, override] of overrides) {
961 const row = byKey.get(key);
962 if (row === undefined) {
963 kept.set(key, override);
964 continue;
965 }
966 const agrees =
967 row.state === override.state &&
968 (override.isDraft === undefined || row.isDraft === override.isDraft);
969 const outranked = now - override.at > PULL_REQUEST_OVERRIDE_TRUST_MS;
970 if (!agrees && !outranked) kept.set(key, override);
971 }
972 return kept.size === overrides.size ? overrides : kept;
974​
975export type PullRequestQuickAction = "close" | "merge" | "ready" | "reopen";
976​
977export function pullRequestHostActions(
978 providers: ReadonlyArray<PullRequestListResult["providers"][number]>,
979): (
980 entry: Pick<EnvironmentPullRequestEntry, "host" | "provider">,
981) => ReadonlySet<PullRequestAction> {
982 const byHost = new Map(
983 providers.flatMap((provider) =>
984 provider.actions === undefined
985 ? []
986 : [[provider.host.toLowerCase(), new Set(provider.actions)] as const],
987 ),
988 );
989 const none = new Set<PullRequestAction>();
990 return (entry) =>
991 byHost.get(entry.host.toLowerCase()) ??
992 sourceControlClients.find(entry.provider)?.changeRequestActionsWhenUnreported ??
993 none;
995​
996export function pullRequestQuickActions(
997 entry: Pick<EnvironmentPullRequestEntry, "state" | "isDraft">,
998 hostActions: ReadonlySet<PullRequestAction>,
999): ReadonlyArray<PullRequestQuickAction> {
1000 const forState: ReadonlyArray<PullRequestQuickAction> =
1001 entry.state === "merged"
1002 ? []
1003 : entry.state === "closed"
1004 ? ["reopen"]
1005 : entry.isDraft
1006 ? ["close", "ready"]
1007 : ["close", "merge"];
1008 return forState.filter((action) => hostActions.has(action));
1010​
1011export function largestPullRequestReadCount(
1012 entries: ReadonlyArray<EnvironmentPullRequestEntry>,
1013): number {
1014 const counts = new Map<string, number>();
1015 for (const entry of entries) {
1016 const read = `${entry.environmentId} ${entry.host.toLowerCase()} ${
1017 sourceControlClients.find(entry.provider)?.changeRequestListScope === "host"
1018 ? ""
1019 : entry.repository.toLowerCase()
1020 }`;
1021 counts.set(read, (counts.get(read) ?? 0) + 1);
1023 return Math.max(0, ...counts.values());
1025​
1026export function findProjectForRepository<
1027 Project extends {
1028 readonly id: string;
1029 readonly environmentId: string;
1030 readonly repositoryIdentity?: RepositoryIdentity | null | undefined;
1031 },
1033 projects: ReadonlyArray<Project>,
1034 input: {
1035 readonly repository: string;
1036 readonly host?: string | undefined;
1037 readonly selectedEnvironmentId?: string | null | undefined;
1038 readonly scopedProjectId?: string | undefined;
1039 readonly scopedEnvironmentId?: string | null | undefined;
1040 },
1041): Project | undefined {
1042 const repository = input.repository.toLowerCase();
1043 const host = input.host?.toLowerCase();
1044 const candidates = projects.filter((project) => {
1045 if (
1046 input.selectedEnvironmentId != null &&
1047 project.environmentId !== input.selectedEnvironmentId
1048 ) {
1049 return false;
1051 const identity = project.repositoryIdentity;
1052 if (
1053 !identity ||
1054 sourceControlClients.repositorySelector(identity)?.toLowerCase() !== repository
1055 ) {
1056 return false;
1058 return (
1059 host === undefined ||
1060 sourceControlClients.changeRequestHost(identity, identity.provider) === host
1061 );
1062 });
1063 // Azure repository names can collide across projects on the same host.
1064 const scoped = findScopedProject(candidates, input.scopedEnvironmentId, input.scopedProjectId);
1065 return scoped ?? candidates[0];