Open History to see the last commit
1import * as Schema from "effect/Schema";
2import * as HttpServerRespondable from "effect/unstable/http/HttpServerRespondable";
3import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
4
5import {
6 IsoDateTime,
7 NonNegativeInt,
8 PositiveInt,
9 ProjectId,
10 TrimmedNonEmptyString,
11} from "./baseSchemas.ts";
12import { SourceControlProviderKind } from "./sourceControl.ts";
13
14export const PullRequestInvolvement = Schema.Literals(["all", "reviewing", "authored"]);
15export type PullRequestInvolvement = typeof PullRequestInvolvement.Type;
16
17export const PullRequestState = Schema.Literals(["open", "closed", "merged"]);
18export type PullRequestState = typeof PullRequestState.Type;
19
20/**
21 * What a listing asks for, which is the three states a change request can be in plus the option
22 * to span them. Separate from `PullRequestState` because a change request is never "all" — only
23 * a request for one can be.
24 */
25export const PullRequestListState = Schema.Literals(["all", "open", "closed", "merged"]);
26export type PullRequestListState = typeof PullRequestListState.Type;
27
28/** Where a review stands overall, as a host that summarises its reviews reports it. */
29export const PullRequestReviewDecision = Schema.Literals([
30 "approved",
31 "changes-requested",
32 "review-required",
33]);
34export type PullRequestReviewDecision = typeof PullRequestReviewDecision.Type;
35
36/** One qualifier's value, bounded because it is written into a host's own search query. */
37const PullRequestQualifierValue = TrimmedNonEmptyString.check(Schema.isMaxLength(200));
38const PullRequestQualifierValues = Schema.Array(PullRequestQualifierValue).check(
39 Schema.isMaxLength(10),
40);
41
42/**
43 * Narrowings beyond state and involvement, each absent by default — an absent field filters
44 * nothing, which is what every listing did before there were any. Optional as a whole so a page
45 * and a server of different ages still speak to each other.
46 *
47 * `checks` is host-side only: no row carries its own check state, so a host that cannot match it
48 * answers unnarrowed rather than the page pretending to know.
49 */
50export const PullRequestListFilters = Schema.Struct({
51 draft: Schema.optional(Schema.Literals(["only", "hide"])),
52 review: Schema.optional(
53 Schema.Literals(["approved", "changes-requested", "review-required", "none"]),
54 ),
55 checks: Schema.optional(Schema.Literals(["passing", "failing"])),
56 /**
57 * Labels as GitHub's own search reads them: each group is one `label:` qualifier, a row must
58 * satisfy every group, and a group holding several names is satisfied by any one of them —
59 * `label:size:S,size:XS` finds either size. Typed rather than picked, since a project's labels
60 * are its own and no menu can list them. Bounded because each becomes a host search qualifier.
61 */
62 labels: Schema.optional(Schema.Array(PullRequestQualifierValues).check(Schema.isMaxLength(10))),
63 excludedLabels: Schema.optional(PullRequestQualifierValues),
64 /** One login, as `author:` names it. */
65 author: Schema.optional(PullRequestQualifierValue),
66});
67export type PullRequestListFilters = typeof PullRequestListFilters.Type;
68
69/** The one-glyph summary of a change request's checks, as its list row wears it. */
70export const PullRequestChecksState = Schema.Literals(["passing", "failing", "pending"]);
71export type PullRequestChecksState = typeof PullRequestChecksState.Type;
72
73export const PullRequestMergeability = Schema.Literals(["mergeable", "conflicting", "unknown"]);
74export type PullRequestMergeability = typeof PullRequestMergeability.Type;
75
76export const PullRequestMergeMethod = Schema.Literals(["merge", "squash", "rebase"]);
77export type PullRequestMergeMethod = typeof PullRequestMergeMethod.Type;
78
79export const PullRequestAction = Schema.Literals([
80 "merge",
81 "ready",
82 "draft",
83 "close",
84 "reopen",
85 /** Bring the base branch's commits into this one, which is what unblocks a stale branch. */
86 "update-branch",
87 /**
88 * Hand the merge to the host: it waits for whatever it requires — a green pipeline, the
89 * approvals, an unblocked branch — and merges without anybody coming back. Separate from
90 * `merge` because the two answer different questions. `merge` is refused outright by a host
91 * that is not ready yet, and this one is for exactly that moment.
92 */
93 "enable-auto-merge",
94 /** Take the standing instruction back, which leaves the change request where it was. */
95 "disable-auto-merge",
96 /** Open a new change request that reverses a merged one. */
97 "revert",
98 /** Allow Actions workflows from a fork pull request to begin running. */
99 "approve-workflows",
100]);
101export type PullRequestAction = typeof PullRequestAction.Type;
102
103/**
104 * How a stale branch catches up with its base: a merge commit, or a rebase onto it. The two are
105 * the host's own choices, not this page's — GitHub offers both and refuses a rebase it cannot
106 * replay, so what is offered comes from the host and what is allowed comes from the viewer.
107 */
108export const PullRequestUpdateMethod = Schema.Literals(["merge", "rebase"]);
109export type PullRequestUpdateMethod = typeof PullRequestUpdateMethod.Type;
110
111/**
112 * Where the branch stands against the base it would merge into. Separate from `mergeability`,
113 * which answers a different question: a branch can be behind and still merge cleanly, and that
114 * pairing — out of date, no conflicts — is the one an update button exists for.
115 *
116 * "unknown" where the host was not asked or could not say, which is every host but GitHub and
117 * every pull request whose head repository could not be compared.
118 */
119export const PullRequestBaseComparison = Schema.Literals(["up-to-date", "behind", "unknown"]);
120export type PullRequestBaseComparison = typeof PullRequestBaseComparison.Type;
121
122export const PullRequestActor = Schema.Struct({
123 login: TrimmedNonEmptyString,
124 name: Schema.NullOr(Schema.String),
125 /** Null where a host does not report one, which is what the initials fall back to. */
126 avatarUrl: Schema.NullOr(Schema.String),
127});
128export type PullRequestActor = typeof PullRequestActor.Type;
129
130export const PullRequestLabel = Schema.Struct({
131 name: TrimmedNonEmptyString,
132 color: Schema.NullOr(Schema.String),
133});
134export type PullRequestLabel = typeof PullRequestLabel.Type;
135
136export const PullRequestCheckStatus = Schema.Literals([
137 "pending",
138 "action-required",
139 "success",
140 "failure",
141 "skipped",
142 "neutral",
143 "cancelled",
144]);
145export type PullRequestCheckStatus = typeof PullRequestCheckStatus.Type;
146
147export const PullRequestCheck = Schema.Struct({
148 name: TrimmedNonEmptyString,
149 status: PullRequestCheckStatus,
150 description: Schema.NullOr(Schema.String),
151 url: Schema.NullOr(Schema.String),
152});
153export type PullRequestCheck = typeof PullRequestCheck.Type;
154
155/**
156 * The reactions a remark can carry. GitHub's eight, which is also what the picker offers: GitLab
157 * accepts any emoji as an award, and the ones outside this set are read as nothing rather than
158 * shown under a name no other host would recognise.
159 */
160export const PullRequestReactionContent = Schema.Literals([
161 "thumbs-up",
162 "thumbs-down",
163 "laugh",
164 "hooray",
165 "confused",
166 "heart",
167 "rocket",
168 "eyes",
169]);
170export type PullRequestReactionContent = typeof PullRequestReactionContent.Type;
171
172/** One reaction and everyone behind it, which is what the hover on a reaction pill says. */
173export const PullRequestReaction = Schema.Struct({
174 content: PullRequestReactionContent,
175 count: PositiveInt,
176 /**
177 * Who reacted, as far as the host named them. A host that reports fewer names than it counts
178 * leaves the rest out, so this is never longer than `count` and may be shorter. When
179 * `viewerHasReacted` is true, the viewer's own login is left out of this list — the page names
180 * them "You" instead — but `count` still counts them along with everyone else.
181 */
182 actors: Schema.Array(TrimmedNonEmptyString),
183 /** The signed-in account is one of them, so pressing the pill takes the reaction back. */
184 viewerHasReacted: Schema.Boolean,
185});
186export type PullRequestReaction = typeof PullRequestReaction.Type;
187
188export const PullRequestCommentKind = Schema.Literals([
189 "issue-comment",
190 "review-comment",
191 "review",
192]);
193export type PullRequestCommentKind = typeof PullRequestCommentKind.Type;
194
195export const PullRequestComment = Schema.Struct({
196 id: TrimmedNonEmptyString,
197 kind: PullRequestCommentKind,
198 author: Schema.NullOr(PullRequestActor),
199 body: Schema.String,
200 createdAt: IsoDateTime,
201 url: Schema.NullOr(Schema.String),
202 path: Schema.NullOr(Schema.String),
203 reviewState: Schema.NullOr(Schema.String),
204 /** Absent from a host with no reactions at all, which is a different thing from none on this. */
205 reactions: Schema.optional(Schema.Array(PullRequestReaction)),
206});
207export type PullRequestComment = typeof PullRequestComment.Type;
208
209/**
210 * Which file a diff line belongs to: `left` is the version before the change, `right` the
211 * version after. A comment has to name one, because a unified diff shows both at once and the
212 * same line number means two different lines.
213 */
214export const PullRequestDiffSide = Schema.Literals(["left", "right"]);
215export type PullRequestDiffSide = typeof PullRequestDiffSide.Type;
216
217/** What submitting a review says about the change, beyond the words in it. */
218export const PullRequestReviewVerdict = Schema.Literals(["comment", "approve", "request-changes"]);
219export type PullRequestReviewVerdict = typeof PullRequestReviewVerdict.Type;
220
221export const PullRequestThreadComment = Schema.Struct({
222 id: TrimmedNonEmptyString,
223 author: Schema.NullOr(PullRequestActor),
224 body: Schema.String,
225 createdAt: IsoDateTime,
226 url: Schema.NullOr(Schema.String),
227 reactions: Schema.optional(Schema.Array(PullRequestReaction)),
228});
229export type PullRequestThreadComment = typeof PullRequestThreadComment.Type;
230
231/**
232 * A conversation anchored to a line of the diff. The detail carries these alongside `comments`
233 * rather than instead of them: the timeline wants one flat, chronological list, and the diff
234 * wants whole threads pinned to their line — the same remarks, read two different ways.
235 */
236export const PullRequestReviewThread = Schema.Struct({
237 id: TrimmedNonEmptyString,
238 path: TrimmedNonEmptyString,
239 /** Null when the host anchors the thread to a file rather than to a line. */
240 line: Schema.NullOr(PositiveInt),
241 side: PullRequestDiffSide,
242 isResolved: Schema.Boolean,
243 /**
244 * The line the thread was written against is no longer in the diff, so it cannot be shown
245 * against the code. Such a thread is listed separately rather than pinned to the wrong line.
246 */
247 isOutdated: Schema.Boolean,
248 comments: Schema.Array(PullRequestThreadComment),
249 /** Host-reported total, when this thread was read in pages. */
250 commentCount: Schema.optional(NonNegativeInt),
251 /** Opaque cursor for the next comment page. Absent once this thread is whole. */
252 nextCommentsCursor: Schema.optional(TrimmedNonEmptyString),
253});
254export type PullRequestReviewThread = typeof PullRequestReviewThread.Type;
255
256/**
257 * Whether a reviewer is a person or a group of them the host addresses as one. GitHub is the only
258 * host here that takes a review request for a team; the others name individuals only, so nothing
259 * they report is ever anything but a user.
260 */
261export const PullRequestReviewerKind = Schema.Literals(["user", "team"]);
262export type PullRequestReviewerKind = typeof PullRequestReviewerKind.Type;
263
264/**
265 * Somebody a review may be asked of. Carries the actor fields so the menu shows the same face and
266 * handle the rest of the page does, and a team wears them too — its slug stands in for a login.
267 */
268export const PullRequestReviewerCandidate = Schema.Struct({
269 ...PullRequestActor.fields,
270 /**
271 * How the host addresses this reviewer when a review is requested, which is not always the
272 * handle it shows: GitHub takes a login or a team slug, GitLab a numeric user id, Bitbucket an
273 * account uuid. Opaque to the page, which sends back whatever the candidate arrived with.
274 */
275 id: TrimmedNonEmptyString,
276 kind: PullRequestReviewerKind,
277 /** A review has already been asked of them, so pressing them takes the request back. */
278 isRequested: Schema.Boolean,
279});
280export type PullRequestReviewerCandidate = typeof PullRequestReviewerCandidate.Type;
281
282export const PullRequestReviewerCandidateList = Schema.Struct({
283 /** Never includes the author: nobody is asked to review their own change request. */
284 candidates: Schema.Array(PullRequestReviewerCandidate),
285 /**
286 * The host has more people with access than the read asked for, so somebody missing from the
287 * menu may still be somebody this change request can be sent to. Nothing is wrong with the
288 * list; it is simply not all of it.
289 */
290 truncated: Schema.Boolean,
291});
292export type PullRequestReviewerCandidateList = typeof PullRequestReviewerCandidateList.Type;
293
294/** A label the repository defines, with whether this change request already wears it. */
295export const PullRequestLabelCandidate = Schema.Struct({
296 ...PullRequestLabel.fields,
297 description: Schema.NullOr(Schema.String),
298 isApplied: Schema.Boolean,
299});
300export type PullRequestLabelCandidate = typeof PullRequestLabelCandidate.Type;
301
302export const PullRequestLabelCandidateList = Schema.Struct({
303 candidates: Schema.Array(PullRequestLabelCandidate),
304 /** The repository defines more labels than the read asked for; the list is not all of them. */
305 truncated: Schema.Boolean,
306});
307export type PullRequestLabelCandidateList = typeof PullRequestLabelCandidateList.Type;
308
309export const PullRequestCommit = Schema.Struct({
310 oid: TrimmedNonEmptyString,
311 messageHeadline: Schema.String,
312 committedDate: IsoDateTime,
313 /** Per-commit line counts where the host can return them without a request per commit. */
314 additions: Schema.optional(NonNegativeInt),
315 deletions: Schema.optional(NonNegativeInt),
316 /**
317 * Everyone the host attributes the commit to. Optional because older servers and hosts that
318 * do not expose commit authors still produce a useful timeline entry.
319 */
320 authors: Schema.optional(Schema.Array(PullRequestActor)),
321});
322export type PullRequestCommit = typeof PullRequestCommit.Type;
323
324/**
325 * What a host can do with a review, which is where the four differ most. GitLab has no way to
326 * say "changes requested", and Azure DevOps exposes no diff through its CLI, so it has no lines
327 * to write against at all.
328 */
329export const PullRequestReviewCapabilities = Schema.Struct({
330 /** A new comment can be anchored to a line of the diff. */
331 inlineComment: Schema.Boolean,
332 /** An existing thread can be replied to. */
333 reply: Schema.Boolean,
334 /** A thread can be marked resolved, and unresolved again. */
335 resolve: Schema.Boolean,
336 /** The verdicts a submitted review can carry. Empty means reviews cannot be submitted. */
337 verdicts: Schema.Array(PullRequestReviewVerdict),
338});
339export type PullRequestReviewCapabilities = typeof PullRequestReviewCapabilities.Type;
340
341/**
342 * What a host lets be rewritten after it has been posted. The two are separate because a host can
343 * take one without the other: Azure DevOps takes a new title and description through the same
344 * command that closes a pull request, and has no way to post a remark here at all — so nothing it
345 * shows in a conversation can be rewritten either.
346 */
347export const PullRequestEditCapabilities = Schema.Struct({
348 /** The change request's own title and description can be rewritten. */
349 changeRequest: Schema.Boolean,
350 /** A remark can be rewritten by whoever wrote it. */
351 comment: Schema.Boolean,
352});
353export type PullRequestEditCapabilities = typeof PullRequestEditCapabilities.Type;
354
355/**
356 * What a host can do about who reviews. The two are independent: a host can take a request without
357 * publishing who may receive one, which is Azure DevOps.
358 */
359export const PullRequestReviewerCapabilities = Schema.Struct({
360 /** A review can be asked of somebody, and the request taken back. */
361 request: Schema.Boolean,
362 /**
363 * The people who may be asked can be listed. False where the host has no such list to give,
364 * which leaves the page to take a name rather than offer a menu — a guessed list would be worse,
365 * because a name missing from it reads as a name that cannot be asked.
366 */
367 listCandidates: Schema.Boolean,
368});
369export type PullRequestReviewerCapabilities = typeof PullRequestReviewerCapabilities.Type;
370
371/**
372 * What a provider can actually do, so a surface can hide what is missing rather than offer an
373 * action that would fail. Every provider fills this in for itself; nothing is assumed.
374 *
375 * Hosts differ more than they look: Azure DevOps exposes no patch through its CLI, and
376 * Bitbucket has no endpoint that reopens a declined pull request. Both would otherwise be dead
377 * buttons.
378 */
379export const PullRequestCapabilities = Schema.Struct({
380 /** A unified patch can be fetched for the change request. */
381 diff: Schema.Boolean,
382 /** A comment can be posted, and the conversation read back. */
383 comment: Schema.Boolean,
384 /** The actions this host can carry out; anything absent is never offered. */
385 actions: Schema.Array(PullRequestAction),
386 /** Merge strategies the provider itself offers, before repository settings narrow them. */
387 mergeMethods: Schema.Array(PullRequestMergeMethod),
388 /**
389 * How this host can bring a stale branch up to date. Absent where it cannot at all, which is
390 * every host that has not said otherwise — so a provider that says nothing offers nothing.
391 */
392 updateMethods: Schema.optional(Schema.Array(PullRequestUpdateMethod)),
393 /**
394 * The host can narrow a listing by free text. False means it answers unnarrowed and whoever
395 * asked has to do the narrowing — which is a different promise, so the page is told rather
396 * than left to show every change request on that host as a search result.
397 */
398 search: Schema.Boolean,
399 /**
400 * Reactions can be read from a remark, and added to one or taken back. One flag for both:
401 * neither host here reports reactions it will not also take, and a surface that could show a
402 * pill it may never press is a surface offering nothing. Optional for the same reason as
403 * `updateMethods` and `edit`: a server that says nothing about reactions has none, which is
404 * what every server before this field was.
405 */
406 reactions: Schema.optional(Schema.Boolean),
407 review: PullRequestReviewCapabilities,
408 reviewers: PullRequestReviewerCapabilities,
409 /**
410 * What can be rewritten after the fact. Optional so a page and a server of different ages still
411 * speak to each other: a server that says nothing about rewriting is one that cannot, which is
412 * what every server before this one was.
413 */
414 edit: Schema.optional(PullRequestEditCapabilities),
415 /**
416 * The repository's labels can be listed, and one put on a change request or taken off it.
417 * Optional for the same reason `edit` is: a server that says nothing about labels has no way
418 * to change them, which is what every server before this field was.
419 */
420 labels: Schema.optional(Schema.Boolean),
421});
422export type PullRequestCapabilities = typeof PullRequestCapabilities.Type;
423
424/**
425 * What the signed-in account may do with this change request, which is a different question from
426 * `capabilities`: that says what the host is able to do at all, and this says whether this viewer
427 * is allowed to ask for it. A host that merges pull requests still will not let a stranger merge
428 * one, so a control belongs on the page only where the two agree.
429 *
430 * A permission the host reports nothing about is granted rather than withheld. Hiding a control
431 * from someone who may in fact use it leaves them no way through and no reason given, while
432 * offering one they may not use ends in the host's own refusal — which at least says why.
433 */
434export const PullRequestViewerPermissions = Schema.Struct({
435 /** Which of the actions this viewer may take; anything absent is theirs to look at only. */
436 actions: Schema.Array(PullRequestAction),
437 /** This viewer may write a remark: a comment, a reply, or a note against a line. */
438 comment: Schema.Boolean,
439 /** This viewer may mark a review conversation resolved, and unresolved again. */
440 resolve: Schema.Boolean,
441 /** The verdicts this viewer may submit a review with. Empty means they may not review. */
442 verdicts: Schema.Array(PullRequestReviewVerdict),
443 /** This viewer may ask somebody for a review, and take the request back again. */
444 requestReviewers: Schema.Boolean,
445 /**
446 * The ways this viewer may bring the branch up to date, narrowed from what the host offers.
447 * Absent or empty means they may not, which is also what a host with no such action says.
448 */
449 updateMethods: Schema.optional(Schema.Array(PullRequestUpdateMethod)),
450 /**
451 * This viewer may put a label on the change request, and take one off. Absent is granted, like
452 * every permission here; the capability beside it is what decides whether a label can be
453 * changed on this host at all.
454 */
455 labels: Schema.optional(Schema.Boolean),
456});
457export type PullRequestViewerPermissions = typeof PullRequestViewerPermissions.Type;
458
459export const PullRequestMergeCapabilities = Schema.Struct({
460 merge: Schema.Boolean,
461 squash: Schema.Boolean,
462 rebase: Schema.Boolean,
463});
464export type PullRequestMergeCapabilities = typeof PullRequestMergeCapabilities.Type;
465
466export const PullRequestListEntry = Schema.Struct({
467 provider: SourceControlProviderKind,
468 /**
469 * The host below which `repository` is addressed, so the same provider kind can serve more
470 * than one account — github.com and a GitHub Enterprise install are different identities.
471 */
472 host: TrimmedNonEmptyString,
473 projectId: ProjectId,
474 projectTitle: TrimmedNonEmptyString,
475 repository: TrimmedNonEmptyString,
476 number: PositiveInt,
477 title: TrimmedNonEmptyString,
478 url: TrimmedNonEmptyString,
479 author: Schema.NullOr(PullRequestActor),
480 headBranch: TrimmedNonEmptyString,
481 baseBranch: TrimmedNonEmptyString,
482 state: PullRequestState,
483 isDraft: Schema.Boolean,
484 mergeability: PullRequestMergeability,
485 /**
486 * Zero where the host has not been asked for the counts yet, which on GitHub is every row a
487 * listing hands over: they are read afterwards, through `PullRequestListStatsInput`. Zero is
488 * what a host that reports no counts at all has always sent, and what the page already draws
489 * as no stat rather than as an empty change.
490 */
491 additions: NonNegativeInt,
492 deletions: NonNegativeInt,
493 createdAt: IsoDateTime,
494 updatedAt: IsoDateTime,
495 viewerReviewRequested: Schema.Boolean,
496 labels: Schema.Array(PullRequestLabel),
497 /** Absent where the host does not summarise its reviews, which is every host but GitHub. */
498 reviewDecision: Schema.optional(PullRequestReviewDecision),
499 /** Absent where the host reports no check rollup, or the change request has no checks. */
500 checksState: Schema.optional(PullRequestChecksState),
501});
502export type PullRequestListEntry = typeof PullRequestListEntry.Type;
503
504/**
505 * Where each repository a listing already reached carries on from, keyed `"<host> <repository>"`
506 * — which is how a listing tells two repositories apart, since the same `owner/repo` exists on
507 * github.com and on an Enterprise install at once.
508 *
509 * Each value is opaque: only the provider that issued one knows what it means, and the page hands
510 * back exactly what it was given rather than composing one.
511 */
512export const PullRequestListCursors = Schema.Record(
513 TrimmedNonEmptyString,
514 // Bounded because it arrives from the page and is unfolded into a host's own filter.
515 TrimmedNonEmptyString.check(Schema.isMaxLength(4096)),
516);
517export type PullRequestListCursors = typeof PullRequestListCursors.Type;
518
519export const PullRequestListInput = Schema.Struct({
520 state: PullRequestListState,
521 involvement: Schema.optional(PullRequestInvolvement),
522 filters: Schema.optional(PullRequestListFilters),
523 projectId: Schema.optional(ProjectId),
524 /**
525 * Only these projects, for a client that assigns each shared repository to one of its
526 * connections and asks the others to stay quiet about it. Absent means every project, which
527 * is what every listing asked for before there were several connections to spread across.
528 */
529 projectIds: Schema.optional(Schema.Array(ProjectId).check(Schema.isMaxLength(100))),
530 /**
531 * Narrows the listing to one host, named as the host itself rather than as its provider kind:
532 * github.com and a GitHub Enterprise install are two accounts, and a kind cannot tell them
533 * apart. Absent means every host the workspace has.
534 */
535 host: Schema.optional(TrimmedNonEmptyString),
536 /** Rows to return per repository, which with a continuation is rows per slice. */
537 limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 500 }))),
538 /**
539 * Carry on from an answer already on the page rather than read the listing again. Only the
540 * repositories named here are read, one slice each — which is what makes a further page cost
541 * one slice rather than every repository over again at a larger size. A repository the page has
542 * enough of is simply left out.
543 *
544 * Absent asks for the listing from the top, which is what raising `limit` alone has always
545 * done and still does.
546 */
547 cursors: Schema.optional(PullRequestListCursors),
548 /**
549 * Free text the hosts themselves are asked to match, rather than a filter over the rows that
550 * have already arrived: a listing only ever holds a page per repository, so a search that
551 * never leaves the client can only find what happened to be loaded. What a match means is the
552 * host's own business — GitHub reads a body, GitLab a description — and a host with no text
553 * filter answers unnarrowed rather than pretending.
554 *
555 * Bounded because it travels into a CLI argument and a query string, and no host makes
556 * anything of a search term this long.
557 */
558 query: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(200))),
559});
560export type PullRequestListInput = typeof PullRequestListInput.Type;
561
562/**
563 * A host the workspace has projects on, and whether it can be read right now. Drives the host
564 * switcher and explains projects the list leaves out.
565 *
566 * One per host rather than per provider kind, because signing in is a question about the host:
567 * a workspace can hold repositories on github.com and on a GitHub Enterprise install at once,
568 * and the two are separate accounts that succeed and fail independently.
569 */
570export const PullRequestProviderSummary = Schema.Struct({
571 host: TrimmedNonEmptyString,
572 kind: SourceControlProviderKind,
573 /** False where a search has to be applied to the rows after they arrive. */
574 searchesOnHost: Schema.Boolean,
575 projectCount: PositiveInt,
576 /** False when the provider's CLI or credentials are missing, with `detail` saying which. */
577 configured: Schema.Boolean,
578 detail: Schema.NullOr(TrimmedNonEmptyString),
579});
580export type PullRequestProviderSummary = typeof PullRequestProviderSummary.Type;
581
582/** One project whose repository could not be read; healthy projects still return entries. */
583export const PullRequestListProjectError = Schema.Struct({
584 projectId: ProjectId,
585 projectTitle: TrimmedNonEmptyString,
586 message: TrimmedNonEmptyString,
587});
588export type PullRequestListProjectError = typeof PullRequestListProjectError.Type;
589
590export const PullRequestListResult = Schema.Struct({
591 /**
592 * The signed-in account per host, which is what involvement filtering compares. Keyed by
593 * host rather than by provider kind: two GitHub hosts are two accounts. A host that could
594 * not be read is absent rather than present-and-undefined, because an open-keyed record
595 * cannot carry an optional value through the JSON codec.
596 */
597 viewers: Schema.Record(TrimmedNonEmptyString, TrimmedNonEmptyString),
598 providers: Schema.Array(PullRequestProviderSummary),
599 /**
600 * By update, newest first, across every repository this answer covers. A page that appends a
601 * continuation sorts what it then holds the same way: a repository's next slice is older than
602 * that repository's last row, but can still be newer than another repository's.
603 */
604 entries: Schema.Array(PullRequestListEntry),
605 errors: Schema.Array(PullRequestListProjectError),
606 /** At least one repository hit the per-repository listing cap. */
607 truncated: Schema.Boolean,
608 /**
609 * Where each repository carries on, to be sent straight back as `cursors`. A repository is
610 * absent from this once it has nothing more to give, and also where its host could not be asked
611 * in an order a continuation means anything in — so an empty record beside `truncated` means
612 * more rows are only reachable by raising `limit`, the way they always were.
613 */
614 nextCursors: PullRequestListCursors,
615});
616export type PullRequestListResult = typeof PullRequestListResult.Type;
617
618export const PullRequestRef = Schema.Struct({
619 projectId: ProjectId,
620 repository: TrimmedNonEmptyString,
621 number: PositiveInt,
622});
623export type PullRequestRef = typeof PullRequestRef.Type;
624
625/**
626 * The small live shape a linked thread needs. Keeping it separate from detail means a sidebar
627 * status check never loads permissions, repository settings, checks, or base comparison data.
628 */
629export const PullRequestSummary = Schema.Struct({
630 provider: SourceControlProviderKind,
631 projectId: ProjectId,
632 repository: TrimmedNonEmptyString,
633 number: PositiveInt,
634 title: TrimmedNonEmptyString,
635 url: TrimmedNonEmptyString,
636 state: PullRequestState,
637 /** Present when the host says the open pull request is still a draft. */
638 isDraft: Schema.optional(Schema.Boolean),
639 headBranch: TrimmedNonEmptyString,
640 baseBranch: TrimmedNonEmptyString,
641 closedAt: Schema.optional(Schema.NullOr(Schema.String)),
642 mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
643 updatedAt: IsoDateTime,
644});
645export type PullRequestSummary = typeof PullRequestSummary.Type;
646
647/**
648 * One row's line counts, read after the listing rather than inside it. On GitHub the pair is
649 * 40-60% of the wall clock of the search that answers the whole page — measured over twelve
650 * repositories, 7.1s with it and 4.0s without — for two small numbers at the end of a row.
651 *
652 * So the listing answers without them and the page asks for them next, which is what puts the
653 * rows on screen at the speed of everything else on them.
654 */
655export const PullRequestDiffStat = Schema.Struct({
656 projectId: ProjectId,
657 repository: TrimmedNonEmptyString,
658 number: PositiveInt,
659 additions: NonNegativeInt,
660 deletions: NonNegativeInt,
661});
662export type PullRequestDiffStat = typeof PullRequestDiffStat.Type;
663
664/**
665 * The rows whose line counts are wanted, which is the rows the page is showing.
666 *
667 * Bounded at the largest listing a page can hold, since each ref becomes a lookup of its own on
668 * the host.
669 */
670export const PullRequestListStatsInput = Schema.Struct({
671 refs: Schema.Array(PullRequestRef).check(Schema.isMaxLength(500)),
672});
673export type PullRequestListStatsInput = typeof PullRequestListStatsInput.Type;
674
675/**
676 * Only the rows that could be answered for. A host with no batched stat read of its own — every
677 * one but GitHub, which all report the counts in the listing itself — is simply absent here, and
678 * the numbers its listing already carried stand.
679 */
680export const PullRequestListStatsResult = Schema.Struct({
681 stats: Schema.Array(PullRequestDiffStat),
682});
683export type PullRequestListStatsResult = typeof PullRequestListStatsResult.Type;
684
685/**
686 * Forget what the server has cached, so the next read asks the host. With a reference it
687 * forgets that one change request's detail and diff; without one it forgets the listings.
688 * A separate request rather than a flag on the reads, so an explicit "refresh" one person
689 * presses is the only thing that spends host requests — every ordinary read shares.
690 */
691export const PullRequestInvalidateInput = Schema.Struct({
692 reference: Schema.optional(PullRequestRef),
693});
694export type PullRequestInvalidateInput = typeof PullRequestInvalidateInput.Type;
695
696export const PullRequestDetail = Schema.Struct({
697 provider: SourceControlProviderKind,
698 capabilities: PullRequestCapabilities,
699 /** What this viewer may do, which `capabilities` says nothing about. Both narrow the page. */
700 viewerPermissions: PullRequestViewerPermissions,
701 projectId: ProjectId,
702 projectTitle: TrimmedNonEmptyString,
703 workspaceRoot: TrimmedNonEmptyString,
704 repository: TrimmedNonEmptyString,
705 number: PositiveInt,
706 title: TrimmedNonEmptyString,
707 body: Schema.String,
708 url: TrimmedNonEmptyString,
709 author: Schema.NullOr(PullRequestActor),
710 state: PullRequestState,
711 isDraft: Schema.Boolean,
712 mergeability: PullRequestMergeability,
713 additions: NonNegativeInt,
714 deletions: NonNegativeInt,
715 changedFiles: NonNegativeInt,
716 headBranch: TrimmedNonEmptyString,
717 headRepositoryNameWithOwner: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
718 baseBranch: TrimmedNonEmptyString,
719 createdAt: IsoDateTime,
720 updatedAt: IsoDateTime,
721 mergedAt: Schema.NullOr(IsoDateTime),
722 closedAt: Schema.NullOr(IsoDateTime),
723 reviewers: Schema.Array(PullRequestActor),
724 labels: Schema.Array(PullRequestLabel),
725 checks: Schema.Array(PullRequestCheck),
726 mergeCapabilities: PullRequestMergeCapabilities,
727 /**
728 * Who the host says the reader is, which is the one thing a conversation cannot be read without
729 * to tell the reader's own remarks from everybody else's — and rewriting a remark is offered
730 * only where the two names agree. Absent where the host could not say, which offers nothing
731 * rather than everything.
732 */
733 viewer: Schema.optional(TrimmedNonEmptyString),
734 /**
735 * Where the branch stands against its base. Optional so a host that cannot compare says
736 * nothing rather than claiming the branch is current — the page shows a banner only where the
737 * answer is "behind", and silence is not that answer.
738 */
739 baseComparison: Schema.optional(PullRequestBaseComparison),
740 /** How many commits the base is ahead by, where the host counted them. */
741 behindBy: Schema.optional(NonNegativeInt),
742 /**
743 * Whether the host is already armed to merge this on its own. Absent where the host does not
744 * report it, which is not the same as off: a page that reads silence as "not armed" offers to
745 * arm something that is already armed, and a second arming is a write nobody asked for.
746 */
747 autoMergeEnabled: Schema.optional(Schema.Boolean),
748 /** The strategy the host will use for an armed auto-merge, where it reports one. */
749 autoMergeMethod: Schema.optional(PullRequestMergeMethod),
750 /** GitHub Actions runs on this head commit that are waiting for a maintainer's approval. */
751 workflowApprovalsRequired: Schema.optional(NonNegativeInt),
752});
753export type PullRequestDetail = typeof PullRequestDetail.Type;
754
755/**
756 * The slower, conversation-shaped half of a change request. It is read independently from the
757 * core detail so a host with a deeply paginated review history cannot hold the title, body,
758 * checks, and actions off screen. `author` and `reviewers` are optional enrichments: GitHub's
759 * conversation query carries avatars and completed reviewers that its basic detail does not.
760 */
761export const PullRequestActivity = Schema.Struct({
762 author: Schema.optional(Schema.NullOr(PullRequestActor)),
763 reviewers: Schema.optional(Schema.Array(PullRequestActor)),
764 comments: Schema.Array(PullRequestComment),
765 /**
766 * How many remarks the host itself counts in the conversation, which is the number a surface
767 * showing a count has to show: `comments` carries what was read, and a reader who can see 225
768 * on the host is not reassured by a page that says 10. Never less than `comments` holds, and
769 * equal to it wherever the host was read to the end.
770 */
771 commentCount: NonNegativeInt,
772 /**
773 * The read stopped at a bound of its own before the host ran out, so `comments` holds less
774 * than `commentCount` counts. Nothing else: a conversation read whole is never truncated,
775 * however long it is.
776 */
777 commentsTruncated: Schema.Boolean,
778 reviewThreads: Schema.Array(PullRequestReviewThread),
779 commits: Schema.Array(PullRequestCommit),
780 /**
781 * The change request's own reactions — the ones on its description, which every host counts
782 * against the change request itself rather than against a remark in the conversation.
783 */
784 reactions: Schema.optional(Schema.Array(PullRequestReaction)),
785});
786export type PullRequestActivity = typeof PullRequestActivity.Type;
787
788/** The complete detail shape after the independently loaded activity has been applied. */
789export const PullRequestDetailView = Schema.Struct({
790 ...PullRequestDetail.fields,
791 ...PullRequestActivity.fields,
792 // A composed view always has the core identity fields, even when the activity did not enrich
793 // them. Re-declare them as required after the activity's optional overrides.
794 author: Schema.NullOr(PullRequestActor),
795 reviewers: Schema.Array(PullRequestActor),
796});
797export type PullRequestDetailView = typeof PullRequestDetailView.Type;
798
799/**
800 * A diff arrives a slice at a time, because a large change is more than any host will hand over
801 * at once — GitHub refuses outright past 300 files — and more than a viewer can lay out in one
802 * go. A slice is a whole number of files, never a file cut in half, so each one parses on its
803 * own and the reader can start on the first while the rest is still coming.
804 */
805export const PullRequestDiffInput = Schema.Struct({
806 ...PullRequestRef.fields,
807 /**
808 * Where to carry on from. Absent asks for the first slice. Opaque to the reader: each host
809 * counts its files its own way, and only the provider that issued one knows what it means.
810 */
811 cursor: Schema.optional(TrimmedNonEmptyString),
812 /**
813 * One commit of the change rather than the whole of it. A large pull request is easier to
814 * read a commit at a time, and the author's own commits are the boundaries they chose.
815 */
816 commit: Schema.optional(TrimmedNonEmptyString),
817});
818export type PullRequestDiffInput = typeof PullRequestDiffInput.Type;
819
820/** Real line counts for a file whose hunks the host withheld from the patch. */
821export const PullRequestOmittedFileStat = Schema.Struct({
822 path: TrimmedNonEmptyString,
823 additions: Schema.Number,
824 deletions: Schema.Number,
825});
826export type PullRequestOmittedFileStat = typeof PullRequestOmittedFileStat.Type;
827
828export const PullRequestDiffResult = Schema.Struct({
829 patch: Schema.String,
830 /**
831 * Something inside this slice could not be shown — a binary file, or a hunk the host declined
832 * to inline. Not the same as there being more slices, which `nextCursor` answers.
833 */
834 truncated: Schema.Boolean,
835 /** Where the next slice starts, or null once the diff is whole. */
836 nextCursor: Schema.NullOr(TrimmedNonEmptyString),
837 /**
838 * The host's own counts for the files whose hunks it withheld, so a file the patch cannot
839 * show still reports what changed instead of a zero the diff never had.
840 */
841 omittedFileStats: Schema.optional(Schema.Array(PullRequestOmittedFileStat)),
842});
843export type PullRequestDiffResult = typeof PullRequestDiffResult.Type;
844
845/** The complete old and new files Pierre needs to open omitted context in a host-backed patch. */
846export const PullRequestDiffFileContentsInput = Schema.Struct({
847 ...PullRequestRef.fields,
848 /** One commit's own comparison; absent means the whole change request. */
849 commit: Schema.optional(TrimmedNonEmptyString),
850 changeType: Schema.Literals(["change", "rename-pure", "rename-changed", "new", "deleted"]),
851 oldPath: TrimmedNonEmptyString,
852 newPath: TrimmedNonEmptyString,
853});
854export type PullRequestDiffFileContentsInput = typeof PullRequestDiffFileContentsInput.Type;
855
856export const PullRequestDiffFileContentsResult = Schema.Struct({
857 oldContents: Schema.String,
858 newContents: Schema.String,
859});
860export type PullRequestDiffFileContentsResult = typeof PullRequestDiffFileContentsResult.Type;
861
862export const PullRequestActionInput = Schema.Struct({
863 ...PullRequestRef.fields,
864 action: PullRequestAction,
865 /**
866 * Which strategy the merge uses, read for `merge` and for `enable-auto-merge` alike — a merge
867 * the host performs later is still a merge, and the strategy is chosen when it is armed rather
868 * than at the moment it happens. Absent means the host's own default.
869 */
870 mergeMethod: Schema.optional(PullRequestMergeMethod),
871 /** Only read for `update-branch`, where absent means the host's own default. */
872 updateMethod: Schema.optional(PullRequestUpdateMethod),
873});
874export type PullRequestActionInput = typeof PullRequestActionInput.Type;
875
876// Not trimmed: the body is markdown, where leading spaces open a code block and two trailing
877// spaces are a line break. GitHub rejects bodies past 65536 characters, so that bound is
878// enforced here to keep oversized payloads off the wire and out of subprocess plumbing; the
879// service rejects a body that is only whitespace.
880const CommentBody = Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536));
881
882export const PullRequestCommentInput = Schema.Struct({
883 ...PullRequestRef.fields,
884 body: CommentBody,
885});
886export type PullRequestCommentInput = typeof PullRequestCommentInput.Type;
887
888/**
889 * A change request's own words rewritten: its title, its description, or both. Each is optional
890 * because the page rewrites them apart — a title corrected on its own must not carry a description
891 * nobody opened — and the service refuses a request that carries neither.
892 *
893 * The title is bounded far past what any host takes, GitHub refusing one past 256 characters, so
894 * an oversized one is turned away before it reaches a subprocess. The body is not trimmed for the
895 * same reason a comment is not: it is markdown, where leading spaces open a code block. An empty
896 * one is allowed, which is how a description is cleared.
897 */
898export const PullRequestUpdateInput = Schema.Struct({
899 ...PullRequestRef.fields,
900 title: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(1024))),
901 body: Schema.optional(Schema.String.check(Schema.isMaxLength(65_536))),
902});
903export type PullRequestUpdateInput = typeof PullRequestUpdateInput.Type;
904
905/**
906 * A remark already posted, rewritten by whoever wrote it. The kind travels beside the id because
907 * an id alone does not say which endpoint addresses it: GitHub rewrites a comment on the
908 * conversation and a comment on a line through two different mutations.
909 *
910 * A review's own summary is not among them. The hosts disagree about what one even is — the entry
911 * Bitbucket shows is a vote this page renders as a remark, with no words behind it to rewrite —
912 * and a control that worked on one host and failed on another is worse than one that is not there.
913 */
914export const PullRequestCommentUpdateInput = Schema.Struct({
915 ...PullRequestRef.fields,
916 commentId: TrimmedNonEmptyString,
917 kind: Schema.Literals(["issue-comment", "review-comment"]),
918 body: CommentBody,
919});
920export type PullRequestCommentUpdateInput = typeof PullRequestCommentUpdateInput.Type;
921
922/** The coordinates of one line in a pull request diff. */
923export const PullRequestReviewPosition = Schema.Union([
924 Schema.Struct({
925 kind: Schema.Literal("added"),
926 newLine: PositiveInt,
927 }),
928 Schema.Struct({
929 kind: Schema.Literal("deleted"),
930 oldLine: PositiveInt,
931 }),
932 Schema.Struct({
933 kind: Schema.Literal("context"),
934 oldLine: PositiveInt,
935 newLine: PositiveInt,
936 /** Which copy of an unchanged line the reviewer selected in a split diff. */
937 side: PullRequestDiffSide,
938 }),
939]);
940export type PullRequestReviewPosition = typeof PullRequestReviewPosition.Type;
941
942/** One remark in a review that has not been sent yet, anchored to a line of the diff. */
943export const PullRequestReviewCommentDraft = Schema.Struct({
944 path: TrimmedNonEmptyString,
945 /**
946 * What the file was called before the change, sent only when it differs. GitLab resolves a
947 * position against both sides of the diff, so a comment on a renamed file needs both names;
948 * the hosts that address a comment by one path ignore this.
949 */
950 oldPath: Schema.optional(TrimmedNonEmptyString),
951 position: PullRequestReviewPosition,
952 body: CommentBody,
953});
954export type PullRequestReviewCommentDraft = typeof PullRequestReviewCommentDraft.Type;
955
956/**
957 * A whole review, sent in one go. The line comments travel with the verdict rather than being
958 * posted as they are written, so a half-finished review is never visible to anyone else — and
959 * so hosts with no notion of a pending review behave the same as the ones that have it.
960 */
961export const PullRequestSubmitReviewInput = Schema.Struct({
962 ...PullRequestRef.fields,
963 verdict: PullRequestReviewVerdict,
964 /** The review's own words. May be empty, which is how an approval with no remarks is sent. */
965 body: Schema.String.check(Schema.isMaxLength(65_536)),
966 comments: Schema.Array(PullRequestReviewCommentDraft),
967});
968export type PullRequestSubmitReviewInput = typeof PullRequestSubmitReviewInput.Type;
969
970export const PullRequestThreadCommentsInput = Schema.Struct({
971 ...PullRequestRef.fields,
972 threadId: TrimmedNonEmptyString,
973 cursor: TrimmedNonEmptyString,
974});
975export type PullRequestThreadCommentsInput = typeof PullRequestThreadCommentsInput.Type;
976
977export const PullRequestThreadCommentsResult = Schema.Struct({
978 comments: Schema.Array(PullRequestThreadComment),
979 nextCursor: Schema.NullOr(TrimmedNonEmptyString),
980});
981export type PullRequestThreadCommentsResult = typeof PullRequestThreadCommentsResult.Type;
982
983export const PullRequestThreadReplyInput = Schema.Struct({
984 ...PullRequestRef.fields,
985 threadId: TrimmedNonEmptyString,
986 body: CommentBody,
987});
988export type PullRequestThreadReplyInput = typeof PullRequestThreadReplyInput.Type;
989
990export const PullRequestThreadResolutionInput = Schema.Struct({
991 ...PullRequestRef.fields,
992 threadId: TrimmedNonEmptyString,
993 resolved: Schema.Boolean,
994});
995export type PullRequestThreadResolutionInput = typeof PullRequestThreadResolutionInput.Type;
996
997/**
998 * Reacting and taking the reaction back are one operation with `reacted` turned around, which is
999 * what pressing the same pill twice is.
1000 */
1001export const PullRequestReactionInput = Schema.Struct({
1002 ...PullRequestRef.fields,
1003 /**
1004 * Which remark to react to, as it arrived in the conversation. Absent reacts to the change
1005 * request itself, which is where its description's reactions live — the id a host uses for
1006 * that is its own to work out.
1007 */
1008 subjectId: Schema.optional(TrimmedNonEmptyString),
1009 content: PullRequestReactionContent,
1010 reacted: Schema.Boolean,
1011});
1012export type PullRequestReactionInput = typeof PullRequestReactionInput.Type;
1013
1014/**
1015 * Asking for a review and taking the request back are one operation with `requested` turned
1016 * around, and asking again somebody who has already reviewed is what a re-request is — so that is
1017 * the same operation once more rather than a third one.
1018 */
1019export const PullRequestReviewerRequestInput = Schema.Struct({
1020 ...PullRequestRef.fields,
1021 /**
1022 * Who, as the candidate list named them. Bounded because every host bounds it as well — GitHub
1023 * refuses past fifteen — and because these travel into a request body a page composed.
1024 */
1025 reviewers: Schema.Array(
1026 Schema.Struct({ id: TrimmedNonEmptyString, kind: PullRequestReviewerKind }),
1027 ).check(Schema.isMinLength(1), Schema.isMaxLength(25)),
1028 requested: Schema.Boolean,
1029});
1030export type PullRequestReviewerRequestInput = typeof PullRequestReviewerRequestInput.Type;
1031
1032/**
1033 * Putting a label on and taking it off are one operation with `applied` turned around, which is
1034 * what pressing the same row in the menu twice is. Named by the label's own name, which is how
1035 * GitHub addresses one.
1036 */
1037export const PullRequestLabelChangeInput = Schema.Struct({
1038 ...PullRequestRef.fields,
1039 labels: Schema.Array(TrimmedNonEmptyString).check(Schema.isMinLength(1), Schema.isMaxLength(25)),
1040 applied: Schema.Boolean,
1041});
1042export type PullRequestLabelChangeInput = typeof PullRequestLabelChangeInput.Type;
1043
1044export const PullRequestUnavailableReason = Schema.Literals([
1045 "cli-missing",
1046 "cli-unauthenticated",
1047 "provider-unsupported",
1048]);
1049export type PullRequestUnavailableReason = typeof PullRequestUnavailableReason.Type;
1050
1051/**
1052 * What each host needs before it can be read, so a failure names the fix rather than the
1053 * symptom. Bitbucket is credentials on the server rather than a signed-in CLI, which is why
1054 * these are whole sentences instead of a tool name to interpolate.
1055 */
1056const PROVIDER_REQUIREMENT: Partial<
1057 Record<SourceControlProviderKind, { readonly missing: string; readonly unauthenticated: string }>
1058> = {
1059 github: {
1060 missing:
1061 "GitHub CLI (`gh`) is required to browse change requests on this host. Install it from https://cli.github.com/ and reload.",
1062 unauthenticated: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
1063 },
1064 gitlab: {
1065 missing:
1066 "GitLab CLI (`glab`) is required to browse change requests on this host. Install it from https://gitlab.com/gitlab-org/cli and reload.",
1067 unauthenticated: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
1068 },
1069 "azure-devops": {
1070 missing:
1071 "Azure CLI (`az`) with the Azure DevOps extension is required. Install `az`, then run `az extension add --name azure-devops`.",
1072 unauthenticated: "Azure CLI is not signed in. Run `az login` and retry.",
1073 },
1074 bitbucket: {
1075 missing:
1076 "Bitbucket needs API credentials on the server. Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.",
1077 unauthenticated:
1078 "Bitbucket rejected the configured credentials. Check T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN.",
1079 },
1080};
1081
1082/**
1083 * The host a project's repository is addressed below. `canonicalKey` is the normalized remote,
1084 * `host/owner/repo`, so its first segment is the host; the provider kind stands in when there is
1085 * no key to read, which keeps one bucket per kind for identities recorded before it existed.
1086 *
1087 * Shared between the server and the page so both bucket a workspace the same way — the page
1088 * knows its hosts before the listing answers, and the two must agree on what they are called.
1089 */
1090export function pullRequestHostOf(
1091 identity: { readonly canonicalKey?: string | undefined } | null | undefined,
1092 kind: SourceControlProviderKind,
1093): string {
1094 const host = identity?.canonicalKey?.split("/")[0]?.trim();
1095 return host === undefined || host.length === 0 ? kind : host.toLowerCase();
1096}
1097
1098/**
1099 * `author:me` names whoever is signed in to the host being read, GitHub's `@me` spelled either
1100 * way. A host's own search would answer it, but the page and the server both re-check an author
1101 * against the row's login, so the name is resolved before either comparison rather than being
1102 * matched as the literal login "me".
1103 *
1104 * Null viewer where the host has not said who the reader is; the filter then stands as typed,
1105 * which is the same answer a search for a user named "me" would give.
1106 *
1107 * Shared between the server and the page so both narrow by the same login.
1108 */
1109export function resolvePullRequestAuthorFilter(
1110 author: string,
1111 viewer: string | null | undefined,
1112): string {
1113 const trimmed = author.trim();
1114 if (!/^@?me$/i.test(trimmed)) return trimmed;
1115 return viewer === null || viewer === undefined || viewer.trim().length === 0 ? trimmed : viewer;
1116}
1117
1118/**
1119 * What a host needs before it can be read, as a sentence to show wherever that host is reported
1120 * as unusable — the whole page when nothing can be read, and one entry in the host switcher when
1121 * only that host cannot. Null when the reason is not about setting a host up.
1122 */
1123export function pullRequestProviderRequirement(
1124 provider: SourceControlProviderKind,
1125 reason: PullRequestUnavailableReason,
1126): string | null {
1127 const requirement = PROVIDER_REQUIREMENT[provider];
1128 if (requirement === undefined) return null;
1129 switch (reason) {
1130 case "cli-missing":
1131 return requirement.missing;
1132 case "cli-unauthenticated":
1133 return requirement.unauthenticated;
1134 case "provider-unsupported":
1135 return null;
1136 }
1137}
1138
1139/**
1140 * The feature is switched off entirely. The message is derived from `reason` and the host
1141 * rather than from whatever the CLI printed, so it stays a stable sentence the UI can show
1142 * as-is; the underlying failure travels in `cause` (absent for `provider-unsupported`, which
1143 * has none).
1144 */
1145export class PullRequestUnavailableError extends Schema.TaggedError<PullRequestUnavailableError>()(
1146 "PullRequestUnavailableError",
1147 {
1148 reason: PullRequestUnavailableReason,
1149 provider: Schema.optional(SourceControlProviderKind),
1150 cause: Schema.optional(Schema.Defect()),
1151 },
1152 { httpApiStatus: 503 },
1153) {
1154 [HttpServerRespondable.symbol]() {
1155 return HttpServerResponse.schemaJson(PullRequestUnavailableError)(this, { status: 503 });
1156 }
1157
1158 override get message(): string {
1159 const requirement =
1160 this.provider === undefined ? undefined : PROVIDER_REQUIREMENT[this.provider];
1161 switch (this.reason) {
1162 case "cli-missing":
1163 return (
1164 requirement?.missing ?? "The tool this host is read through is not installed or set up."
1165 );
1166 case "cli-unauthenticated":
1167 return requirement?.unauthenticated ?? "This host has no working credentials.";
1168 case "provider-unsupported":
1169 return "Change requests cannot be browsed for this project's host yet.";
1170 }
1171 }
1172}
1173
1174export class PullRequestOperationError extends Schema.TaggedError<PullRequestOperationError>()(
1175 "PullRequestOperationError",
1176 {
1177 operation: Schema.String,
1178 detail: TrimmedNonEmptyString,
1179 cause: Schema.optional(Schema.Defect()),
1180 },
1181 { httpApiStatus: 502 },
1182) {
1183 [HttpServerRespondable.symbol]() {
1184 return HttpServerResponse.schemaJson(PullRequestOperationError)(this, { status: 502 });
1185 }
1186
1187 override get message(): string {
1188 return `Pull request operation ${this.operation} failed: ${this.detail}`;
1189 }
1190}