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