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

pullRequestList.logic.ts

797 lines33.0 KB

1import * as Schema from "effect/Schema";
2​
3import {
4 EnvironmentId,
5 PullRequestListEntry,
6 PullRequestListProjectError,
7 PullRequestListResult,
8 resolvePullRequestAuthorFilter,
9} from "@t3tools/contracts";
10import type {
11 PullRequestDiffStat,
12 PullRequestInvolvement,
13 PullRequestListCursors,
14 PullRequestListFilters,
15 PullRequestListState,
16} from "@t3tools/contracts";
17​
18/**
19 * A listed change request with the environment that read it. Nothing on a row says which machine
20 * it came from, and the page unions every connected one — so acting on a row, refreshing it, or
21 * opening its detail all need the tag the listing itself does not carry.
22 */
23export interface EnvironmentPullRequestEntry extends PullRequestListEntry {
24 readonly environmentId: EnvironmentId;
26​
27export interface EnvironmentPullRequestStat extends PullRequestDiffStat {
28 readonly environmentId: EnvironmentId;
30​
31export interface EnvironmentPullRequestError extends PullRequestListProjectError {
32 readonly environmentId: EnvironmentId;
34​
35export type PullRequestGroupKey = "reviewRequested" | "authored" | "others";
36​
37export interface PullRequestGroup<Entry extends PullRequestListEntry = PullRequestListEntry> {
38 readonly key: PullRequestGroupKey;
39 readonly label: string;
40 readonly entries: ReadonlyArray<Entry>;
42​
43/**
44 * The signed-in account per host. Keyed `"<environmentId> <host>"` once a listing spans more than
45 * one environment: two machines can both reach github.com signed in as different people, and a
46 * single host-keyed record would let whichever answered last decide who "I" am — which is how
47 * every row of somebody's own work came to be filed under Others.
48 */
49export type PullRequestViewers = PullRequestListResult["viewers"];
50​
51/** A row plus the environment that read it, where the caller has one to give. */
52type ScopedEntry = PullRequestListEntry & { readonly environmentId?: string };
53​
54export const pullRequestViewerKey = (entry: ScopedEntry): string =>
55 `${entry.environmentId ?? ""} ${entry.host}`;
56​
57const GROUP_LABELS: Record<PullRequestGroupKey, string> = {
58 reviewRequested: "Review requested",
59 authored: "Authored",
60 others: "Others",
61};
62​
63function normalize(value: string | null | undefined): string | null {
64 const trimmed = value?.trim().toLowerCase() ?? "";
65 return trimmed.length > 0 ? trimmed : null;
67​
68/**
69 * The signed-in login for the host a row came from, or null where none was given. Shared by
70 * authorship matching here and by `author:me` resolution wherever a row's own viewer is needed.
71 */
72export function pullRequestEntryViewer(
73 entry: ScopedEntry,
74 viewers: PullRequestViewers,
75): string | null {
76 // The environment's own answer first; a plain host key is what a single-environment listing
77 // still writes, and what the snapshot from one carries.
78 return normalize(viewers[pullRequestViewerKey(entry)] ?? viewers[entry.host]);
80​
81/**
82 * Authorship is per host, not per provider kind: the same list can hold change requests from
83 * GitHub, GitLab and a GitHub Enterprise install, and the account that owns one says nothing
84 * about the others.
85 */
86function isAuthoredByViewer(entry: ScopedEntry, viewers: PullRequestViewers): boolean {
87 const viewer = pullRequestEntryViewer(entry, viewers);
88 return viewer !== null && normalize(entry.author?.login) === viewer;
90​
91/** What `review:` and `status:` take, in GitHub's spelling and in the contract's. */
92const REVIEW_VALUES: Record<string, PullRequestListFilters["review"]> = {
93 approved: "approved",
94 changes_requested: "changes-requested",
95 "changes-requested": "changes-requested",
96 required: "review-required",
97 "review-required": "review-required",
98 none: "none",
99};
100const CHECKS_VALUES: Record<string, PullRequestListFilters["checks"]> = {
101 success: "passing",
102 passing: "passing",
103 failure: "failing",
104 failing: "failing",
105};
106​
107/**
108 * One token of a typed query: a run of non-space characters in which a quoted stretch counts as
109 * part of the token, so `label:"needs design"` stays whole. An unbalanced quote is dropped rather
110 * than swallowing the rest of the line.
111 */
112const QUERY_TOKEN = /(?:[^\s"]|"[^"]*")+/g;
113/** The contract's own ceilings on a qualifier: this many names, each this long. */
114const MAX_QUALIFIER_VALUES = 10;
115const MAX_QUALIFIER_LENGTH = 200;
116​
117function qualifierValue(raw: string): string {
118 return raw.replaceAll('"', "").trim();
120​
121/** A qualifier's value as the list it may be: split on commas, each name unquoted on its own. */
122function splitQualifierList(raw: string): string[] {
123 // Quoting names one whole label however many commas it holds: `label:"needs,triage"` asks for
124 // the label written that way, not for either half of it.
125 if (/^\s*"[^"]*"\s*$/.test(raw)) {
126 const whole = qualifierValue(raw);
127 return whole.length === 0 ? [] : [whole];
128 }
129 return raw
130 .split(",")
131 .map((part) => qualifierValue(part))
132 .filter((part) => part.length > 0);
134​
135/**
136 * A typed query is written by hand, and the contract bounds what a qualifier may carry — so what
137 * is typed past those bounds is cut here rather than refused by the request that carries it.
138 */
139function boundedNames(names: ReadonlyArray<string>): string[] {
140 return names
141 .slice(0, MAX_QUALIFIER_VALUES)
142 .map((name) => name.slice(0, MAX_QUALIFIER_LENGTH).trim())
143 .filter((name) => name.length > 0);
145​
146/**
147 * A typed query split into the qualifiers the hosts can act on and the text that is left. Written
148 * GitHub's way — `label:foo`, `-label:"needs design"`, `author:octocat`, `draft:true`,
149 * `review:approved`, `status:success` — because a project's labels are its own and a menu cannot
150 * list them.
151 *
152 * A key this does not know is read as a label of that whole name: repositories namespace their
153 * labels with a colon — `size:XXL`, `area:web`, `vouch:trusted` — and someone typing one means
154 * the label, not a description that happens to contain it. `-size:XXL` excludes the same way.
155 *
156 * Quoting is the way back to plain text: `"size:XXL"` is searched for as written, which is what
157 * makes a literal search for a colon still possible. A known key whose value it does not take is
158 * text too, so a search for "status:" itself is still findable.
159 */
160export function parsePullRequestQuery(raw: string): {
161 readonly text: string;
162 readonly filters: PullRequestListFilters;
163} {
164 const text: string[] = [];
165 const labels: string[][] = [];
166 const excludedLabels: string[] = [];
167 let author: string | undefined;
168 let draft: PullRequestListFilters["draft"];
169 let review: PullRequestListFilters["review"];
170 let checks: PullRequestListFilters["checks"];
171 for (const [token] of raw.matchAll(QUERY_TOKEN)) {
172 const qualifier = /^(-?)([A-Za-z][A-Za-z0-9_-]*):(.*)$/.exec(token);
173 const value = qualifier === null ? "" : qualifierValue(qualifier[3] ?? "");
174 const negated = qualifier?.[1] === "-";
175 switch (value.length === 0 ? "" : (qualifier?.[2]?.toLowerCase() ?? "")) {
176 case "label": {
177 // GitHub's own OR: `label:a,b` is one qualifier satisfied by either name. Negated, the
178 // comma excludes each — a row carrying any of them goes.
179 const names = boundedNames(splitQualifierList(qualifier?.[3] ?? ""));
180 if (names.length === 0) break;
181 if (negated) excludedLabels.push(...names);
182 else labels.push(names);
183 continue;
184 }
185 case "author":
186 if (negated) break;
187 author = value.slice(0, MAX_QUALIFIER_LENGTH).trim();
188 continue;
189 case "draft":
190 if (negated || (value.toLowerCase() !== "true" && value.toLowerCase() !== "false")) break;
191 draft = value.toLowerCase() === "true" ? "only" : "hide";
192 continue;
193 case "review": {
194 const decision = negated ? undefined : REVIEW_VALUES[value.toLowerCase()];
195 if (decision === undefined) break;
196 review = decision;
197 continue;
198 }
199 case "status":
200 case "checks": {
201 const state = negated ? undefined : CHECKS_VALUES[value.toLowerCase()];
202 if (state === undefined) break;
203 checks = state;
204 continue;
205 }
206 case "":
207 break;
208 default:
209 // An unknown key, read as the namespaced label it almost always is. A pasted link is
210 // not one — `https://…` would otherwise become a label named after its own scheme.
211 if (!value.startsWith("/")) {
212 // The key names the namespace, so the bare parts of `size:S,XS` are both sizes. A part
213 // that already carries a colon names its whole label — `size:S,size:XS` is the same
214 // pair written out, and prefixing it again would ask for `size:size:XS`.
215 const names = boundedNames(
216 splitQualifierList(qualifier?.[3] ?? "").map((name) =>
217 name.includes(":") ? name : `${qualifier?.[2] ?? ""}:${name}`,
218 ),
219 );
220 if (names.length === 0) break;
221 if (negated) excludedLabels.push(...names);
222 else labels.push(names);
223 continue;
224 }
225 }
226 text.push(token);
227 }
228 return {
229 text: text.join(" "),
230 filters: {
231 ...(labels.length === 0 ? {} : { labels: labels.slice(0, MAX_QUALIFIER_VALUES) }),
232 ...(excludedLabels.length === 0
233 ? {}
234 : { excludedLabels: excludedLabels.slice(0, MAX_QUALIFIER_VALUES) }),
235 ...(author === undefined ? {} : { author }),
236 ...(draft === undefined ? {} : { draft }),
237 ...(review === undefined ? {} : { review }),
238 ...(checks === undefined ? {} : { checks }),
239 },
240 };
242​
243/** Free-text filter over the fields a row actually shows, plus `#123` / `123`. */
244export function matchesPullRequestQuery(entry: PullRequestListEntry, query: string): boolean {
245 const normalizedQuery = query.trim().toLowerCase();
246 if (normalizedQuery.length === 0) return true;
247 return `#${entry.number} ${entry.title} ${entry.repository} ${entry.headBranch} ${entry.author?.login ?? ""}`
248 .toLowerCase()
249 .includes(normalizedQuery);
251​
252/**
253 * The server returns the involvement superset for a state, so switching between the Reviewing
254 * and Authored tabs never waits on the network.
255 */
256export function filterPullRequestsByInvolvement<Entry extends ScopedEntry>(
257 entries: ReadonlyArray<Entry>,
258 viewers: PullRequestViewers,
259 involvement: PullRequestInvolvement,
260): ReadonlyArray<Entry> {
261 if (involvement === "reviewing") {
262 return entries.filter((entry) => entry.viewerReviewRequested);
263 }
264 if (involvement === "authored") {
265 return entries.filter((entry) => isAuthoredByViewer(entry, viewers));
266 }
267 return entries;
269​
270/**
271 * The rows already read, kept only where the filters now being asked about would keep them.
272 *
273 * Every combination of filters is its own question to the hosts, and asking a new one is no
274 * reason to blank the page: what has been read is narrowed here and stays until the answer for
275 * the new question replaces it. So this may only ever drop rows — a merged pull request cannot
276 * sit under "Open" for the round trip — and what it leaves is a subset of the answer rather than
277 * the answer itself.
278 *
279 * Only the filters a row can be judged by from its own fields. Involvement is left out because
280 * it needs to know who is signed in on each host, and the search text because searching is the
281 * hosts' own answer; both are narrowed where that knowledge already lives.
282 */
283export function narrowPullRequestsToFilters<Entry extends PullRequestListEntry>(
284 entries: ReadonlyArray<Entry>,
285 filters: {
286 readonly state: PullRequestListState;
287 readonly projectId: string | undefined;
288 readonly host: string | undefined;
289 },
290): ReadonlyArray<Entry> {
291 return entries.filter(
292 (entry) =>
293 (filters.state === "all" || entry.state === filters.state) &&
294 (filters.projectId === undefined || entry.projectId === filters.projectId) &&
295 (filters.host === undefined || entry.host === filters.host),
296 );
298​
299/**
300 * The further narrowings over rows that have already arrived, for the hosts that could not apply
301 * them themselves and for the moment before an answer that did lands.
302 *
303 * `checks` is absent because no listed row carries its check state: that one filter is the
304 * host's alone, and a row a host did not narrow stays rather than being guessed at.
305 *
306 * `viewer` is the row's own host's signed-in login, so `author:me` resolves against it rather
307 * than being compared as the literal name "me". Optional, and left unresolved without one.
308 */
309export function matchesPullRequestFilters(
310 entry: PullRequestListEntry,
311 filters: PullRequestListFilters,
312 viewer?: string | null,
313): boolean {
314 const labels = entry.labels.map((label) => label.name.trim().toLowerCase());
315 const holds = (label: string) => labels.includes(label.trim().toLowerCase());
316 return (
317 (filters.draft === undefined || entry.isDraft === (filters.draft === "only")) &&
318 (filters.review === undefined ||
319 (filters.review === "none"
320 ? entry.reviewDecision === undefined
321 : entry.reviewDecision === filters.review)) &&
322 (filters.labels === undefined || filters.labels.every((group) => group.some(holds))) &&
323 (filters.excludedLabels === undefined || !filters.excludedLabels.some(holds)) &&
324 (filters.author === undefined ||
325 entry.author?.login.toLowerCase() ===
326 resolvePullRequestAuthorFilter(filters.author, viewer).toLowerCase())
327 );
329​
330/**
331 * Only relationships the list data actually carries: no "previously reviewed" bucket is
332 * inferred, because the listing has no review history.
333 */
334export function groupPullRequestsByInvolvement<Entry extends ScopedEntry>(
335 entries: ReadonlyArray<Entry>,
336 viewers: PullRequestViewers,
337): ReadonlyArray<PullRequestGroup<Entry>> {
338 const buckets: Record<PullRequestGroupKey, Entry[]> = {
339 reviewRequested: [],
340 authored: [],
341 others: [],
342 };
343 for (const entry of entries) {
344 if (isAuthoredByViewer(entry, viewers)) {
345 buckets.authored.push(entry);
346 } else if (entry.viewerReviewRequested) {
347 buckets.reviewRequested.push(entry);
348 } else {
349 buckets.others.push(entry);
350 }
351 }
352 return (["reviewRequested", "authored", "others"] as const)
353 .filter((key) => buckets[key].length > 0)
354 .map((key) => ({ key, label: GROUP_LABELS[key], entries: buckets[key] }));
356​
357/**
358 * Repository plus number is unique on one host, so the host makes the key unique overall — and
359 * the environment on top of that, because two connected machines can hold the same repository and
360 * would otherwise contribute two rows under one key.
361 */
362export function pullRequestEntryKey(entry: ScopedEntry): string {
363 const scope = entry.environmentId === undefined ? "" : `${entry.environmentId}:`;
364 return `${scope}${entry.host}:${entry.repository}#${entry.number}`;
366​
367/**
368 * The priority groups built from the hosts' own answers rather than re-partitioned from the
369 * paginated feed. The feed is sliced by recency, so an older authored or review-requested row
370 * can be missing from its first page and arrive with a later one; grouping the loaded pages
371 * would then move it above rows already read. Here the partitions come whole from their own
372 * server-filtered reads, the feed fills "Others" in its own order, and a continuation can only
373 * append — a row it carries that a partition already holds is dropped rather than moved.
374 */
375export function partitionPullRequestsWithPriority<Entry extends PullRequestListEntry>(
376 entries: ReadonlyArray<Entry>,
377 authored: ReadonlyArray<Entry>,
378 reviewRequested: ReadonlyArray<Entry>,
379): ReadonlyArray<PullRequestGroup<Entry>> {
380 const authoredByKey = new Map(authored.map((entry) => [pullRequestEntryKey(entry), entry]));
381 // A row can be both authored and review-requested; authored wins, as the local grouping has it.
382 const reviewByKey = new Map(
383 reviewRequested.flatMap((entry) => {
384 const key = pullRequestEntryKey(entry);
385 return authoredByKey.has(key) ? [] : [[key, entry] as const];
386 }),
387 );
388 const others: Entry[] = [];
389 for (const entry of entries) {
390 const key = pullRequestEntryKey(entry);
391 // The feed's copy of a partitioned row is at least as fresh — it replaces in place.
392 if (authoredByKey.has(key)) {
393 authoredByKey.set(key, entry);
394 } else if (reviewByKey.has(key)) {
395 reviewByKey.set(key, entry);
396 } else {
397 others.push(entry);
398 }
399 }
400 const byRecency = (left: Entry, right: Entry) => right.updatedAt.localeCompare(left.updatedAt);
401 return (
402 [
403 { key: "reviewRequested", entries: [...reviewByKey.values()].toSorted(byRecency) },
404 { key: "authored", entries: [...authoredByKey.values()].toSorted(byRecency) },
405 { key: "others", entries: others },
406 ] as const
407 )
408 .filter((group) => group.entries.length > 0)
409 .map((group) => ({ ...group, label: GROUP_LABELS[group.key] }));
411​
412export type PullRequestDiffStats = ReadonlyMap<
413 string,
414 { readonly additions: number; readonly deletions: number }
415>;
416​
417/**
418 * The line counts held so far, with a new batch merged on. The stats read is keyed by the rows
419 * on screen, so adding or removing one row is a fresh query with nothing in it yet; replacing
420 * the map would blank every count already showing for the round trip. Merging by row identity
421 * keeps them until their replacements arrive.
422 */
423export function mergePullRequestDiffStats(
424 previous: PullRequestDiffStats,
425 stats: ReadonlyArray<{
426 readonly environmentId: string;
427 readonly projectId: string;
428 readonly number: number;
429 readonly additions: number;
430 readonly deletions: number;
431 }>,
432): PullRequestDiffStats {
433 if (stats.length === 0) return previous;
434 const next = new Map(previous);
435 for (const stat of stats) {
436 next.set(diffStatKey(stat), { additions: stat.additions, deletions: stat.deletions });
437 }
438 return next;
440​
441/** A project id only names a project within its own environment, so the key carries both. */
442const diffStatKey = (row: {
443 readonly environmentId: string;
444 readonly projectId: string;
445 readonly number: number;
446}) => `${row.environmentId} ${row.projectId} ${row.number}`;
447​
448/**
449 * Every connected environment's listing, read as one list.
450 *
451 * `nextCursors` is keyed by environment rather than by repository: a cursor only means anything
452 * to the host that issued it, and two machines can hold the same repository. `viewers` is not —
453 * a host names one account, and the same host reached from two machines is the same account.
454 */
455export interface MergedPullRequestList {
456 /** Keyed `"<environmentId> <host>"`, so one host's two accounts stay two accounts. */
457 readonly viewers: PullRequestViewers;
458 readonly providers: PullRequestListResult["providers"];
459 readonly entries: ReadonlyArray<EnvironmentPullRequestEntry>;
460 readonly errors: ReadonlyArray<EnvironmentPullRequestError>;
461 readonly truncated: boolean;
462 readonly nextCursors: Readonly<Record<string, PullRequestListCursors>>;
463 /**
464 * The environments with rows still on their hosts. Those with a cursor are continued from it;
465 * the rest can only be reached by asking them for a longer page, and are named here so that
466 * asking still happens once every other environment has run out of cursors.
467 */
468 readonly truncatedEnvironments: ReadonlyArray<string>;
470​
471/**
472 * The environments' answers folded into one. A host reached from more than one environment is one
473 * row in the switcher, readable if any environment could read it and searched on the host only if
474 * every one of them did — a host answering unnarrowed anywhere still needs the local pass.
475 */
476export function mergePullRequestLists(
477 answers: ReadonlyArray<readonly [EnvironmentId, PullRequestListResult]>,
478): MergedPullRequestList | null {
479 if (answers.length === 0) return null;
480 const viewers: Record<string, string> = {};
481 const truncatedEnvironments: string[] = [];
482 const providers = new Map<string, PullRequestListResult["providers"][number]>();
483 const entries: EnvironmentPullRequestEntry[] = [];
484 const errors: EnvironmentPullRequestError[] = [];
485 const nextCursors: Record<string, PullRequestListCursors> = {};
486 let truncated = false;
487 for (const [environmentId, answer] of answers) {
488 for (const [host, login] of Object.entries(answer.viewers)) {
489 viewers[`${environmentId} ${host}`] = login;
490 }
491 for (const provider of answer.providers) {
492 const held = providers.get(provider.host);
493 providers.set(
494 provider.host,
495 held === undefined
496 ? provider
497 : {
498 ...(held.configured ? held : provider),
499 projectCount: held.projectCount + provider.projectCount,
500 searchesOnHost: held.searchesOnHost && provider.searchesOnHost,
501 configured: held.configured || provider.configured,
502 },
503 );
504 }
505 entries.push(...answer.entries.map((entry) => ({ ...entry, environmentId })));
506 errors.push(...answer.errors.map((error) => ({ ...error, environmentId })));
507 truncated ||= answer.truncated;
508 if (answer.truncated) truncatedEnvironments.push(environmentId);
509 if (Object.keys(answer.nextCursors).length > 0) {
510 nextCursors[environmentId] = answer.nextCursors;
511 }
512 }
513 return {
514 viewers,
515 providers: [...providers.values()],
516 entries: entries.toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
517 errors,
518 truncated,
519 nextCursors,
520 truncatedEnvironments,
521 };
523​
524/** One page is what the list itself starts with, and all a cold start needs to look warm. */
525const SNAPSHOT_MAX_ENTRIES = 99;
526​
527type SnapshotStorage = Pick<Storage, "getItem" | "setItem">;
528​
529/**
530 * Keyed by the whole set of environments the list was read from: connecting or dropping one
531 * changes which rows belong on the page, and a snapshot taken from a different set would
532 * hydrate rows no longer being read.
533 */
534export const pullRequestEnvironmentSetKey = (environmentIds: ReadonlyArray<string>): string =>
535 [...environmentIds].sort((left, right) => left.localeCompare(right)).join(",");
536​
537const snapshotStorageKey = (environmentSetKey: string) =>
538 `t3.pullRequests.list:${environmentSetKey}`;
539​
540/**
541 * The priority groups' own server-filtered answers, carried with the feed. An authored pull
542 * request older than the feed's first page lives only in these, so a snapshot without them
543 * cold-starts into an Authored group missing exactly the rows that made it worth having.
544 */
545export interface PullRequestPartitionsSnapshot {
546 readonly authored: ReadonlyArray<EnvironmentPullRequestEntry>;
547 readonly reviewing: ReadonlyArray<EnvironmentPullRequestEntry>;
549​
550export interface PullRequestListSnapshot {
551 readonly scope: string;
552 readonly data: MergedPullRequestList;
553 readonly partitions?: PullRequestPartitionsSnapshot | undefined;
555​
556/**
557 * Decoded with the contract's own schema rather than trusted from a cast: storage is writable
558 * by anything in the origin and by any past version of this app, and one malformed row would
559 * otherwise crash the list on every reload until the key is cleared. A snapshot from before a
560 * schema change is rejected the same way, which is exactly the cold start it would have broken.
561 */
562const EnvironmentPullRequestEntrySchema = Schema.Struct({
563 ...PullRequestListEntry.fields,
564 environmentId: EnvironmentId,
565});
566​
567const EnvironmentPullRequestErrorSchema = Schema.Struct({
568 ...PullRequestListProjectError.fields,
569 environmentId: EnvironmentId,
570});
571​
572const decodeSnapshot = Schema.decodeUnknownOption(
573 Schema.Struct({
574 scope: Schema.String,
575 data: Schema.Struct({
576 ...PullRequestListResult.fields,
577 entries: Schema.Array(EnvironmentPullRequestEntrySchema),
578 errors: Schema.Array(EnvironmentPullRequestErrorSchema),
579 // Per environment here, unlike the wire shape, which is per repository within one.
580 nextCursors: Schema.Record(Schema.String, PullRequestListResult.fields.nextCursors),
581 truncatedEnvironments: Schema.Array(Schema.String),
582 }),
583 // Optional so a snapshot written before the partitions existed still hydrates the feed.
584 partitions: Schema.optional(
585 Schema.Struct({
586 authored: Schema.Array(EnvironmentPullRequestEntrySchema),
587 reviewing: Schema.Array(EnvironmentPullRequestEntrySchema),
588 }),
589 ),
590 }),
591);
592​
593/**
594 * The last list answered for this environment, brought back across a reload. The registry the
595 * queries live in is recreated with the renderer, so without this a revisit cold-starts into
596 * skeletons even though almost every row is unchanged; hydrated, the stale rows render at once
597 * and the live read reconciles them in place by key. Errors are not carried — a failure is
598 * never cached, and yesterday's is not this morning's.
599 */
600export function readPullRequestListSnapshot(
601 storage: SnapshotStorage | undefined,
602 environmentSetKey: string,
603): PullRequestListSnapshot | null {
604 try {
605 const raw = storage?.getItem(snapshotStorageKey(environmentSetKey));
606 if (!raw) return null;
607 const decoded = decodeSnapshot(JSON.parse(raw));
608 return decoded._tag === "Some" ? decoded.value : null;
609 } catch {
610 return null;
611 }
613​
614export function writePullRequestListSnapshot(
615 storage: SnapshotStorage | undefined,
616 environmentSetKey: string,
617 snapshot: PullRequestListSnapshot,
618): void {
619 try {
620 storage?.setItem(
621 snapshotStorageKey(environmentSetKey),
622 JSON.stringify({
623 scope: snapshot.scope,
624 data: {
625 ...snapshot.data,
626 entries: snapshot.data.entries.slice(0, SNAPSHOT_MAX_ENTRIES),
627 // A failure is never cached and yesterday's is not this morning's; a cursor names a
628 // position in a listing the host has long since forgotten.
629 errors: [],
630 nextCursors: {},
631 // Where a listing stopped is as stale as the cursor that named it.
632 truncatedEnvironments: [],
633 },
634 ...(snapshot.partitions === undefined
635 ? {}
636 : {
637 partitions: {
638 authored: snapshot.partitions.authored.slice(0, SNAPSHOT_MAX_ENTRIES),
639 reviewing: snapshot.partitions.reviewing.slice(0, SNAPSHOT_MAX_ENTRIES),
640 },
641 }),
642 }),
643 );
644 } catch {
645 // Storage can be full or denied; the snapshot is a convenience, not a record.
646 }
648​
649/**
650 * The project scope to actually ask for. A `projectId` in the URL outlives the environment it
651 * came from, and one from elsewhere narrows the listing to nothing — an empty page with no
652 * visible filter explaining it, since the switcher has no such project to show as selected. So
653 * an id the environment does not have is dropped.
654 *
655 * Until `projectsKnown`, the id is kept rather than dropped: an environment that has not
656 * reported yet is not the same as one without the project, and dropping first would show every
657 * project's pull requests for a moment before narrowing back down.
658 */
659export function resolveProjectScope<Id extends string>(
660 projectId: Id | undefined,
661 projects: ReadonlyArray<{ readonly id: string }>,
662 projectsKnown: boolean,
663): Id | undefined {
664 if (projectId === undefined || !projectsKnown) return projectId;
665 return projects.some((project) => project.id === projectId) ? projectId : undefined;
667​
668/**
669 * The project an id names, on the server that owns it. A project id is only unique within its own
670 * environment, so an id alone can name two projects on two connected machines: with a server in
671 * hand the answer is exact, and without one it is only given where a single environment has that
672 * id — narrowing to the wrong machine reads an empty list nobody asked for.
673 */
674export function findScopedProject<
675 Project extends { readonly id: string; readonly environmentId: string },
676>(
677 projects: ReadonlyArray<Project>,
678 environmentId: string | null | undefined,
679 projectId: string | undefined,
680): Project | undefined {
681 if (projectId === undefined) return undefined;
682 const matches = projects.filter((project) => project.id === projectId);
683 if (environmentId === null || environmentId === undefined) {
684 return matches.length === 1 ? matches[0] : undefined;
685 }
686 return matches.find((project) => project.environmentId === environmentId);
688​
689/**
690 * Which environments a listing should ask, once the project scope is known. Scoping to a project
691 * scopes to the server that owns it, saving every other server a read that could only answer with
692 * nothing. Where an id is ambiguous — two servers holding the same project id, with no server
693 * named — only the servers that actually hold that id are asked: a server without it may still
694 * hold an unrelated project of its own under the same string, and asking it would return that
695 * project's rows rather than an honest empty answer.
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 // Before the servers have said what they hold, an id nothing matches is an id nothing has been
708 // asked about yet — reading none of them would show an empty page for a project that is there.
709 if (scopedProjectId === undefined || !projectsKnown) return environmentIds;
710 const holders = new Set(
711 projects
712 .filter((project) => project.id === scopedProjectId)
713 .map((project) => project.environmentId),
714 );
715 return environmentIds.filter((environmentId) => holders.has(environmentId));
717​
718/**
719 * The server a saved selection names, before its project is looked up against it. Still
720 * connecting is not the same as gone: a server the workspace already knows about is kept named
721 * here even while it has nothing to answer with yet, so the lookup that follows finds nothing
722 * under it rather than falling through to a different server's project of the same id. Only a
723 * name outside the workspace's whole catalog falls back to the page's own scope, which is what
724 * lets a link to a server since removed still resolve by project id alone.
725 */
726export function resolveSelectedEnvironmentId<Id extends string>(
727 namedEnvironmentId: Id | undefined,
728 knownEnvironmentIds: ReadonlySet<Id>,
729 fallbackEnvironmentId: Id | null,
730): Id | null {
731 if (namedEnvironmentId === undefined) return fallbackEnvironmentId;
732 return knownEnvironmentIds.has(namedEnvironmentId) ? namedEnvironmentId : fallbackEnvironmentId;
734​
735/**
736 * How well a row answers the text that was searched for, as a number to order by.
737 *
738 * Every host searches more than a row shows — GitHub reads bodies and commit messages, GitLab
739 * and Bitbucket read descriptions — so a result can be a real match with nothing on the row to
740 * show for it. Ordering those by recency alone is what puts an apparently unrelated pull request
741 * between two obvious ones. They are still results, so they are still shown; they are shown last,
742 * under the rows whose own words matched.
743 *
744 * The scale is deliberately coarse. It sorts rows into "this is the one", "this mentions it" and
745 * "the host says so", which is as fine a judgement as the row's own fields support.
746 */
747export function scorePullRequestMatch(entry: PullRequestListEntry, query: string): number {
748 const needle = query.trim().toLowerCase();
749 if (needle.length === 0) return 0;
750 const number = needle.replace(/^#/u, "");
751 // Asking for a number is asking for one pull request, and it is the answer or it is not.
752 if (/^\d+$/u.test(number)) return String(entry.number) === number ? 100 : 0;
753​
754 const title = entry.title.toLowerCase();
755 const terms = needle.split(/\s+/u).filter((term) => term.length > 0);
756 if (title === needle) return 90;
757 if (title.includes(needle)) return 80;
758 // Every word, in any order: "wizard welcome" is still about the welcome wizard.
759 if (terms.length > 1 && terms.every((term) => title.includes(term))) return 70;
760 if (entry.headBranch.toLowerCase().includes(needle)) return 60;
761 if ((entry.author?.login ?? "").toLowerCase().includes(needle)) return 50;
762 if (entry.repository.toLowerCase().includes(needle)) return 40;
763 if (terms.some((term) => title.includes(term))) return 30;
764 // The host matched something this row does not show — a description, a comment, a commit.
765 return 10;
767​
768/**
769 * Search results in the order they answer the question, most convincing first, and by recency
770 * among equals. Only for a search: without one, a listing is a timeline and recency is the order.
771 */
772export function rankPullRequestMatches<Entry extends PullRequestListEntry>(
773 entries: ReadonlyArray<Entry>,
774 query: string,
775): ReadonlyArray<Entry> {
776 if (query.trim().length === 0) return entries;
777 return entries.toSorted((left, right) => {
778 const byScore = scorePullRequestMatch(right, query) - scorePullRequestMatch(left, query);
779 return byScore !== 0 ? byScore : right.updatedAt.localeCompare(left.updatedAt);
780 });
782​
783/**
784 * A row with the line counts that arrived after it did. Only where the host left them out — a
785 * listing that carried them is not second-guessed — and only where they have arrived, since a row
786 * draws perfectly well without them in the meantime.
787 */
788export function withDiffStat<
789 Entry extends PullRequestListEntry & { readonly environmentId: string },
790>(
791 entry: Entry,
792 statsByRow: ReadonlyMap<string, { readonly additions: number; readonly deletions: number }>,
793): Entry {
794 if (entry.additions !== 0 || entry.deletions !== 0) return entry;
795 const stat = statsByRow.get(diffStatKey(entry));
796 return stat === undefined ? entry : { ...entry, ...stat };