@catamorphic/github 0.0.0-stage → 0.1.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/api.ts ADDED
@@ -0,0 +1,1580 @@
1
+ import {
2
+ type FetchLike,
3
+ type GithubActor,
4
+ GithubApiError,
5
+ type GithubCheckRun,
6
+ type GithubCheckRunFields,
7
+ type GithubComment,
8
+ GithubGraphqlError,
9
+ type GithubPullRequest,
10
+ type GithubPullRequestFile,
11
+ type GithubPullRequestReview,
12
+ type GithubPullRequestStatus,
13
+ type GithubRepo,
14
+ type GithubRepositoryEvent,
15
+ type GithubReviewComment,
16
+ type GithubReviewEvent,
17
+ type GithubReviewThread,
18
+ type GithubReviewThreadComment,
19
+ type GithubUser,
20
+ } from "./types.js";
21
+
22
+ const API_BASE = "https://api.github.com";
23
+
24
+ export interface GithubApiOptions {
25
+ fetch?: FetchLike;
26
+ baseUrl?: string;
27
+ signal?: AbortSignal;
28
+ }
29
+
30
+ interface RawRepo {
31
+ id: number;
32
+ full_name: string;
33
+ name: string;
34
+ owner: { login: string };
35
+ private: boolean;
36
+ default_branch: string;
37
+ clone_url: string;
38
+ description: string | null;
39
+ pushed_at: string | null;
40
+ }
41
+
42
+ interface RawPullRequest {
43
+ number: number;
44
+ title: string;
45
+ html_url: string;
46
+ user: { login: string } | null;
47
+ head: { ref: string; sha?: string };
48
+ body?: string | null;
49
+ requested_reviewers?: Array<{ login: string }>;
50
+ base: { ref: string };
51
+ draft: boolean;
52
+ updated_at: string;
53
+ }
54
+
55
+ /** The fields of a single pull request that its list entries lack. */
56
+ interface RawPullRequestDetail extends RawPullRequest {
57
+ state: "open" | "closed";
58
+ merged?: boolean;
59
+ merged_at?: string | null;
60
+ additions?: number;
61
+ deletions?: number;
62
+ changed_files?: number;
63
+ comments?: number;
64
+ review_comments?: number;
65
+ }
66
+
67
+ interface RawCommitStatus {
68
+ state: string;
69
+ statuses: Array<{ state: string }>;
70
+ }
71
+
72
+ const FAILED_CONCLUSIONS = new Set([
73
+ "failure",
74
+ "timed_out",
75
+ "cancelled",
76
+ "action_required",
77
+ "startup_failure",
78
+ "stale",
79
+ ]);
80
+
81
+ interface RawWatchPull {
82
+ id: number;
83
+ number: number;
84
+ updated_at: string;
85
+ user: { login: string } | null;
86
+ head: { sha: string };
87
+ [key: string]: unknown;
88
+ }
89
+
90
+ interface RawPullReview {
91
+ id: number;
92
+ state: string;
93
+ submitted_at: string;
94
+ user: { login: string } | null;
95
+ [key: string]: unknown;
96
+ }
97
+
98
+ interface RawWorkflowRun {
99
+ id: number;
100
+ run_attempt: number;
101
+ status: string;
102
+ conclusion: string | null;
103
+ updated_at: string;
104
+ actor: { login: string } | null;
105
+ [key: string]: unknown;
106
+ }
107
+
108
+ interface RawCheckRun {
109
+ id: number;
110
+ status: string;
111
+ conclusion: string | null;
112
+ updated_at: string;
113
+ app: { slug: string } | null;
114
+ [key: string]: unknown;
115
+ }
116
+
117
+ interface RawCheckSuite {
118
+ id: number;
119
+ status: string;
120
+ conclusion: string | null;
121
+ updated_at: string;
122
+ app: { slug: string } | null;
123
+ [key: string]: unknown;
124
+ }
125
+
126
+ interface RawDiscussionComment {
127
+ id: number;
128
+ body: string;
129
+ user: { login: string } | null;
130
+ created_at?: string;
131
+ submitted_at?: string;
132
+ html_url: string;
133
+ state?: string;
134
+ path?: string;
135
+ line?: number | null;
136
+ in_reply_to_id?: number;
137
+ diff_hunk?: string;
138
+ side?: "LEFT" | "RIGHT";
139
+ }
140
+
141
+ interface RawUser {
142
+ login: string;
143
+ id: number;
144
+ type?: string;
145
+ }
146
+
147
+ interface RawReview {
148
+ id: number;
149
+ state: string;
150
+ user: RawUser | null;
151
+ body: string | null;
152
+ commit_id: string | null;
153
+ submitted_at?: string | null;
154
+ html_url: string;
155
+ pull_request_url?: string;
156
+ }
157
+
158
+ interface RawComment {
159
+ id: number;
160
+ user: RawUser | null;
161
+ body: string | null;
162
+ html_url: string;
163
+ pull_request_url?: string;
164
+ issue_url?: string;
165
+ in_reply_to_id?: number;
166
+ }
167
+
168
+ /** GraphQL's actor: a bot's login has no `[bot]` suffix there. */
169
+ interface RawGraphqlActor {
170
+ __typename: string;
171
+ login: string;
172
+ databaseId?: number | null;
173
+ }
174
+
175
+ interface RawThreadComment {
176
+ databaseId: number;
177
+ body: string;
178
+ url: string;
179
+ createdAt: string;
180
+ author: RawGraphqlActor | null;
181
+ }
182
+
183
+ interface RawThreadComments {
184
+ pageInfo: { hasNextPage: boolean; endCursor: string | null };
185
+ nodes: RawThreadComment[];
186
+ }
187
+
188
+ interface RawThread {
189
+ id: string;
190
+ isResolved: boolean;
191
+ isOutdated: boolean;
192
+ path: string;
193
+ line: number | null;
194
+ startLine: number | null;
195
+ diffSide: "LEFT" | "RIGHT" | null;
196
+ comments: RawThreadComments;
197
+ }
198
+
199
+ /** Any node by id: only a review thread fills the thread fields. */
200
+ interface RawThreadNode {
201
+ __typename: string;
202
+ id?: string;
203
+ isResolved?: boolean;
204
+ pullRequest?: { number: number; repository: { nameWithOwner: string } };
205
+ comments?: { nodes: RawThreadComment[] };
206
+ latest?: { nodes: RawThreadComment[] };
207
+ }
208
+
209
+ const THREAD_COMMENT_FIELDS = `databaseId body url createdAt
210
+ author { __typename login ... on User { databaseId } }`;
211
+
212
+ const REVIEW_THREADS_QUERY = `query ReviewThreads($owner: String!, $name: String!, $number: Int!, $after: String) {
213
+ repository(owner: $owner, name: $name) {
214
+ pullRequest(number: $number) {
215
+ reviewThreads(first: 100, after: $after) {
216
+ pageInfo { hasNextPage endCursor }
217
+ nodes {
218
+ id isResolved isOutdated path line startLine diffSide
219
+ comments(first: 100) { pageInfo { hasNextPage endCursor } nodes { ${THREAD_COMMENT_FIELDS} } }
220
+ }
221
+ }
222
+ }
223
+ }
224
+ }`;
225
+
226
+ const THREAD_COMMENTS_QUERY = `query ThreadComments($id: ID!, $after: String) {
227
+ node(id: $id) {
228
+ ... on PullRequestReviewThread {
229
+ comments(first: 100, after: $after) { pageInfo { hasNextPage endCursor } nodes { ${THREAD_COMMENT_FIELDS} } }
230
+ }
231
+ }
232
+ }`;
233
+
234
+ const REVIEW_THREAD_QUERY = `query ReviewThread($id: ID!) {
235
+ node(id: $id) {
236
+ __typename
237
+ ... on PullRequestReviewThread {
238
+ id isResolved
239
+ pullRequest { number repository { nameWithOwner } }
240
+ comments(first: 1) { nodes { ${THREAD_COMMENT_FIELDS} } }
241
+ latest: comments(last: 1) { nodes { ${THREAD_COMMENT_FIELDS} } }
242
+ }
243
+ }
244
+ }`;
245
+
246
+ const RESOLVE_REVIEW_THREAD_MUTATION = `mutation ResolveReviewThread($id: ID!) {
247
+ resolveReviewThread(input: { threadId: $id }) { thread { id isResolved } }
248
+ }`;
249
+
250
+ /** Most pages any paginated read follows, so a loop always ends. */
251
+ const MAX_PAGES = 50;
252
+
253
+ function actorOf(user: RawUser | null): GithubActor | null {
254
+ return user
255
+ ? { login: user.login, type: user.type ?? "User", id: user.id }
256
+ : null;
257
+ }
258
+
259
+ function graphqlActorOf(actor: RawGraphqlActor | null): GithubActor | null {
260
+ if (!actor) return null;
261
+ const bot = actor.__typename === "Bot";
262
+ return {
263
+ login:
264
+ bot && !actor.login.endsWith("[bot]")
265
+ ? `${actor.login}[bot]`
266
+ : actor.login,
267
+ type: actor.__typename,
268
+ id: actor.databaseId ?? null,
269
+ };
270
+ }
271
+
272
+ function threadCommentOf(raw: RawThreadComment): GithubReviewThreadComment {
273
+ return {
274
+ id: raw.databaseId,
275
+ author: graphqlActorOf(raw.author),
276
+ body: raw.body,
277
+ url: raw.url,
278
+ createdAt: raw.createdAt,
279
+ };
280
+ }
281
+
282
+ function reviewOf(raw: RawReview): GithubPullRequestReview {
283
+ return {
284
+ id: raw.id,
285
+ state: raw.state,
286
+ author: actorOf(raw.user),
287
+ body: raw.body ?? "",
288
+ commitId: raw.commit_id ?? null,
289
+ submittedAt: raw.submitted_at ?? null,
290
+ url: raw.html_url,
291
+ number: trailingNumber(raw.pull_request_url, "pulls"),
292
+ };
293
+ }
294
+
295
+ function commentOf(raw: RawComment): GithubComment {
296
+ return {
297
+ id: raw.id,
298
+ author: actorOf(raw.user),
299
+ body: raw.body ?? "",
300
+ url: raw.html_url,
301
+ number:
302
+ trailingNumber(raw.pull_request_url, "pulls") ??
303
+ trailingNumber(raw.issue_url, "issues"),
304
+ ...(raw.in_reply_to_id ? { inReplyTo: raw.in_reply_to_id } : {}),
305
+ };
306
+ }
307
+
308
+ /** `…/pulls/42` → 42; null when the URL does not end that way. */
309
+ function trailingNumber(
310
+ url: string | undefined,
311
+ collection: "pulls" | "issues",
312
+ ): number | null {
313
+ const match = url ? new RegExp(`/${collection}/(\\d+)$`).exec(url) : null;
314
+ return match?.[1] ? Number(match[1]) : null;
315
+ }
316
+
317
+ function pullRequestSummary(pr: RawPullRequest): GithubPullRequest {
318
+ return {
319
+ number: pr.number,
320
+ body: pr.body ?? "",
321
+ headSha: pr.head.sha,
322
+ requestedReviewers: pr.requested_reviewers?.map((user) => user.login) ?? [],
323
+ title: pr.title,
324
+ url: pr.html_url,
325
+ author: pr.user?.login ?? "unknown",
326
+ head: pr.head.ref,
327
+ base: pr.base.ref,
328
+ draft: pr.draft,
329
+ updatedAt: pr.updated_at,
330
+ };
331
+ }
332
+
333
+ function discussionComment(raw: RawDiscussionComment) {
334
+ return {
335
+ id: raw.id,
336
+ body: raw.body ?? "",
337
+ author: raw.user,
338
+ createdAt: raw.created_at ?? raw.submitted_at ?? "",
339
+ url: raw.html_url,
340
+ ...(raw.state ? { state: raw.state } : {}),
341
+ ...(raw.path ? { path: raw.path, line: raw.line } : {}),
342
+ ...(raw.in_reply_to_id ? { replyToId: raw.in_reply_to_id } : {}),
343
+ ...(raw.diff_hunk ? { diffHunk: raw.diff_hunk } : {}),
344
+ ...(raw.side ? { side: raw.side } : {}),
345
+ };
346
+ }
347
+
348
+ /** Minimal REST client: a user access token, or anonymous public reads. */
349
+ export class GithubApi {
350
+ private readonly fetch: FetchLike;
351
+ private readonly baseUrl: string;
352
+ private readonly signal?: AbortSignal;
353
+
354
+ constructor(
355
+ private readonly accessToken: string | null,
356
+ opts?: GithubApiOptions,
357
+ ) {
358
+ this.fetch = opts?.fetch ?? fetch;
359
+ this.baseUrl = opts?.baseUrl ?? API_BASE;
360
+ this.signal = opts?.signal;
361
+ }
362
+
363
+ private async request<T>(
364
+ path: string,
365
+ init?: { method?: string; body?: unknown },
366
+ ): Promise<T> {
367
+ const response = await this.fetch(`${this.baseUrl}${path}`, {
368
+ ...(this.signal ? { signal: this.signal } : {}),
369
+ method: init?.method ?? "GET",
370
+ headers: {
371
+ Accept: "application/vnd.github+json",
372
+ ...(this.accessToken
373
+ ? { Authorization: `Bearer ${this.accessToken}` }
374
+ : {}),
375
+ "X-GitHub-Api-Version": "2022-11-28",
376
+ ...(init?.body !== undefined
377
+ ? { "Content-Type": "application/json" }
378
+ : {}),
379
+ },
380
+ ...(init?.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
381
+ });
382
+ if (!response.ok) {
383
+ const body = (await response.json().catch(() => ({}))) as {
384
+ message?: string;
385
+ };
386
+ throw new GithubApiError(
387
+ response.status,
388
+ body.message ?? `GitHub API returned ${response.status}`,
389
+ );
390
+ }
391
+ return (await response.json()) as T;
392
+ }
393
+
394
+ private async requestPages<T>(path: string): Promise<T[]> {
395
+ const values: T[] = [];
396
+ for (let page = 1; ; page++) {
397
+ const batch = await this.request<T[]>(
398
+ `${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`,
399
+ );
400
+ values.push(...batch);
401
+ if (batch.length < 100) return values;
402
+ }
403
+ }
404
+
405
+ /** A call GitHub answers with no body (204), such as a DELETE. */
406
+ private async requestNoContent(path: string, method: string): Promise<void> {
407
+ const response = await this.fetch(`${this.baseUrl}${path}`, {
408
+ ...(this.signal ? { signal: this.signal } : {}),
409
+ method,
410
+ headers: {
411
+ Accept: "application/vnd.github+json",
412
+ ...(this.accessToken
413
+ ? { Authorization: `Bearer ${this.accessToken}` }
414
+ : {}),
415
+ "X-GitHub-Api-Version": "2022-11-28",
416
+ },
417
+ });
418
+ if (!response.ok) {
419
+ const body = (await response.json().catch(() => ({}))) as {
420
+ message?: string;
421
+ };
422
+ throw new GithubApiError(
423
+ response.status,
424
+ body.message ?? `GitHub API returned ${response.status}`,
425
+ );
426
+ }
427
+ }
428
+
429
+ /**
430
+ * One GraphQL request against {@link githubGraphqlUrl} of the API base.
431
+ * HTTP failures throw {@link GithubApiError}; an answer carrying `errors`
432
+ * throws {@link GithubGraphqlError}, so a partial answer is never taken
433
+ * for a whole one.
434
+ */
435
+ async graphql<T>(
436
+ query: string,
437
+ variables: Readonly<Record<string, unknown>> = {},
438
+ ): Promise<T> {
439
+ const response = await this.fetch(githubGraphqlUrl(this.baseUrl), {
440
+ ...(this.signal ? { signal: this.signal } : {}),
441
+ method: "POST",
442
+ redirect: "error",
443
+ headers: {
444
+ Accept: "application/json",
445
+ ...(this.accessToken
446
+ ? { Authorization: `Bearer ${this.accessToken}` }
447
+ : {}),
448
+ "Content-Type": "application/json",
449
+ },
450
+ body: JSON.stringify({ query, variables }),
451
+ });
452
+ const body = (await response.json().catch(() => ({}))) as {
453
+ data?: T | null;
454
+ errors?: Array<{ message?: string; type?: string }>;
455
+ message?: string;
456
+ };
457
+ if (!response.ok) {
458
+ throw new GithubApiError(
459
+ response.status,
460
+ body.message ?? `GitHub GraphQL returned ${response.status}`,
461
+ );
462
+ }
463
+ if (body.errors?.length) {
464
+ throw new GithubGraphqlError(
465
+ body.errors.map((error) => ({
466
+ message: error.message ?? "unknown error",
467
+ ...(error.type ? { type: error.type } : {}),
468
+ })),
469
+ response.status,
470
+ );
471
+ }
472
+ if (body.data === undefined || body.data === null) {
473
+ throw new GithubApiError(
474
+ response.status,
475
+ "GitHub GraphQL returned no data",
476
+ );
477
+ }
478
+ return body.data;
479
+ }
480
+
481
+ /**
482
+ * Every review thread of a pull request with all of its comments, oldest
483
+ * first, following GraphQL's pages.
484
+ */
485
+ async reviewThreads(input: {
486
+ fullName: string;
487
+ number: number;
488
+ }): Promise<GithubReviewThread[]> {
489
+ const [owner = "", name = ""] = repositoryPath(input.fullName).split("/");
490
+ const threads: GithubReviewThread[] = [];
491
+ let after: string | null = null;
492
+ for (let page = 0; page < MAX_PAGES; page++) {
493
+ const data: {
494
+ repository: {
495
+ pullRequest: {
496
+ reviewThreads: {
497
+ pageInfo: { hasNextPage: boolean; endCursor: string | null };
498
+ nodes: RawThread[];
499
+ };
500
+ } | null;
501
+ } | null;
502
+ } = await this.graphql(REVIEW_THREADS_QUERY, {
503
+ owner,
504
+ name,
505
+ number: positive(input.number),
506
+ after,
507
+ });
508
+ const connection = data.repository?.pullRequest?.reviewThreads;
509
+ if (!connection) {
510
+ throw new GithubApiError(
511
+ 404,
512
+ `Pull request ${input.fullName}#${input.number} was not found`,
513
+ );
514
+ }
515
+ for (const thread of connection.nodes) {
516
+ const comments = thread.comments.nodes.map(threadCommentOf);
517
+ let more = thread.comments.pageInfo;
518
+ for (let next = 0; more.hasNextPage && next < MAX_PAGES; next++) {
519
+ const rest: { node: { comments: RawThreadComments } | null } =
520
+ await this.graphql(THREAD_COMMENTS_QUERY, {
521
+ id: thread.id,
522
+ after: more.endCursor,
523
+ });
524
+ if (!rest.node) break;
525
+ comments.push(...rest.node.comments.nodes.map(threadCommentOf));
526
+ more = rest.node.comments.pageInfo;
527
+ }
528
+ threads.push({
529
+ id: thread.id,
530
+ isResolved: thread.isResolved,
531
+ isOutdated: thread.isOutdated,
532
+ path: thread.path,
533
+ line: thread.line,
534
+ startLine: thread.startLine,
535
+ side: thread.diffSide,
536
+ comments,
537
+ });
538
+ }
539
+ if (!connection.pageInfo.hasNextPage) return threads;
540
+ after = connection.pageInfo.endCursor;
541
+ }
542
+ throw new GithubApiError(
543
+ 422,
544
+ `${input.fullName}#${input.number} has more review threads than Work reads`,
545
+ );
546
+ }
547
+
548
+ /**
549
+ * One review thread by node id: where it lives, whether it is resolved,
550
+ * and its first and last comments. Null when the id names no review
551
+ * thread.
552
+ */
553
+ async reviewThread(input: { threadId: string }): Promise<{
554
+ id: string;
555
+ isResolved: boolean;
556
+ repository: string;
557
+ number: number;
558
+ firstComment: GithubReviewThreadComment | null;
559
+ lastComment: GithubReviewThreadComment | null;
560
+ } | null> {
561
+ const data = await this.graphql<{ node: RawThreadNode | null }>(
562
+ REVIEW_THREAD_QUERY,
563
+ { id: input.threadId },
564
+ ).catch((error: unknown) => {
565
+ if (
566
+ error instanceof GithubGraphqlError &&
567
+ error.errors.every((entry) => entry.type === "NOT_FOUND")
568
+ )
569
+ return null;
570
+ throw error;
571
+ });
572
+ const node = data?.node;
573
+ if (
574
+ node?.__typename !== "PullRequestReviewThread" ||
575
+ !node.id ||
576
+ !node.pullRequest
577
+ )
578
+ return null;
579
+ const [first] = node.comments?.nodes ?? [];
580
+ const [last] = node.latest?.nodes ?? [];
581
+ return {
582
+ id: node.id,
583
+ isResolved: node.isResolved === true,
584
+ repository: node.pullRequest.repository.nameWithOwner,
585
+ number: node.pullRequest.number,
586
+ firstComment: first ? threadCommentOf(first) : null,
587
+ lastComment: last ? threadCommentOf(last) : null,
588
+ };
589
+ }
590
+
591
+ /** Mark a review thread resolved (GraphQL `resolveReviewThread`). */
592
+ async resolveReviewThread(input: {
593
+ threadId: string;
594
+ }): Promise<{ id: string; isResolved: boolean }> {
595
+ const data = await this.graphql<{
596
+ resolveReviewThread: {
597
+ thread: { id: string; isResolved: boolean };
598
+ } | null;
599
+ }>(RESOLVE_REVIEW_THREAD_MUTATION, { id: input.threadId });
600
+ const thread = data.resolveReviewThread?.thread;
601
+ if (!thread) {
602
+ throw new GithubApiError(422, "GitHub did not resolve the review thread");
603
+ }
604
+ return { id: thread.id, isResolved: thread.isResolved };
605
+ }
606
+
607
+ /** Replace a pull request's description. */
608
+ async updatePullRequest(input: {
609
+ fullName: string;
610
+ number: number;
611
+ body: string;
612
+ }): Promise<{ number: number; url: string; body: string }> {
613
+ const raw = await this.request<{
614
+ number: number;
615
+ html_url: string;
616
+ body: string | null;
617
+ }>(
618
+ `/repos/${repositoryPath(input.fullName)}/pulls/${positive(input.number)}`,
619
+ { method: "PATCH", body: { body: input.body } },
620
+ );
621
+ return { number: raw.number, url: raw.html_url, body: raw.body ?? "" };
622
+ }
623
+
624
+ /** A pull request's reviews, oldest first. */
625
+ async listReviews(input: {
626
+ fullName: string;
627
+ number: number;
628
+ }): Promise<GithubPullRequestReview[]> {
629
+ const raw = await this.requestPages<RawReview>(
630
+ `/repos/${repositoryPath(input.fullName)}/pulls/${positive(input.number)}/reviews`,
631
+ );
632
+ return raw.map(reviewOf);
633
+ }
634
+
635
+ async review(input: {
636
+ fullName: string;
637
+ number: number;
638
+ reviewId: number;
639
+ }): Promise<GithubPullRequestReview> {
640
+ return reviewOf(
641
+ await this.request<RawReview>(
642
+ `/repos/${repositoryPath(input.fullName)}/pulls/${positive(input.number)}/reviews/${positive(input.reviewId)}`,
643
+ ),
644
+ );
645
+ }
646
+
647
+ /**
648
+ * Dismiss a review that approved or requested changes, so it no longer
649
+ * counts toward the pull request's review decision.
650
+ */
651
+ async dismissReview(input: {
652
+ fullName: string;
653
+ number: number;
654
+ reviewId: number;
655
+ message: string;
656
+ }): Promise<GithubPullRequestReview> {
657
+ return reviewOf(
658
+ await this.request<RawReview>(
659
+ `/repos/${repositoryPath(input.fullName)}/pulls/${positive(input.number)}/reviews/${positive(input.reviewId)}/dismissals`,
660
+ {
661
+ method: "PUT",
662
+ body: { message: input.message, event: "DISMISS" },
663
+ },
664
+ ),
665
+ );
666
+ }
667
+
668
+ /** A pull request review comment (an inline comment) by id. */
669
+ async reviewComment(input: {
670
+ fullName: string;
671
+ commentId: number;
672
+ }): Promise<GithubComment> {
673
+ return commentOf(
674
+ await this.request<RawComment>(
675
+ `/repos/${repositoryPath(input.fullName)}/pulls/comments/${positive(input.commentId)}`,
676
+ ),
677
+ );
678
+ }
679
+
680
+ /** An issue or pull request conversation comment by id. */
681
+ async issueComment(input: {
682
+ fullName: string;
683
+ commentId: number;
684
+ }): Promise<GithubComment> {
685
+ return commentOf(
686
+ await this.request<RawComment>(
687
+ `/repos/${repositoryPath(input.fullName)}/issues/comments/${positive(input.commentId)}`,
688
+ ),
689
+ );
690
+ }
691
+
692
+ async updateIssueComment(input: {
693
+ fullName: string;
694
+ commentId: number;
695
+ body: string;
696
+ }): Promise<GithubComment> {
697
+ return commentOf(
698
+ await this.request<RawComment>(
699
+ `/repos/${repositoryPath(input.fullName)}/issues/comments/${positive(input.commentId)}`,
700
+ { method: "PATCH", body: { body: input.body } },
701
+ ),
702
+ );
703
+ }
704
+
705
+ /** Whether an issue number names a pull request. */
706
+ async issueKind(input: {
707
+ fullName: string;
708
+ number: number;
709
+ }): Promise<"issue" | "pull_request"> {
710
+ const raw = await this.request<{ pull_request?: unknown }>(
711
+ `/repos/${repositoryPath(input.fullName)}/issues/${positive(input.number)}`,
712
+ );
713
+ return raw.pull_request ? "pull_request" : "issue";
714
+ }
715
+
716
+ /** An issue's or pull request's conversation comments, oldest first. */
717
+ async issueComments(input: {
718
+ fullName: string;
719
+ number: number;
720
+ }): Promise<GithubComment[]> {
721
+ const raw = await this.requestPages<RawComment>(
722
+ `/repos/${repositoryPath(input.fullName)}/issues/${positive(input.number)}/comments`,
723
+ );
724
+ return raw.map(commentOf);
725
+ }
726
+
727
+ /** A pull request's inline review comments, oldest first. */
728
+ async reviewComments(input: {
729
+ fullName: string;
730
+ number: number;
731
+ }): Promise<GithubComment[]> {
732
+ const raw = await this.requestPages<RawComment>(
733
+ `/repos/${repositoryPath(input.fullName)}/pulls/${positive(input.number)}/comments`,
734
+ );
735
+ return raw.map(commentOf);
736
+ }
737
+
738
+ /** Check runs on a commit, by name when given, with the App that made each. */
739
+ async checkRuns(input: {
740
+ fullName: string;
741
+ sha: string;
742
+ name?: string;
743
+ }): Promise<
744
+ Array<{
745
+ id: number;
746
+ externalId: string | null;
747
+ app: string | null;
748
+ status: string;
749
+ conclusion: string | null;
750
+ url: string | null;
751
+ }>
752
+ > {
753
+ if (!/^[0-9a-f]{40}$/.test(input.sha)) {
754
+ throw new GithubApiError(400, `Invalid commit: ${input.sha}`);
755
+ }
756
+ const runs: Array<{
757
+ id: number;
758
+ external_id: string | null;
759
+ app: { slug: string } | null;
760
+ status: string;
761
+ conclusion: string | null;
762
+ html_url: string | null;
763
+ }> = [];
764
+ const name = input.name
765
+ ? `&check_name=${encodeURIComponent(input.name)}`
766
+ : "";
767
+ for (let page = 1; page <= MAX_PAGES; page++) {
768
+ const batch = await this.request<{ check_runs: typeof runs }>(
769
+ `/repos/${repositoryPath(input.fullName)}/commits/${input.sha}/check-runs?filter=all&per_page=100&page=${page}${name}`,
770
+ );
771
+ runs.push(...batch.check_runs);
772
+ if (batch.check_runs.length < 100) break;
773
+ }
774
+ return runs.map((run) => ({
775
+ id: run.id,
776
+ externalId: run.external_id ?? null,
777
+ app: run.app?.slug ?? null,
778
+ status: run.status,
779
+ conclusion: run.conclusion,
780
+ url: run.html_url,
781
+ }));
782
+ }
783
+
784
+ async deleteIssueComment(input: {
785
+ fullName: string;
786
+ commentId: number;
787
+ }): Promise<void> {
788
+ await this.requestNoContent(
789
+ `/repos/${repositoryPath(input.fullName)}/issues/comments/${positive(input.commentId)}`,
790
+ "DELETE",
791
+ );
792
+ }
793
+
794
+ async getUser(): Promise<GithubUser> {
795
+ const raw = await this.request<{
796
+ login: string;
797
+ id: number;
798
+ avatar_url: string;
799
+ name: string | null;
800
+ }>("/user");
801
+ return {
802
+ login: raw.login,
803
+ id: raw.id,
804
+ avatarUrl: raw.avatar_url,
805
+ name: raw.name,
806
+ };
807
+ }
808
+
809
+ async getRepo(fullName: string): Promise<GithubRepo> {
810
+ if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) {
811
+ throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
812
+ }
813
+ return mapRepo(await this.request<RawRepo>(`/repos/${fullName}`));
814
+ }
815
+
816
+ /**
817
+ * Create an empty repository for the authenticated user, or in
818
+ * `organization` when given. Nothing is initialized, so the first push
819
+ * defines its history.
820
+ */
821
+ async createRepo(input: {
822
+ name: string;
823
+ organization?: string;
824
+ private: boolean;
825
+ description?: string;
826
+ }): Promise<GithubRepo> {
827
+ if (!/^[\w.-]+$/.test(input.name)) {
828
+ throw new GithubApiError(400, `Invalid repository name: ${input.name}`);
829
+ }
830
+ if (input.organization && !/^[\w.-]+$/.test(input.organization)) {
831
+ throw new GithubApiError(
832
+ 400,
833
+ `Invalid organization: ${input.organization}`,
834
+ );
835
+ }
836
+ return mapRepo(
837
+ await this.request<RawRepo>(
838
+ input.organization
839
+ ? `/orgs/${input.organization}/repos`
840
+ : "/user/repos",
841
+ {
842
+ method: "POST",
843
+ body: {
844
+ name: input.name,
845
+ private: input.private,
846
+ auto_init: false,
847
+ ...(input.description !== undefined
848
+ ? { description: input.description }
849
+ : {}),
850
+ },
851
+ },
852
+ ),
853
+ );
854
+ }
855
+
856
+ /**
857
+ * Open a pull request. `head` and `base` are branch names in the same
858
+ * repository (cross-fork PRs are out of scope for now).
859
+ */
860
+ async createPullRequest(
861
+ fullName: string,
862
+ input: { title: string; head: string; base: string; body?: string },
863
+ ): Promise<{ url: string; number: number }> {
864
+ if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) {
865
+ throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
866
+ }
867
+ const raw = await this.request<{ html_url: string; number: number }>(
868
+ `/repos/${fullName}/pulls`,
869
+ {
870
+ method: "POST",
871
+ body: {
872
+ title: input.title,
873
+ head: input.head,
874
+ base: input.base,
875
+ ...(input.body !== undefined ? { body: input.body } : {}),
876
+ },
877
+ },
878
+ );
879
+ return { url: raw.html_url, number: raw.number };
880
+ }
881
+
882
+ async pullRequestDiscussion(input: { fullName: string; number: number }) {
883
+ const base = `/repos/${input.fullName}`;
884
+ const pull = await this.request<{
885
+ state: string;
886
+ merged: boolean;
887
+ head: { sha: string };
888
+ assignees: Array<{ login: string }>;
889
+ requested_reviewers: Array<{ login: string }>;
890
+ }>(`${base}/pulls/${input.number}`);
891
+ const [reviews, comments, inlineComments, checks] = await Promise.all([
892
+ this.requestPages<RawDiscussionComment>(
893
+ `${base}/pulls/${input.number}/reviews`,
894
+ ),
895
+ this.requestPages<RawDiscussionComment>(
896
+ `${base}/issues/${input.number}/comments`,
897
+ ),
898
+ this.requestPages<RawDiscussionComment>(
899
+ `${base}/pulls/${input.number}/comments`,
900
+ ),
901
+ this.request<{
902
+ check_runs: Array<{
903
+ name: string;
904
+ status: string;
905
+ conclusion: string | null;
906
+ html_url: string;
907
+ }>;
908
+ }>(`${base}/commits/${pull.head.sha}/check-runs?per_page=100`),
909
+ ]);
910
+ return {
911
+ state: pull.merged ? "MERGED" : pull.state.toUpperCase(),
912
+ reviewDecision: null,
913
+ assignees: pull.assignees.map(({ login }) => ({ login })),
914
+ reviewRequests: pull.requested_reviewers.map(({ login }) => ({ login })),
915
+ reviews: reviews.map(discussionComment),
916
+ comments: comments.map(discussionComment),
917
+ inlineComments: inlineComments.map(discussionComment),
918
+ inlineCommentsUnavailable: false,
919
+ statusCheckRollup: checks.check_runs.map((check) => ({
920
+ name: check.name,
921
+ status: check.status.toUpperCase(),
922
+ conclusion: check.conclusion?.toUpperCase() ?? null,
923
+ detailsUrl: check.html_url,
924
+ })),
925
+ };
926
+ }
927
+
928
+ async commentOnPullRequest(input: {
929
+ fullName: string;
930
+ number: number;
931
+ body: string;
932
+ replyTo?: number;
933
+ }) {
934
+ const endpoint = input.replyTo
935
+ ? `/repos/${input.fullName}/pulls/${input.number}/comments/${input.replyTo}/replies`
936
+ : `/repos/${input.fullName}/issues/${input.number}/comments`;
937
+ return discussionComment(
938
+ await this.request<RawDiscussionComment>(endpoint, {
939
+ method: "POST",
940
+ body: { body: input.body },
941
+ }),
942
+ );
943
+ }
944
+
945
+ /**
946
+ * Submit a pull request review, optionally with inline comments anchored
947
+ * to lines of the diff. Without `event` the review stays pending on GitHub;
948
+ * `COMMENT` publishes it without a verdict.
949
+ */
950
+ async createReview(input: {
951
+ fullName: string;
952
+ number: number;
953
+ event?: GithubReviewEvent;
954
+ body?: string;
955
+ /** The revision reviewed; defaults to the pull request's current head. */
956
+ commitId?: string;
957
+ comments?: readonly GithubReviewComment[];
958
+ }): Promise<{ id: number; url: string; state: string }> {
959
+ const raw = await this.request<{
960
+ id: number;
961
+ html_url: string;
962
+ state: string;
963
+ }>(
964
+ `/repos/${repositoryPath(input.fullName)}/pulls/${positive(input.number)}/reviews`,
965
+ {
966
+ method: "POST",
967
+ body: {
968
+ ...(input.event ? { event: input.event } : {}),
969
+ ...(input.body !== undefined ? { body: input.body } : {}),
970
+ ...(input.commitId ? { commit_id: input.commitId } : {}),
971
+ ...(input.comments?.length
972
+ ? {
973
+ comments: input.comments.map((comment) => ({
974
+ path: comment.path,
975
+ body: comment.body,
976
+ ...(comment.line !== undefined ? { line: comment.line } : {}),
977
+ ...(comment.side ? { side: comment.side } : {}),
978
+ ...(comment.startLine !== undefined
979
+ ? { start_line: comment.startLine }
980
+ : {}),
981
+ ...(comment.startSide
982
+ ? { start_side: comment.startSide }
983
+ : {}),
984
+ })),
985
+ }
986
+ : {}),
987
+ },
988
+ },
989
+ );
990
+ return { id: raw.id, url: raw.html_url, state: raw.state };
991
+ }
992
+
993
+ /** Report a check run on a commit (requires the app's `checks` permission). */
994
+ async createCheckRun(
995
+ input: GithubCheckRunFields & {
996
+ fullName: string;
997
+ name: string;
998
+ headSha: string;
999
+ },
1000
+ ): Promise<GithubCheckRun> {
1001
+ return mapCheckRun(
1002
+ await this.request<RawCheckRunResult>(
1003
+ `/repos/${repositoryPath(input.fullName)}/check-runs`,
1004
+ {
1005
+ method: "POST",
1006
+ body: {
1007
+ name: input.name,
1008
+ head_sha: input.headSha,
1009
+ ...checkRunBody(input),
1010
+ },
1011
+ },
1012
+ ),
1013
+ );
1014
+ }
1015
+
1016
+ async updateCheckRun(
1017
+ input: GithubCheckRunFields & {
1018
+ fullName: string;
1019
+ checkRunId: number;
1020
+ name?: string;
1021
+ },
1022
+ ): Promise<GithubCheckRun> {
1023
+ return mapCheckRun(
1024
+ await this.request<RawCheckRunResult>(
1025
+ `/repos/${repositoryPath(input.fullName)}/check-runs/${positive(input.checkRunId)}`,
1026
+ {
1027
+ method: "PATCH",
1028
+ body: {
1029
+ ...(input.name ? { name: input.name } : {}),
1030
+ ...checkRunBody(input),
1031
+ },
1032
+ },
1033
+ ),
1034
+ );
1035
+ }
1036
+
1037
+ /** Tie each review to the exact revision the reviewer inspected. */
1038
+ async reviewPullRequest(input: {
1039
+ fullName: string;
1040
+ number: number;
1041
+ headSha: string;
1042
+ decision: "APPROVE" | "REQUEST_CHANGES";
1043
+ body: string;
1044
+ }): Promise<void> {
1045
+ const current = await this.request<{
1046
+ state: string;
1047
+ head: { sha: string };
1048
+ }>(`/repos/${input.fullName}/pulls/${input.number}`);
1049
+ if (current.state !== "open" || current.head.sha !== input.headSha)
1050
+ throw new Error(
1051
+ "This proposal changed since you opened it. Refresh and review the latest changes.",
1052
+ );
1053
+ await this.request(
1054
+ `/repos/${input.fullName}/pulls/${input.number}/reviews`,
1055
+ {
1056
+ method: "POST",
1057
+ body: {
1058
+ commit_id: input.headSha,
1059
+ event: input.decision,
1060
+ body: input.body,
1061
+ },
1062
+ },
1063
+ );
1064
+ }
1065
+
1066
+ async mergePullRequest(input: {
1067
+ fullName: string;
1068
+ number: number;
1069
+ headSha: string;
1070
+ }): Promise<{ sha: string }> {
1071
+ const result = await this.request<{
1072
+ merged: boolean;
1073
+ sha: string;
1074
+ message: string;
1075
+ }>(`/repos/${input.fullName}/pulls/${input.number}/merge`, {
1076
+ method: "PUT",
1077
+ body: { sha: input.headSha, merge_method: "squash" },
1078
+ });
1079
+ if (!result.merged)
1080
+ throw new Error(result.message || "The proposal could not be applied");
1081
+ return { sha: result.sha };
1082
+ }
1083
+
1084
+ /** GitHub includes direct and team requests in review-requested:@me. */
1085
+ private async requestedReviewNumbers(fullName: string): Promise<Set<number>> {
1086
+ const numbers = new Set<number>();
1087
+ const query = encodeURIComponent(
1088
+ `repo:${fullName} is:pr is:open review-requested:@me`,
1089
+ );
1090
+ for (let page = 1; page <= 10; page++) {
1091
+ const result = await this.request<{
1092
+ items: Array<{ number: number }>;
1093
+ incomplete_results: boolean;
1094
+ total_count: number;
1095
+ }>(`/search/issues?q=${query}&per_page=100&page=${page}`);
1096
+ if (result.incomplete_results || result.total_count > 1000)
1097
+ throw new Error("Review request search is incomplete");
1098
+ for (const item of result.items) numbers.add(item.number);
1099
+ if (result.items.length < 100 || numbers.size >= result.total_count)
1100
+ return numbers;
1101
+ }
1102
+ throw new Error("Review request search is incomplete");
1103
+ }
1104
+
1105
+ /** Open pull requests, most recently updated first. */
1106
+ async listPullRequests(fullName: string): Promise<GithubPullRequest[]> {
1107
+ if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) {
1108
+ throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
1109
+ }
1110
+ const raw = await this.requestPages<RawPullRequest>(
1111
+ `/repos/${fullName}/pulls?state=open&sort=updated&direction=desc`,
1112
+ );
1113
+ const requested = raw.length
1114
+ ? await this.requestedReviewNumbers(fullName).catch(() => undefined)
1115
+ : new Set<number>();
1116
+ return raw.map((pr) => ({
1117
+ ...(requested
1118
+ ? { reviewRequestedForViewer: requested.has(pr.number) }
1119
+ : { reviewRequestsUnavailable: true }),
1120
+ ...pullRequestSummary(pr),
1121
+ }));
1122
+ }
1123
+
1124
+ /** Read an individual pull request, including completed proposals. */
1125
+ async pullRequest(input: {
1126
+ fullName: string;
1127
+ number: number;
1128
+ }): Promise<GithubPullRequest> {
1129
+ if (
1130
+ !/^[\w.-]+\/[\w.-]+$/.test(input.fullName) ||
1131
+ !Number.isSafeInteger(input.number) ||
1132
+ input.number <= 0
1133
+ )
1134
+ throw new GithubApiError(400, "Invalid pull request");
1135
+ return pullRequestSummary(
1136
+ await this.request<RawPullRequest>(
1137
+ `/repos/${input.fullName}/pulls/${input.number}`,
1138
+ ),
1139
+ );
1140
+ }
1141
+
1142
+ /**
1143
+ * Where a pull request stands: open, draft, merged or closed, how much it
1144
+ * changes, how many comments it has and what its head's checks say. A
1145
+ * token that cannot read checks still reads the rest.
1146
+ */
1147
+ async pullRequestStatus(input: {
1148
+ fullName: string;
1149
+ number: number;
1150
+ /** Anonymous chip reads reserve their smaller rate limit for status. */
1151
+ includeChecks?: boolean;
1152
+ }): Promise<GithubPullRequestStatus> {
1153
+ if (
1154
+ !/^[\w.-]+\/[\w.-]+$/.test(input.fullName) ||
1155
+ !Number.isSafeInteger(input.number) ||
1156
+ input.number <= 0
1157
+ )
1158
+ throw new GithubApiError(400, "Invalid pull request");
1159
+ const pr = await this.request<RawPullRequestDetail>(
1160
+ `/repos/${input.fullName}/pulls/${input.number}`,
1161
+ );
1162
+ const checks =
1163
+ input.includeChecks !== false && pr.state === "open" && pr.head.sha
1164
+ ? await this.checksOf(input.fullName, pr.head.sha).catch(
1165
+ () => undefined,
1166
+ )
1167
+ : undefined;
1168
+ return {
1169
+ number: pr.number,
1170
+ title: pr.title,
1171
+ url: pr.html_url,
1172
+ repository: input.fullName,
1173
+ author: pr.user?.login ?? "unknown",
1174
+ head: pr.head.ref,
1175
+ base: pr.base.ref,
1176
+ state:
1177
+ pr.merged || pr.merged_at
1178
+ ? "merged"
1179
+ : pr.state === "closed"
1180
+ ? "closed"
1181
+ : pr.draft
1182
+ ? "draft"
1183
+ : "open",
1184
+ additions: pr.additions ?? 0,
1185
+ deletions: pr.deletions ?? 0,
1186
+ changedFiles: pr.changed_files ?? 0,
1187
+ comments: (pr.comments ?? 0) + (pr.review_comments ?? 0),
1188
+ ...(checks ? { checks } : {}),
1189
+ updatedAt: pr.updated_at,
1190
+ };
1191
+ }
1192
+
1193
+ /** Check runs and commit statuses on one commit, counted together. */
1194
+ private async checksOf(
1195
+ fullName: string,
1196
+ sha: string,
1197
+ ): Promise<GithubPullRequestStatus["checks"]> {
1198
+ const [runs, status] = await Promise.all([
1199
+ this.request<{ check_runs: RawCheckRun[] }>(
1200
+ `/repos/${fullName}/commits/${sha}/check-runs?per_page=100`,
1201
+ ),
1202
+ this.request<RawCommitStatus>(
1203
+ `/repos/${fullName}/commits/${sha}/status`,
1204
+ ).catch(() => undefined),
1205
+ ]);
1206
+ const counts = { passed: 0, failed: 0, pending: 0 };
1207
+ for (const run of runs.check_runs) {
1208
+ if (run.status !== "completed") counts.pending += 1;
1209
+ else if (run.conclusion && FAILED_CONCLUSIONS.has(run.conclusion))
1210
+ counts.failed += 1;
1211
+ else counts.passed += 1;
1212
+ }
1213
+ for (const entry of status?.statuses ?? []) {
1214
+ if (entry.state === "pending") counts.pending += 1;
1215
+ else if (entry.state === "success") counts.passed += 1;
1216
+ else counts.failed += 1;
1217
+ }
1218
+ if (counts.passed + counts.failed + counts.pending === 0) return undefined;
1219
+ return {
1220
+ state:
1221
+ counts.failed > 0
1222
+ ? "failure"
1223
+ : counts.pending > 0
1224
+ ? "pending"
1225
+ : "success",
1226
+ ...counts,
1227
+ };
1228
+ }
1229
+
1230
+ /** Changed files of a pull request, with unified-diff patches. */
1231
+ async pullRequestFiles(
1232
+ fullName: string,
1233
+ number: number,
1234
+ ): Promise<GithubPullRequestFile[]> {
1235
+ if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) {
1236
+ throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
1237
+ }
1238
+ const raw = await this.requestPages<{
1239
+ filename: string;
1240
+ status: string;
1241
+ additions: number;
1242
+ deletions: number;
1243
+ patch?: string;
1244
+ previous_filename?: string;
1245
+ }>(`/repos/${fullName}/pulls/${number}/files`);
1246
+ return raw.map((file) => ({
1247
+ path: file.filename,
1248
+ status: file.status,
1249
+ additions: file.additions,
1250
+ deletions: file.deletions,
1251
+ // Absent for binary/huge files — the viewer shows a placeholder.
1252
+ patch: file.patch ?? null,
1253
+ ...(file.previous_filename
1254
+ ? { previousPath: file.previous_filename }
1255
+ : {}),
1256
+ }));
1257
+ }
1258
+
1259
+ /** Repository activity available to the connected user. */
1260
+ async listRepositoryEvents(
1261
+ fullName: string,
1262
+ ): Promise<GithubRepositoryEvent[]> {
1263
+ if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) {
1264
+ throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
1265
+ }
1266
+ const raw = await this.request<
1267
+ Array<{
1268
+ id: string;
1269
+ type: string;
1270
+ actor: { login: string } | null;
1271
+ created_at: string;
1272
+ payload: unknown;
1273
+ }>
1274
+ >(`/repos/${fullName}/events?per_page=100`);
1275
+ return raw.map((event) => ({
1276
+ id: event.id,
1277
+ type: event.type,
1278
+ actor: event.actor?.login ?? null,
1279
+ createdAt: event.created_at,
1280
+ payload: event.payload,
1281
+ }));
1282
+ }
1283
+
1284
+ /**
1285
+ * Complete polling surface for desktop Watchers. The repository Events API
1286
+ * omits some check and Actions transitions, so merge state-stamped snapshots
1287
+ * from the dedicated APIs. Unsupported permission slices degrade to the
1288
+ * events the connected user can read instead of disabling the monitor.
1289
+ */
1290
+ async listRepositoryWatchEvents(
1291
+ fullName: string,
1292
+ ): Promise<GithubRepositoryEvent[]> {
1293
+ if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) {
1294
+ throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
1295
+ }
1296
+ const [events, pulls, workflowRuns] = await Promise.all([
1297
+ this.listRepositoryEvents(fullName),
1298
+ this.optionalRequest<RawWatchPull[]>(
1299
+ `/repos/${fullName}/pulls?state=all&sort=updated&direction=desc&per_page=25`,
1300
+ [],
1301
+ ),
1302
+ this.optionalRequest<{ workflow_runs: RawWorkflowRun[] }>(
1303
+ `/repos/${fullName}/actions/runs?per_page=100`,
1304
+ { workflow_runs: [] },
1305
+ ),
1306
+ ]);
1307
+ const recentPulls = pulls.slice(0, 3);
1308
+ const pullDetails = await Promise.all(
1309
+ recentPulls.map(async (pull) => {
1310
+ const [reviews, runs, suites] = await Promise.all([
1311
+ this.optionalRequest<RawPullReview[]>(
1312
+ `/repos/${fullName}/pulls/${pull.number}/reviews?per_page=100`,
1313
+ [],
1314
+ ),
1315
+ this.optionalRequest<{ check_runs: RawCheckRun[] }>(
1316
+ `/repos/${fullName}/commits/${pull.head.sha}/check-runs?filter=all&per_page=100`,
1317
+ { check_runs: [] },
1318
+ ),
1319
+ this.optionalRequest<{ check_suites: RawCheckSuite[] }>(
1320
+ `/repos/${fullName}/commits/${pull.head.sha}/check-suites?per_page=100`,
1321
+ { check_suites: [] },
1322
+ ),
1323
+ ]);
1324
+ return {
1325
+ pull,
1326
+ reviews,
1327
+ runs: runs.check_runs,
1328
+ suites: suites.check_suites,
1329
+ };
1330
+ }),
1331
+ );
1332
+ const snapshots: GithubRepositoryEvent[] = [
1333
+ ...pulls.map((pull) => ({
1334
+ id: `pull_request:${pull.id}:${pull.updated_at}`,
1335
+ type: "PullRequestEvent",
1336
+ actor: pull.user?.login ?? null,
1337
+ createdAt: pull.updated_at,
1338
+ payload: { action: "updated", number: pull.number, pull_request: pull },
1339
+ })),
1340
+ ...workflowRuns.workflow_runs.map((run) => ({
1341
+ id: `workflow_run:${run.id}:${run.run_attempt}:${run.updated_at}:${run.status}:${run.conclusion ?? ""}`,
1342
+ type: "WorkflowRunEvent",
1343
+ actor: run.actor?.login ?? null,
1344
+ createdAt: run.updated_at,
1345
+ payload: { action: run.status, workflow_run: run },
1346
+ })),
1347
+ ...pullDetails.flatMap(({ pull, reviews, runs, suites }) => [
1348
+ ...reviews.map((review) => ({
1349
+ id: `pull_request_review:${review.id}:${review.submitted_at}:${review.state}`,
1350
+ type: "PullRequestReviewEvent",
1351
+ actor: review.user?.login ?? null,
1352
+ createdAt: review.submitted_at,
1353
+ payload: { action: "submitted", review, pull_request: pull },
1354
+ })),
1355
+ ...runs.map((run) => ({
1356
+ id: `check_run:${run.id}:${run.updated_at}:${run.status}:${run.conclusion ?? ""}`,
1357
+ type: "CheckRunEvent",
1358
+ actor: run.app?.slug ?? null,
1359
+ createdAt: run.updated_at,
1360
+ payload: { action: run.status, check_run: run, pull_request: pull },
1361
+ })),
1362
+ ...suites.map((suite) => ({
1363
+ id: `check_suite:${suite.id}:${suite.updated_at}:${suite.status}:${suite.conclusion ?? ""}`,
1364
+ type: "CheckSuiteEvent",
1365
+ actor: suite.app?.slug ?? null,
1366
+ createdAt: suite.updated_at,
1367
+ payload: {
1368
+ action: suite.status,
1369
+ check_suite: suite,
1370
+ pull_request: pull,
1371
+ },
1372
+ })),
1373
+ ]),
1374
+ ];
1375
+ return [...events, ...snapshots]
1376
+ .filter(
1377
+ (event, index, all) =>
1378
+ all.findIndex((candidate) => candidate.id === event.id) === index,
1379
+ )
1380
+ .sort((left, right) => right.createdAt.localeCompare(left.createdAt));
1381
+ }
1382
+
1383
+ private async optionalRequest<T>(path: string, fallback: T): Promise<T> {
1384
+ try {
1385
+ return await this.request<T>(path);
1386
+ } catch (error) {
1387
+ if (
1388
+ error instanceof GithubApiError &&
1389
+ (error.status === 403 || error.status === 404)
1390
+ ) {
1391
+ return fallback;
1392
+ }
1393
+ throw error;
1394
+ }
1395
+ }
1396
+
1397
+ /**
1398
+ * Repositories the authenticated user can access. GitHub supports this one
1399
+ * endpoint for GitHub App user tokens, fine-grained tokens, and the OAuth
1400
+ * token exposed by `gh`, so every credential source follows the same API.
1401
+ */
1402
+ async listAccessibleRepos(opts?: {
1403
+ perPage?: number;
1404
+ }): Promise<GithubRepo[]> {
1405
+ const perPage = opts?.perPage ?? 100;
1406
+ const repos: GithubRepo[] = [];
1407
+ let page = 1;
1408
+ for (;;) {
1409
+ const result = await this.request<RawRepo[]>(
1410
+ `/user/repos?per_page=${perPage}&page=${page}&sort=pushed&direction=desc`,
1411
+ );
1412
+ repos.push(...result.map(mapRepo));
1413
+ if (result.length < perPage) break;
1414
+ page += 1;
1415
+ }
1416
+ return repos.sort((a, b) =>
1417
+ (b.pushedAt ?? "").localeCompare(a.pushedAt ?? ""),
1418
+ );
1419
+ }
1420
+
1421
+ /** Repositories a GitHub App installation token can reach. */
1422
+ async listInstallationRepos(): Promise<GithubRepo[]> {
1423
+ const repos: GithubRepo[] = [];
1424
+ for (let page = 1; ; page += 1) {
1425
+ const result = await this.request<{ repositories: RawRepo[] }>(
1426
+ `/installation/repositories?per_page=100&page=${page}`,
1427
+ );
1428
+ repos.push(...result.repositories.map(mapRepo));
1429
+ if (result.repositories.length < 100) break;
1430
+ }
1431
+ return repos.sort((a, b) =>
1432
+ (b.pushedAt ?? "").localeCompare(a.pushedAt ?? ""),
1433
+ );
1434
+ }
1435
+ }
1436
+
1437
+ interface RawCheckRunResult {
1438
+ id: number;
1439
+ html_url: string | null;
1440
+ status: string;
1441
+ conclusion: string | null;
1442
+ }
1443
+
1444
+ function mapCheckRun(raw: RawCheckRunResult): GithubCheckRun {
1445
+ return {
1446
+ id: raw.id,
1447
+ url: raw.html_url,
1448
+ status: raw.status,
1449
+ conclusion: raw.conclusion,
1450
+ };
1451
+ }
1452
+
1453
+ function checkRunBody(fields: GithubCheckRunFields) {
1454
+ return {
1455
+ ...(fields.status ? { status: fields.status } : {}),
1456
+ ...(fields.conclusion ? { conclusion: fields.conclusion } : {}),
1457
+ ...(fields.detailsUrl ? { details_url: fields.detailsUrl } : {}),
1458
+ ...(fields.externalId ? { external_id: fields.externalId } : {}),
1459
+ ...(fields.startedAt ? { started_at: fields.startedAt } : {}),
1460
+ ...(fields.completedAt ? { completed_at: fields.completedAt } : {}),
1461
+ ...(fields.output
1462
+ ? {
1463
+ output: {
1464
+ title: fields.output.title,
1465
+ summary: fields.output.summary,
1466
+ ...(fields.output.text ? { text: fields.output.text } : {}),
1467
+ ...(fields.output.annotations?.length
1468
+ ? {
1469
+ annotations: fields.output.annotations.map((annotation) => ({
1470
+ path: annotation.path,
1471
+ start_line: annotation.startLine,
1472
+ end_line: annotation.endLine,
1473
+ annotation_level: annotation.level,
1474
+ message: annotation.message,
1475
+ ...(annotation.title ? { title: annotation.title } : {}),
1476
+ })),
1477
+ }
1478
+ : {}),
1479
+ },
1480
+ }
1481
+ : {}),
1482
+ };
1483
+ }
1484
+
1485
+ /**
1486
+ * The GraphQL endpoint beside a REST API base: `https://api.github.com/graphql`
1487
+ * for github.com (and GHE.com's `api.<subdomain>.ghe.com`), and `/api/graphql`
1488
+ * for GitHub Enterprise Server, whose REST base is `https://HOST/api/v3`.
1489
+ */
1490
+ export function githubGraphqlUrl(apiBaseUrl: string = API_BASE): string {
1491
+ const url = new URL(apiBaseUrl);
1492
+ const path = url.pathname.replace(/\/+$/, "");
1493
+ url.pathname = /\/api\/v3$/.test(path)
1494
+ ? `${path.slice(0, -"/v3".length)}/graphql`
1495
+ : `${path}/graphql`;
1496
+ url.search = "";
1497
+ url.hash = "";
1498
+ return url.toString();
1499
+ }
1500
+
1501
+ function repositoryPath(fullName: string): string {
1502
+ if (!/^[\w.-]+\/[\w.-]+$/.test(fullName) || fullName.includes("..")) {
1503
+ throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
1504
+ }
1505
+ return fullName;
1506
+ }
1507
+
1508
+ function positive(value: number): number {
1509
+ if (!Number.isSafeInteger(value) || value <= 0) {
1510
+ throw new GithubApiError(400, `Invalid number: ${value}`);
1511
+ }
1512
+ return value;
1513
+ }
1514
+
1515
+ function mapRepo(raw: RawRepo): GithubRepo {
1516
+ return {
1517
+ id: raw.id,
1518
+ fullName: raw.full_name,
1519
+ name: raw.name,
1520
+ owner: raw.owner.login,
1521
+ private: raw.private,
1522
+ defaultBranch: raw.default_branch,
1523
+ cloneUrl: raw.clone_url,
1524
+ description: raw.description,
1525
+ pushedAt: raw.pushed_at,
1526
+ };
1527
+ }
1528
+
1529
+ /**
1530
+ * Git-over-HTTPS credentials for a user access token. GitHub accepts the
1531
+ * token as the password with the fixed `x-access-token` username.
1532
+ */
1533
+ export function gitCredentialsFor(accessToken: string): {
1534
+ username: string;
1535
+ password: string;
1536
+ } {
1537
+ return { username: "x-access-token", password: accessToken };
1538
+ }
1539
+
1540
+ /** True when the remote URL points at github.com (https or ssh form). */
1541
+ export function isGithubRemoteUrl(url: string): boolean {
1542
+ return repoFullNameFromUrl(url) !== null;
1543
+ }
1544
+
1545
+ /**
1546
+ * The repository and number of a pull request's web address
1547
+ * (`https://github.com/owner/repo/pull/12`, anything after the number
1548
+ * ignored), under `webBaseUrl` for GitHub Enterprise. Null otherwise.
1549
+ */
1550
+ export function pullRequestFromUrl({
1551
+ url,
1552
+ webBaseUrl = "https://github.com",
1553
+ }: {
1554
+ url: string;
1555
+ webBaseUrl?: string;
1556
+ }): { fullName: string; number: number } | null {
1557
+ const base = webBaseUrl.replace(/\/+$/, "");
1558
+ const trimmed = url.trim();
1559
+ if (!trimmed.toLowerCase().startsWith(`${base.toLowerCase()}/`)) return null;
1560
+ const match = /^([\w.-]+\/[\w.-]+)\/pull\/(\d+)(?:[/?#].*)?$/.exec(
1561
+ trimmed.slice(base.length + 1),
1562
+ );
1563
+ const number = Number(match?.[2]);
1564
+ return match?.[1] && Number.isSafeInteger(number) && number > 0
1565
+ ? { fullName: match[1], number }
1566
+ : null;
1567
+ }
1568
+
1569
+ /**
1570
+ * Extract `owner/repo` from a github.com clone URL
1571
+ * (`https://github.com/owner/repo.git`, `git@github.com:owner/repo.git`).
1572
+ * Returns null for anything that is not a github.com remote.
1573
+ */
1574
+ export function repoFullNameFromUrl(url: string): string | null {
1575
+ const match =
1576
+ /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:)([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/.exec(
1577
+ url.trim(),
1578
+ );
1579
+ return match?.[1] ?? null;
1580
+ }