@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/LICENSE.txt +202 -0
- package/NOTICE.txt +32 -0
- package/README.md +143 -2
- package/dist/api.d.ts +366 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/app-auth.d.ts +84 -0
- package/dist/app-auth.d.ts.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1371 -0
- package/dist/index.js.map +15 -0
- package/dist/manifest.d.ts +83 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/oauth.d.ts +74 -0
- package/dist/oauth.d.ts.map +1 -0
- package/dist/rest.d.ts +57 -0
- package/dist/rest.d.ts.map +1 -0
- package/dist/types.d.ts +307 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +47 -4
- package/src/api.ts +1580 -0
- package/src/app-auth.ts +412 -0
- package/src/index.ts +74 -0
- package/src/manifest.ts +197 -0
- package/src/oauth.ts +272 -0
- package/src/rest.ts +170 -0
- package/src/types.ts +355 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1371 @@
|
|
|
1
|
+
// src/types.ts
|
|
2
|
+
class GithubAuthError extends Error {
|
|
3
|
+
code;
|
|
4
|
+
constructor(code, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.code = code;
|
|
7
|
+
this.name = "GithubAuthError";
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
class GithubApiError extends Error {
|
|
12
|
+
status;
|
|
13
|
+
constructor(status, message) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.name = "GithubApiError";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
class GithubGraphqlError extends GithubApiError {
|
|
21
|
+
errors;
|
|
22
|
+
constructor(errors, status = 200) {
|
|
23
|
+
super(status, `GitHub GraphQL: ${errors.map((error) => error.message).join("; ") || "unknown error"}`);
|
|
24
|
+
this.errors = errors;
|
|
25
|
+
this.name = "GithubGraphqlError";
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// src/api.ts
|
|
30
|
+
var API_BASE = "https://api.github.com";
|
|
31
|
+
var FAILED_CONCLUSIONS = new Set([
|
|
32
|
+
"failure",
|
|
33
|
+
"timed_out",
|
|
34
|
+
"cancelled",
|
|
35
|
+
"action_required",
|
|
36
|
+
"startup_failure",
|
|
37
|
+
"stale"
|
|
38
|
+
]);
|
|
39
|
+
var THREAD_COMMENT_FIELDS = `databaseId body url createdAt
|
|
40
|
+
author { __typename login ... on User { databaseId } }`;
|
|
41
|
+
var REVIEW_THREADS_QUERY = `query ReviewThreads($owner: String!, $name: String!, $number: Int!, $after: String) {
|
|
42
|
+
repository(owner: $owner, name: $name) {
|
|
43
|
+
pullRequest(number: $number) {
|
|
44
|
+
reviewThreads(first: 100, after: $after) {
|
|
45
|
+
pageInfo { hasNextPage endCursor }
|
|
46
|
+
nodes {
|
|
47
|
+
id isResolved isOutdated path line startLine diffSide
|
|
48
|
+
comments(first: 100) { pageInfo { hasNextPage endCursor } nodes { ${THREAD_COMMENT_FIELDS} } }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}`;
|
|
54
|
+
var THREAD_COMMENTS_QUERY = `query ThreadComments($id: ID!, $after: String) {
|
|
55
|
+
node(id: $id) {
|
|
56
|
+
... on PullRequestReviewThread {
|
|
57
|
+
comments(first: 100, after: $after) { pageInfo { hasNextPage endCursor } nodes { ${THREAD_COMMENT_FIELDS} } }
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}`;
|
|
61
|
+
var REVIEW_THREAD_QUERY = `query ReviewThread($id: ID!) {
|
|
62
|
+
node(id: $id) {
|
|
63
|
+
__typename
|
|
64
|
+
... on PullRequestReviewThread {
|
|
65
|
+
id isResolved
|
|
66
|
+
pullRequest { number repository { nameWithOwner } }
|
|
67
|
+
comments(first: 1) { nodes { ${THREAD_COMMENT_FIELDS} } }
|
|
68
|
+
latest: comments(last: 1) { nodes { ${THREAD_COMMENT_FIELDS} } }
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}`;
|
|
72
|
+
var RESOLVE_REVIEW_THREAD_MUTATION = `mutation ResolveReviewThread($id: ID!) {
|
|
73
|
+
resolveReviewThread(input: { threadId: $id }) { thread { id isResolved } }
|
|
74
|
+
}`;
|
|
75
|
+
var MAX_PAGES = 50;
|
|
76
|
+
function actorOf(user) {
|
|
77
|
+
return user ? { login: user.login, type: user.type ?? "User", id: user.id } : null;
|
|
78
|
+
}
|
|
79
|
+
function graphqlActorOf(actor) {
|
|
80
|
+
if (!actor)
|
|
81
|
+
return null;
|
|
82
|
+
const bot = actor.__typename === "Bot";
|
|
83
|
+
return {
|
|
84
|
+
login: bot && !actor.login.endsWith("[bot]") ? `${actor.login}[bot]` : actor.login,
|
|
85
|
+
type: actor.__typename,
|
|
86
|
+
id: actor.databaseId ?? null
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function threadCommentOf(raw) {
|
|
90
|
+
return {
|
|
91
|
+
id: raw.databaseId,
|
|
92
|
+
author: graphqlActorOf(raw.author),
|
|
93
|
+
body: raw.body,
|
|
94
|
+
url: raw.url,
|
|
95
|
+
createdAt: raw.createdAt
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
function reviewOf(raw) {
|
|
99
|
+
return {
|
|
100
|
+
id: raw.id,
|
|
101
|
+
state: raw.state,
|
|
102
|
+
author: actorOf(raw.user),
|
|
103
|
+
body: raw.body ?? "",
|
|
104
|
+
commitId: raw.commit_id ?? null,
|
|
105
|
+
submittedAt: raw.submitted_at ?? null,
|
|
106
|
+
url: raw.html_url,
|
|
107
|
+
number: trailingNumber(raw.pull_request_url, "pulls")
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function commentOf(raw) {
|
|
111
|
+
return {
|
|
112
|
+
id: raw.id,
|
|
113
|
+
author: actorOf(raw.user),
|
|
114
|
+
body: raw.body ?? "",
|
|
115
|
+
url: raw.html_url,
|
|
116
|
+
number: trailingNumber(raw.pull_request_url, "pulls") ?? trailingNumber(raw.issue_url, "issues"),
|
|
117
|
+
...raw.in_reply_to_id ? { inReplyTo: raw.in_reply_to_id } : {}
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function trailingNumber(url, collection) {
|
|
121
|
+
const match = url ? new RegExp(`/${collection}/(\\d+)$`).exec(url) : null;
|
|
122
|
+
return match?.[1] ? Number(match[1]) : null;
|
|
123
|
+
}
|
|
124
|
+
function pullRequestSummary(pr) {
|
|
125
|
+
return {
|
|
126
|
+
number: pr.number,
|
|
127
|
+
body: pr.body ?? "",
|
|
128
|
+
headSha: pr.head.sha,
|
|
129
|
+
requestedReviewers: pr.requested_reviewers?.map((user) => user.login) ?? [],
|
|
130
|
+
title: pr.title,
|
|
131
|
+
url: pr.html_url,
|
|
132
|
+
author: pr.user?.login ?? "unknown",
|
|
133
|
+
head: pr.head.ref,
|
|
134
|
+
base: pr.base.ref,
|
|
135
|
+
draft: pr.draft,
|
|
136
|
+
updatedAt: pr.updated_at
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function discussionComment(raw) {
|
|
140
|
+
return {
|
|
141
|
+
id: raw.id,
|
|
142
|
+
body: raw.body ?? "",
|
|
143
|
+
author: raw.user,
|
|
144
|
+
createdAt: raw.created_at ?? raw.submitted_at ?? "",
|
|
145
|
+
url: raw.html_url,
|
|
146
|
+
...raw.state ? { state: raw.state } : {},
|
|
147
|
+
...raw.path ? { path: raw.path, line: raw.line } : {},
|
|
148
|
+
...raw.in_reply_to_id ? { replyToId: raw.in_reply_to_id } : {},
|
|
149
|
+
...raw.diff_hunk ? { diffHunk: raw.diff_hunk } : {},
|
|
150
|
+
...raw.side ? { side: raw.side } : {}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
class GithubApi {
|
|
155
|
+
accessToken;
|
|
156
|
+
fetch;
|
|
157
|
+
baseUrl;
|
|
158
|
+
signal;
|
|
159
|
+
constructor(accessToken, opts) {
|
|
160
|
+
this.accessToken = accessToken;
|
|
161
|
+
this.fetch = opts?.fetch ?? fetch;
|
|
162
|
+
this.baseUrl = opts?.baseUrl ?? API_BASE;
|
|
163
|
+
this.signal = opts?.signal;
|
|
164
|
+
}
|
|
165
|
+
async request(path, init) {
|
|
166
|
+
const response = await this.fetch(`${this.baseUrl}${path}`, {
|
|
167
|
+
...this.signal ? { signal: this.signal } : {},
|
|
168
|
+
method: init?.method ?? "GET",
|
|
169
|
+
headers: {
|
|
170
|
+
Accept: "application/vnd.github+json",
|
|
171
|
+
...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {},
|
|
172
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
173
|
+
...init?.body !== undefined ? { "Content-Type": "application/json" } : {}
|
|
174
|
+
},
|
|
175
|
+
...init?.body !== undefined ? { body: JSON.stringify(init.body) } : {}
|
|
176
|
+
});
|
|
177
|
+
if (!response.ok) {
|
|
178
|
+
const body = await response.json().catch(() => ({}));
|
|
179
|
+
throw new GithubApiError(response.status, body.message ?? `GitHub API returned ${response.status}`);
|
|
180
|
+
}
|
|
181
|
+
return await response.json();
|
|
182
|
+
}
|
|
183
|
+
async requestPages(path) {
|
|
184
|
+
const values = [];
|
|
185
|
+
for (let page = 1;; page++) {
|
|
186
|
+
const batch = await this.request(`${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`);
|
|
187
|
+
values.push(...batch);
|
|
188
|
+
if (batch.length < 100)
|
|
189
|
+
return values;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async requestNoContent(path, method) {
|
|
193
|
+
const response = await this.fetch(`${this.baseUrl}${path}`, {
|
|
194
|
+
...this.signal ? { signal: this.signal } : {},
|
|
195
|
+
method,
|
|
196
|
+
headers: {
|
|
197
|
+
Accept: "application/vnd.github+json",
|
|
198
|
+
...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {},
|
|
199
|
+
"X-GitHub-Api-Version": "2022-11-28"
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
if (!response.ok) {
|
|
203
|
+
const body = await response.json().catch(() => ({}));
|
|
204
|
+
throw new GithubApiError(response.status, body.message ?? `GitHub API returned ${response.status}`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
async graphql(query, variables = {}) {
|
|
208
|
+
const response = await this.fetch(githubGraphqlUrl(this.baseUrl), {
|
|
209
|
+
...this.signal ? { signal: this.signal } : {},
|
|
210
|
+
method: "POST",
|
|
211
|
+
redirect: "error",
|
|
212
|
+
headers: {
|
|
213
|
+
Accept: "application/json",
|
|
214
|
+
...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {},
|
|
215
|
+
"Content-Type": "application/json"
|
|
216
|
+
},
|
|
217
|
+
body: JSON.stringify({ query, variables })
|
|
218
|
+
});
|
|
219
|
+
const body = await response.json().catch(() => ({}));
|
|
220
|
+
if (!response.ok) {
|
|
221
|
+
throw new GithubApiError(response.status, body.message ?? `GitHub GraphQL returned ${response.status}`);
|
|
222
|
+
}
|
|
223
|
+
if (body.errors?.length) {
|
|
224
|
+
throw new GithubGraphqlError(body.errors.map((error) => ({
|
|
225
|
+
message: error.message ?? "unknown error",
|
|
226
|
+
...error.type ? { type: error.type } : {}
|
|
227
|
+
})), response.status);
|
|
228
|
+
}
|
|
229
|
+
if (body.data === undefined || body.data === null) {
|
|
230
|
+
throw new GithubApiError(response.status, "GitHub GraphQL returned no data");
|
|
231
|
+
}
|
|
232
|
+
return body.data;
|
|
233
|
+
}
|
|
234
|
+
async reviewThreads(input) {
|
|
235
|
+
const [owner = "", name = ""] = repositoryPath(input.fullName).split("/");
|
|
236
|
+
const threads = [];
|
|
237
|
+
let after = null;
|
|
238
|
+
for (let page = 0;page < MAX_PAGES; page++) {
|
|
239
|
+
const data = await this.graphql(REVIEW_THREADS_QUERY, {
|
|
240
|
+
owner,
|
|
241
|
+
name,
|
|
242
|
+
number: positive(input.number),
|
|
243
|
+
after
|
|
244
|
+
});
|
|
245
|
+
const connection = data.repository?.pullRequest?.reviewThreads;
|
|
246
|
+
if (!connection) {
|
|
247
|
+
throw new GithubApiError(404, `Pull request ${input.fullName}#${input.number} was not found`);
|
|
248
|
+
}
|
|
249
|
+
for (const thread of connection.nodes) {
|
|
250
|
+
const comments = thread.comments.nodes.map(threadCommentOf);
|
|
251
|
+
let more = thread.comments.pageInfo;
|
|
252
|
+
for (let next = 0;more.hasNextPage && next < MAX_PAGES; next++) {
|
|
253
|
+
const rest = await this.graphql(THREAD_COMMENTS_QUERY, {
|
|
254
|
+
id: thread.id,
|
|
255
|
+
after: more.endCursor
|
|
256
|
+
});
|
|
257
|
+
if (!rest.node)
|
|
258
|
+
break;
|
|
259
|
+
comments.push(...rest.node.comments.nodes.map(threadCommentOf));
|
|
260
|
+
more = rest.node.comments.pageInfo;
|
|
261
|
+
}
|
|
262
|
+
threads.push({
|
|
263
|
+
id: thread.id,
|
|
264
|
+
isResolved: thread.isResolved,
|
|
265
|
+
isOutdated: thread.isOutdated,
|
|
266
|
+
path: thread.path,
|
|
267
|
+
line: thread.line,
|
|
268
|
+
startLine: thread.startLine,
|
|
269
|
+
side: thread.diffSide,
|
|
270
|
+
comments
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
if (!connection.pageInfo.hasNextPage)
|
|
274
|
+
return threads;
|
|
275
|
+
after = connection.pageInfo.endCursor;
|
|
276
|
+
}
|
|
277
|
+
throw new GithubApiError(422, `${input.fullName}#${input.number} has more review threads than Work reads`);
|
|
278
|
+
}
|
|
279
|
+
async reviewThread(input) {
|
|
280
|
+
const data = await this.graphql(REVIEW_THREAD_QUERY, { id: input.threadId }).catch((error) => {
|
|
281
|
+
if (error instanceof GithubGraphqlError && error.errors.every((entry) => entry.type === "NOT_FOUND"))
|
|
282
|
+
return null;
|
|
283
|
+
throw error;
|
|
284
|
+
});
|
|
285
|
+
const node = data?.node;
|
|
286
|
+
if (node?.__typename !== "PullRequestReviewThread" || !node.id || !node.pullRequest)
|
|
287
|
+
return null;
|
|
288
|
+
const [first] = node.comments?.nodes ?? [];
|
|
289
|
+
const [last] = node.latest?.nodes ?? [];
|
|
290
|
+
return {
|
|
291
|
+
id: node.id,
|
|
292
|
+
isResolved: node.isResolved === true,
|
|
293
|
+
repository: node.pullRequest.repository.nameWithOwner,
|
|
294
|
+
number: node.pullRequest.number,
|
|
295
|
+
firstComment: first ? threadCommentOf(first) : null,
|
|
296
|
+
lastComment: last ? threadCommentOf(last) : null
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
async resolveReviewThread(input) {
|
|
300
|
+
const data = await this.graphql(RESOLVE_REVIEW_THREAD_MUTATION, { id: input.threadId });
|
|
301
|
+
const thread = data.resolveReviewThread?.thread;
|
|
302
|
+
if (!thread) {
|
|
303
|
+
throw new GithubApiError(422, "GitHub did not resolve the review thread");
|
|
304
|
+
}
|
|
305
|
+
return { id: thread.id, isResolved: thread.isResolved };
|
|
306
|
+
}
|
|
307
|
+
async updatePullRequest(input) {
|
|
308
|
+
const raw = await this.request(`/repos/${repositoryPath(input.fullName)}/pulls/${positive(input.number)}`, { method: "PATCH", body: { body: input.body } });
|
|
309
|
+
return { number: raw.number, url: raw.html_url, body: raw.body ?? "" };
|
|
310
|
+
}
|
|
311
|
+
async listReviews(input) {
|
|
312
|
+
const raw = await this.requestPages(`/repos/${repositoryPath(input.fullName)}/pulls/${positive(input.number)}/reviews`);
|
|
313
|
+
return raw.map(reviewOf);
|
|
314
|
+
}
|
|
315
|
+
async review(input) {
|
|
316
|
+
return reviewOf(await this.request(`/repos/${repositoryPath(input.fullName)}/pulls/${positive(input.number)}/reviews/${positive(input.reviewId)}`));
|
|
317
|
+
}
|
|
318
|
+
async dismissReview(input) {
|
|
319
|
+
return reviewOf(await this.request(`/repos/${repositoryPath(input.fullName)}/pulls/${positive(input.number)}/reviews/${positive(input.reviewId)}/dismissals`, {
|
|
320
|
+
method: "PUT",
|
|
321
|
+
body: { message: input.message, event: "DISMISS" }
|
|
322
|
+
}));
|
|
323
|
+
}
|
|
324
|
+
async reviewComment(input) {
|
|
325
|
+
return commentOf(await this.request(`/repos/${repositoryPath(input.fullName)}/pulls/comments/${positive(input.commentId)}`));
|
|
326
|
+
}
|
|
327
|
+
async issueComment(input) {
|
|
328
|
+
return commentOf(await this.request(`/repos/${repositoryPath(input.fullName)}/issues/comments/${positive(input.commentId)}`));
|
|
329
|
+
}
|
|
330
|
+
async updateIssueComment(input) {
|
|
331
|
+
return commentOf(await this.request(`/repos/${repositoryPath(input.fullName)}/issues/comments/${positive(input.commentId)}`, { method: "PATCH", body: { body: input.body } }));
|
|
332
|
+
}
|
|
333
|
+
async issueKind(input) {
|
|
334
|
+
const raw = await this.request(`/repos/${repositoryPath(input.fullName)}/issues/${positive(input.number)}`);
|
|
335
|
+
return raw.pull_request ? "pull_request" : "issue";
|
|
336
|
+
}
|
|
337
|
+
async issueComments(input) {
|
|
338
|
+
const raw = await this.requestPages(`/repos/${repositoryPath(input.fullName)}/issues/${positive(input.number)}/comments`);
|
|
339
|
+
return raw.map(commentOf);
|
|
340
|
+
}
|
|
341
|
+
async reviewComments(input) {
|
|
342
|
+
const raw = await this.requestPages(`/repos/${repositoryPath(input.fullName)}/pulls/${positive(input.number)}/comments`);
|
|
343
|
+
return raw.map(commentOf);
|
|
344
|
+
}
|
|
345
|
+
async checkRuns(input) {
|
|
346
|
+
if (!/^[0-9a-f]{40}$/.test(input.sha)) {
|
|
347
|
+
throw new GithubApiError(400, `Invalid commit: ${input.sha}`);
|
|
348
|
+
}
|
|
349
|
+
const runs = [];
|
|
350
|
+
const name = input.name ? `&check_name=${encodeURIComponent(input.name)}` : "";
|
|
351
|
+
for (let page = 1;page <= MAX_PAGES; page++) {
|
|
352
|
+
const batch = await this.request(`/repos/${repositoryPath(input.fullName)}/commits/${input.sha}/check-runs?filter=all&per_page=100&page=${page}${name}`);
|
|
353
|
+
runs.push(...batch.check_runs);
|
|
354
|
+
if (batch.check_runs.length < 100)
|
|
355
|
+
break;
|
|
356
|
+
}
|
|
357
|
+
return runs.map((run) => ({
|
|
358
|
+
id: run.id,
|
|
359
|
+
externalId: run.external_id ?? null,
|
|
360
|
+
app: run.app?.slug ?? null,
|
|
361
|
+
status: run.status,
|
|
362
|
+
conclusion: run.conclusion,
|
|
363
|
+
url: run.html_url
|
|
364
|
+
}));
|
|
365
|
+
}
|
|
366
|
+
async deleteIssueComment(input) {
|
|
367
|
+
await this.requestNoContent(`/repos/${repositoryPath(input.fullName)}/issues/comments/${positive(input.commentId)}`, "DELETE");
|
|
368
|
+
}
|
|
369
|
+
async getUser() {
|
|
370
|
+
const raw = await this.request("/user");
|
|
371
|
+
return {
|
|
372
|
+
login: raw.login,
|
|
373
|
+
id: raw.id,
|
|
374
|
+
avatarUrl: raw.avatar_url,
|
|
375
|
+
name: raw.name
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
async getRepo(fullName) {
|
|
379
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) {
|
|
380
|
+
throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
|
|
381
|
+
}
|
|
382
|
+
return mapRepo(await this.request(`/repos/${fullName}`));
|
|
383
|
+
}
|
|
384
|
+
async createRepo(input) {
|
|
385
|
+
if (!/^[\w.-]+$/.test(input.name)) {
|
|
386
|
+
throw new GithubApiError(400, `Invalid repository name: ${input.name}`);
|
|
387
|
+
}
|
|
388
|
+
if (input.organization && !/^[\w.-]+$/.test(input.organization)) {
|
|
389
|
+
throw new GithubApiError(400, `Invalid organization: ${input.organization}`);
|
|
390
|
+
}
|
|
391
|
+
return mapRepo(await this.request(input.organization ? `/orgs/${input.organization}/repos` : "/user/repos", {
|
|
392
|
+
method: "POST",
|
|
393
|
+
body: {
|
|
394
|
+
name: input.name,
|
|
395
|
+
private: input.private,
|
|
396
|
+
auto_init: false,
|
|
397
|
+
...input.description !== undefined ? { description: input.description } : {}
|
|
398
|
+
}
|
|
399
|
+
}));
|
|
400
|
+
}
|
|
401
|
+
async createPullRequest(fullName, input) {
|
|
402
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) {
|
|
403
|
+
throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
|
|
404
|
+
}
|
|
405
|
+
const raw = await this.request(`/repos/${fullName}/pulls`, {
|
|
406
|
+
method: "POST",
|
|
407
|
+
body: {
|
|
408
|
+
title: input.title,
|
|
409
|
+
head: input.head,
|
|
410
|
+
base: input.base,
|
|
411
|
+
...input.body !== undefined ? { body: input.body } : {}
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
return { url: raw.html_url, number: raw.number };
|
|
415
|
+
}
|
|
416
|
+
async pullRequestDiscussion(input) {
|
|
417
|
+
const base = `/repos/${input.fullName}`;
|
|
418
|
+
const pull = await this.request(`${base}/pulls/${input.number}`);
|
|
419
|
+
const [reviews, comments, inlineComments, checks] = await Promise.all([
|
|
420
|
+
this.requestPages(`${base}/pulls/${input.number}/reviews`),
|
|
421
|
+
this.requestPages(`${base}/issues/${input.number}/comments`),
|
|
422
|
+
this.requestPages(`${base}/pulls/${input.number}/comments`),
|
|
423
|
+
this.request(`${base}/commits/${pull.head.sha}/check-runs?per_page=100`)
|
|
424
|
+
]);
|
|
425
|
+
return {
|
|
426
|
+
state: pull.merged ? "MERGED" : pull.state.toUpperCase(),
|
|
427
|
+
reviewDecision: null,
|
|
428
|
+
assignees: pull.assignees.map(({ login }) => ({ login })),
|
|
429
|
+
reviewRequests: pull.requested_reviewers.map(({ login }) => ({ login })),
|
|
430
|
+
reviews: reviews.map(discussionComment),
|
|
431
|
+
comments: comments.map(discussionComment),
|
|
432
|
+
inlineComments: inlineComments.map(discussionComment),
|
|
433
|
+
inlineCommentsUnavailable: false,
|
|
434
|
+
statusCheckRollup: checks.check_runs.map((check) => ({
|
|
435
|
+
name: check.name,
|
|
436
|
+
status: check.status.toUpperCase(),
|
|
437
|
+
conclusion: check.conclusion?.toUpperCase() ?? null,
|
|
438
|
+
detailsUrl: check.html_url
|
|
439
|
+
}))
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
async commentOnPullRequest(input) {
|
|
443
|
+
const endpoint = input.replyTo ? `/repos/${input.fullName}/pulls/${input.number}/comments/${input.replyTo}/replies` : `/repos/${input.fullName}/issues/${input.number}/comments`;
|
|
444
|
+
return discussionComment(await this.request(endpoint, {
|
|
445
|
+
method: "POST",
|
|
446
|
+
body: { body: input.body }
|
|
447
|
+
}));
|
|
448
|
+
}
|
|
449
|
+
async createReview(input) {
|
|
450
|
+
const raw = await this.request(`/repos/${repositoryPath(input.fullName)}/pulls/${positive(input.number)}/reviews`, {
|
|
451
|
+
method: "POST",
|
|
452
|
+
body: {
|
|
453
|
+
...input.event ? { event: input.event } : {},
|
|
454
|
+
...input.body !== undefined ? { body: input.body } : {},
|
|
455
|
+
...input.commitId ? { commit_id: input.commitId } : {},
|
|
456
|
+
...input.comments?.length ? {
|
|
457
|
+
comments: input.comments.map((comment) => ({
|
|
458
|
+
path: comment.path,
|
|
459
|
+
body: comment.body,
|
|
460
|
+
...comment.line !== undefined ? { line: comment.line } : {},
|
|
461
|
+
...comment.side ? { side: comment.side } : {},
|
|
462
|
+
...comment.startLine !== undefined ? { start_line: comment.startLine } : {},
|
|
463
|
+
...comment.startSide ? { start_side: comment.startSide } : {}
|
|
464
|
+
}))
|
|
465
|
+
} : {}
|
|
466
|
+
}
|
|
467
|
+
});
|
|
468
|
+
return { id: raw.id, url: raw.html_url, state: raw.state };
|
|
469
|
+
}
|
|
470
|
+
async createCheckRun(input) {
|
|
471
|
+
return mapCheckRun(await this.request(`/repos/${repositoryPath(input.fullName)}/check-runs`, {
|
|
472
|
+
method: "POST",
|
|
473
|
+
body: {
|
|
474
|
+
name: input.name,
|
|
475
|
+
head_sha: input.headSha,
|
|
476
|
+
...checkRunBody(input)
|
|
477
|
+
}
|
|
478
|
+
}));
|
|
479
|
+
}
|
|
480
|
+
async updateCheckRun(input) {
|
|
481
|
+
return mapCheckRun(await this.request(`/repos/${repositoryPath(input.fullName)}/check-runs/${positive(input.checkRunId)}`, {
|
|
482
|
+
method: "PATCH",
|
|
483
|
+
body: {
|
|
484
|
+
...input.name ? { name: input.name } : {},
|
|
485
|
+
...checkRunBody(input)
|
|
486
|
+
}
|
|
487
|
+
}));
|
|
488
|
+
}
|
|
489
|
+
async reviewPullRequest(input) {
|
|
490
|
+
const current = await this.request(`/repos/${input.fullName}/pulls/${input.number}`);
|
|
491
|
+
if (current.state !== "open" || current.head.sha !== input.headSha)
|
|
492
|
+
throw new Error("This proposal changed since you opened it. Refresh and review the latest changes.");
|
|
493
|
+
await this.request(`/repos/${input.fullName}/pulls/${input.number}/reviews`, {
|
|
494
|
+
method: "POST",
|
|
495
|
+
body: {
|
|
496
|
+
commit_id: input.headSha,
|
|
497
|
+
event: input.decision,
|
|
498
|
+
body: input.body
|
|
499
|
+
}
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
async mergePullRequest(input) {
|
|
503
|
+
const result = await this.request(`/repos/${input.fullName}/pulls/${input.number}/merge`, {
|
|
504
|
+
method: "PUT",
|
|
505
|
+
body: { sha: input.headSha, merge_method: "squash" }
|
|
506
|
+
});
|
|
507
|
+
if (!result.merged)
|
|
508
|
+
throw new Error(result.message || "The proposal could not be applied");
|
|
509
|
+
return { sha: result.sha };
|
|
510
|
+
}
|
|
511
|
+
async requestedReviewNumbers(fullName) {
|
|
512
|
+
const numbers = new Set;
|
|
513
|
+
const query = encodeURIComponent(`repo:${fullName} is:pr is:open review-requested:@me`);
|
|
514
|
+
for (let page = 1;page <= 10; page++) {
|
|
515
|
+
const result = await this.request(`/search/issues?q=${query}&per_page=100&page=${page}`);
|
|
516
|
+
if (result.incomplete_results || result.total_count > 1000)
|
|
517
|
+
throw new Error("Review request search is incomplete");
|
|
518
|
+
for (const item of result.items)
|
|
519
|
+
numbers.add(item.number);
|
|
520
|
+
if (result.items.length < 100 || numbers.size >= result.total_count)
|
|
521
|
+
return numbers;
|
|
522
|
+
}
|
|
523
|
+
throw new Error("Review request search is incomplete");
|
|
524
|
+
}
|
|
525
|
+
async listPullRequests(fullName) {
|
|
526
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) {
|
|
527
|
+
throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
|
|
528
|
+
}
|
|
529
|
+
const raw = await this.requestPages(`/repos/${fullName}/pulls?state=open&sort=updated&direction=desc`);
|
|
530
|
+
const requested = raw.length ? await this.requestedReviewNumbers(fullName).catch(() => {
|
|
531
|
+
return;
|
|
532
|
+
}) : new Set;
|
|
533
|
+
return raw.map((pr) => ({
|
|
534
|
+
...requested ? { reviewRequestedForViewer: requested.has(pr.number) } : { reviewRequestsUnavailable: true },
|
|
535
|
+
...pullRequestSummary(pr)
|
|
536
|
+
}));
|
|
537
|
+
}
|
|
538
|
+
async pullRequest(input) {
|
|
539
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(input.fullName) || !Number.isSafeInteger(input.number) || input.number <= 0)
|
|
540
|
+
throw new GithubApiError(400, "Invalid pull request");
|
|
541
|
+
return pullRequestSummary(await this.request(`/repos/${input.fullName}/pulls/${input.number}`));
|
|
542
|
+
}
|
|
543
|
+
async pullRequestStatus(input) {
|
|
544
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(input.fullName) || !Number.isSafeInteger(input.number) || input.number <= 0)
|
|
545
|
+
throw new GithubApiError(400, "Invalid pull request");
|
|
546
|
+
const pr = await this.request(`/repos/${input.fullName}/pulls/${input.number}`);
|
|
547
|
+
const checks = input.includeChecks !== false && pr.state === "open" && pr.head.sha ? await this.checksOf(input.fullName, pr.head.sha).catch(() => {
|
|
548
|
+
return;
|
|
549
|
+
}) : undefined;
|
|
550
|
+
return {
|
|
551
|
+
number: pr.number,
|
|
552
|
+
title: pr.title,
|
|
553
|
+
url: pr.html_url,
|
|
554
|
+
repository: input.fullName,
|
|
555
|
+
author: pr.user?.login ?? "unknown",
|
|
556
|
+
head: pr.head.ref,
|
|
557
|
+
base: pr.base.ref,
|
|
558
|
+
state: pr.merged || pr.merged_at ? "merged" : pr.state === "closed" ? "closed" : pr.draft ? "draft" : "open",
|
|
559
|
+
additions: pr.additions ?? 0,
|
|
560
|
+
deletions: pr.deletions ?? 0,
|
|
561
|
+
changedFiles: pr.changed_files ?? 0,
|
|
562
|
+
comments: (pr.comments ?? 0) + (pr.review_comments ?? 0),
|
|
563
|
+
...checks ? { checks } : {},
|
|
564
|
+
updatedAt: pr.updated_at
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
async checksOf(fullName, sha) {
|
|
568
|
+
const [runs, status] = await Promise.all([
|
|
569
|
+
this.request(`/repos/${fullName}/commits/${sha}/check-runs?per_page=100`),
|
|
570
|
+
this.request(`/repos/${fullName}/commits/${sha}/status`).catch(() => {
|
|
571
|
+
return;
|
|
572
|
+
})
|
|
573
|
+
]);
|
|
574
|
+
const counts = { passed: 0, failed: 0, pending: 0 };
|
|
575
|
+
for (const run of runs.check_runs) {
|
|
576
|
+
if (run.status !== "completed")
|
|
577
|
+
counts.pending += 1;
|
|
578
|
+
else if (run.conclusion && FAILED_CONCLUSIONS.has(run.conclusion))
|
|
579
|
+
counts.failed += 1;
|
|
580
|
+
else
|
|
581
|
+
counts.passed += 1;
|
|
582
|
+
}
|
|
583
|
+
for (const entry of status?.statuses ?? []) {
|
|
584
|
+
if (entry.state === "pending")
|
|
585
|
+
counts.pending += 1;
|
|
586
|
+
else if (entry.state === "success")
|
|
587
|
+
counts.passed += 1;
|
|
588
|
+
else
|
|
589
|
+
counts.failed += 1;
|
|
590
|
+
}
|
|
591
|
+
if (counts.passed + counts.failed + counts.pending === 0)
|
|
592
|
+
return;
|
|
593
|
+
return {
|
|
594
|
+
state: counts.failed > 0 ? "failure" : counts.pending > 0 ? "pending" : "success",
|
|
595
|
+
...counts
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
async pullRequestFiles(fullName, number) {
|
|
599
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) {
|
|
600
|
+
throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
|
|
601
|
+
}
|
|
602
|
+
const raw = await this.requestPages(`/repos/${fullName}/pulls/${number}/files`);
|
|
603
|
+
return raw.map((file) => ({
|
|
604
|
+
path: file.filename,
|
|
605
|
+
status: file.status,
|
|
606
|
+
additions: file.additions,
|
|
607
|
+
deletions: file.deletions,
|
|
608
|
+
patch: file.patch ?? null,
|
|
609
|
+
...file.previous_filename ? { previousPath: file.previous_filename } : {}
|
|
610
|
+
}));
|
|
611
|
+
}
|
|
612
|
+
async listRepositoryEvents(fullName) {
|
|
613
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) {
|
|
614
|
+
throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
|
|
615
|
+
}
|
|
616
|
+
const raw = await this.request(`/repos/${fullName}/events?per_page=100`);
|
|
617
|
+
return raw.map((event) => ({
|
|
618
|
+
id: event.id,
|
|
619
|
+
type: event.type,
|
|
620
|
+
actor: event.actor?.login ?? null,
|
|
621
|
+
createdAt: event.created_at,
|
|
622
|
+
payload: event.payload
|
|
623
|
+
}));
|
|
624
|
+
}
|
|
625
|
+
async listRepositoryWatchEvents(fullName) {
|
|
626
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(fullName)) {
|
|
627
|
+
throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
|
|
628
|
+
}
|
|
629
|
+
const [events, pulls, workflowRuns] = await Promise.all([
|
|
630
|
+
this.listRepositoryEvents(fullName),
|
|
631
|
+
this.optionalRequest(`/repos/${fullName}/pulls?state=all&sort=updated&direction=desc&per_page=25`, []),
|
|
632
|
+
this.optionalRequest(`/repos/${fullName}/actions/runs?per_page=100`, { workflow_runs: [] })
|
|
633
|
+
]);
|
|
634
|
+
const recentPulls = pulls.slice(0, 3);
|
|
635
|
+
const pullDetails = await Promise.all(recentPulls.map(async (pull) => {
|
|
636
|
+
const [reviews, runs, suites] = await Promise.all([
|
|
637
|
+
this.optionalRequest(`/repos/${fullName}/pulls/${pull.number}/reviews?per_page=100`, []),
|
|
638
|
+
this.optionalRequest(`/repos/${fullName}/commits/${pull.head.sha}/check-runs?filter=all&per_page=100`, { check_runs: [] }),
|
|
639
|
+
this.optionalRequest(`/repos/${fullName}/commits/${pull.head.sha}/check-suites?per_page=100`, { check_suites: [] })
|
|
640
|
+
]);
|
|
641
|
+
return {
|
|
642
|
+
pull,
|
|
643
|
+
reviews,
|
|
644
|
+
runs: runs.check_runs,
|
|
645
|
+
suites: suites.check_suites
|
|
646
|
+
};
|
|
647
|
+
}));
|
|
648
|
+
const snapshots = [
|
|
649
|
+
...pulls.map((pull) => ({
|
|
650
|
+
id: `pull_request:${pull.id}:${pull.updated_at}`,
|
|
651
|
+
type: "PullRequestEvent",
|
|
652
|
+
actor: pull.user?.login ?? null,
|
|
653
|
+
createdAt: pull.updated_at,
|
|
654
|
+
payload: { action: "updated", number: pull.number, pull_request: pull }
|
|
655
|
+
})),
|
|
656
|
+
...workflowRuns.workflow_runs.map((run) => ({
|
|
657
|
+
id: `workflow_run:${run.id}:${run.run_attempt}:${run.updated_at}:${run.status}:${run.conclusion ?? ""}`,
|
|
658
|
+
type: "WorkflowRunEvent",
|
|
659
|
+
actor: run.actor?.login ?? null,
|
|
660
|
+
createdAt: run.updated_at,
|
|
661
|
+
payload: { action: run.status, workflow_run: run }
|
|
662
|
+
})),
|
|
663
|
+
...pullDetails.flatMap(({ pull, reviews, runs, suites }) => [
|
|
664
|
+
...reviews.map((review) => ({
|
|
665
|
+
id: `pull_request_review:${review.id}:${review.submitted_at}:${review.state}`,
|
|
666
|
+
type: "PullRequestReviewEvent",
|
|
667
|
+
actor: review.user?.login ?? null,
|
|
668
|
+
createdAt: review.submitted_at,
|
|
669
|
+
payload: { action: "submitted", review, pull_request: pull }
|
|
670
|
+
})),
|
|
671
|
+
...runs.map((run) => ({
|
|
672
|
+
id: `check_run:${run.id}:${run.updated_at}:${run.status}:${run.conclusion ?? ""}`,
|
|
673
|
+
type: "CheckRunEvent",
|
|
674
|
+
actor: run.app?.slug ?? null,
|
|
675
|
+
createdAt: run.updated_at,
|
|
676
|
+
payload: { action: run.status, check_run: run, pull_request: pull }
|
|
677
|
+
})),
|
|
678
|
+
...suites.map((suite) => ({
|
|
679
|
+
id: `check_suite:${suite.id}:${suite.updated_at}:${suite.status}:${suite.conclusion ?? ""}`,
|
|
680
|
+
type: "CheckSuiteEvent",
|
|
681
|
+
actor: suite.app?.slug ?? null,
|
|
682
|
+
createdAt: suite.updated_at,
|
|
683
|
+
payload: {
|
|
684
|
+
action: suite.status,
|
|
685
|
+
check_suite: suite,
|
|
686
|
+
pull_request: pull
|
|
687
|
+
}
|
|
688
|
+
}))
|
|
689
|
+
])
|
|
690
|
+
];
|
|
691
|
+
return [...events, ...snapshots].filter((event, index, all) => all.findIndex((candidate) => candidate.id === event.id) === index).sort((left, right) => right.createdAt.localeCompare(left.createdAt));
|
|
692
|
+
}
|
|
693
|
+
async optionalRequest(path, fallback) {
|
|
694
|
+
try {
|
|
695
|
+
return await this.request(path);
|
|
696
|
+
} catch (error) {
|
|
697
|
+
if (error instanceof GithubApiError && (error.status === 403 || error.status === 404)) {
|
|
698
|
+
return fallback;
|
|
699
|
+
}
|
|
700
|
+
throw error;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
async listAccessibleRepos(opts) {
|
|
704
|
+
const perPage = opts?.perPage ?? 100;
|
|
705
|
+
const repos = [];
|
|
706
|
+
let page = 1;
|
|
707
|
+
for (;; ) {
|
|
708
|
+
const result = await this.request(`/user/repos?per_page=${perPage}&page=${page}&sort=pushed&direction=desc`);
|
|
709
|
+
repos.push(...result.map(mapRepo));
|
|
710
|
+
if (result.length < perPage)
|
|
711
|
+
break;
|
|
712
|
+
page += 1;
|
|
713
|
+
}
|
|
714
|
+
return repos.sort((a, b) => (b.pushedAt ?? "").localeCompare(a.pushedAt ?? ""));
|
|
715
|
+
}
|
|
716
|
+
async listInstallationRepos() {
|
|
717
|
+
const repos = [];
|
|
718
|
+
for (let page = 1;; page += 1) {
|
|
719
|
+
const result = await this.request(`/installation/repositories?per_page=100&page=${page}`);
|
|
720
|
+
repos.push(...result.repositories.map(mapRepo));
|
|
721
|
+
if (result.repositories.length < 100)
|
|
722
|
+
break;
|
|
723
|
+
}
|
|
724
|
+
return repos.sort((a, b) => (b.pushedAt ?? "").localeCompare(a.pushedAt ?? ""));
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
function mapCheckRun(raw) {
|
|
728
|
+
return {
|
|
729
|
+
id: raw.id,
|
|
730
|
+
url: raw.html_url,
|
|
731
|
+
status: raw.status,
|
|
732
|
+
conclusion: raw.conclusion
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
function checkRunBody(fields) {
|
|
736
|
+
return {
|
|
737
|
+
...fields.status ? { status: fields.status } : {},
|
|
738
|
+
...fields.conclusion ? { conclusion: fields.conclusion } : {},
|
|
739
|
+
...fields.detailsUrl ? { details_url: fields.detailsUrl } : {},
|
|
740
|
+
...fields.externalId ? { external_id: fields.externalId } : {},
|
|
741
|
+
...fields.startedAt ? { started_at: fields.startedAt } : {},
|
|
742
|
+
...fields.completedAt ? { completed_at: fields.completedAt } : {},
|
|
743
|
+
...fields.output ? {
|
|
744
|
+
output: {
|
|
745
|
+
title: fields.output.title,
|
|
746
|
+
summary: fields.output.summary,
|
|
747
|
+
...fields.output.text ? { text: fields.output.text } : {},
|
|
748
|
+
...fields.output.annotations?.length ? {
|
|
749
|
+
annotations: fields.output.annotations.map((annotation) => ({
|
|
750
|
+
path: annotation.path,
|
|
751
|
+
start_line: annotation.startLine,
|
|
752
|
+
end_line: annotation.endLine,
|
|
753
|
+
annotation_level: annotation.level,
|
|
754
|
+
message: annotation.message,
|
|
755
|
+
...annotation.title ? { title: annotation.title } : {}
|
|
756
|
+
}))
|
|
757
|
+
} : {}
|
|
758
|
+
}
|
|
759
|
+
} : {}
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
function githubGraphqlUrl(apiBaseUrl = API_BASE) {
|
|
763
|
+
const url = new URL(apiBaseUrl);
|
|
764
|
+
const path = url.pathname.replace(/\/+$/, "");
|
|
765
|
+
url.pathname = /\/api\/v3$/.test(path) ? `${path.slice(0, -"/v3".length)}/graphql` : `${path}/graphql`;
|
|
766
|
+
url.search = "";
|
|
767
|
+
url.hash = "";
|
|
768
|
+
return url.toString();
|
|
769
|
+
}
|
|
770
|
+
function repositoryPath(fullName) {
|
|
771
|
+
if (!/^[\w.-]+\/[\w.-]+$/.test(fullName) || fullName.includes("..")) {
|
|
772
|
+
throw new GithubApiError(400, `Invalid repository name: ${fullName}`);
|
|
773
|
+
}
|
|
774
|
+
return fullName;
|
|
775
|
+
}
|
|
776
|
+
function positive(value) {
|
|
777
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
778
|
+
throw new GithubApiError(400, `Invalid number: ${value}`);
|
|
779
|
+
}
|
|
780
|
+
return value;
|
|
781
|
+
}
|
|
782
|
+
function mapRepo(raw) {
|
|
783
|
+
return {
|
|
784
|
+
id: raw.id,
|
|
785
|
+
fullName: raw.full_name,
|
|
786
|
+
name: raw.name,
|
|
787
|
+
owner: raw.owner.login,
|
|
788
|
+
private: raw.private,
|
|
789
|
+
defaultBranch: raw.default_branch,
|
|
790
|
+
cloneUrl: raw.clone_url,
|
|
791
|
+
description: raw.description,
|
|
792
|
+
pushedAt: raw.pushed_at
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
function gitCredentialsFor(accessToken) {
|
|
796
|
+
return { username: "x-access-token", password: accessToken };
|
|
797
|
+
}
|
|
798
|
+
function isGithubRemoteUrl(url) {
|
|
799
|
+
return repoFullNameFromUrl(url) !== null;
|
|
800
|
+
}
|
|
801
|
+
function pullRequestFromUrl({
|
|
802
|
+
url,
|
|
803
|
+
webBaseUrl = "https://github.com"
|
|
804
|
+
}) {
|
|
805
|
+
const base = webBaseUrl.replace(/\/+$/, "");
|
|
806
|
+
const trimmed = url.trim();
|
|
807
|
+
if (!trimmed.toLowerCase().startsWith(`${base.toLowerCase()}/`))
|
|
808
|
+
return null;
|
|
809
|
+
const match = /^([\w.-]+\/[\w.-]+)\/pull\/(\d+)(?:[/?#].*)?$/.exec(trimmed.slice(base.length + 1));
|
|
810
|
+
const number = Number(match?.[2]);
|
|
811
|
+
return match?.[1] && Number.isSafeInteger(number) && number > 0 ? { fullName: match[1], number } : null;
|
|
812
|
+
}
|
|
813
|
+
function repoFullNameFromUrl(url) {
|
|
814
|
+
const match = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:)([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/.exec(url.trim());
|
|
815
|
+
return match?.[1] ?? null;
|
|
816
|
+
}
|
|
817
|
+
// src/app-auth.ts
|
|
818
|
+
import {
|
|
819
|
+
createHash,
|
|
820
|
+
createPrivateKey,
|
|
821
|
+
sign
|
|
822
|
+
} from "node:crypto";
|
|
823
|
+
var API_BASE2 = "https://api.github.com";
|
|
824
|
+
var JWT_LIFETIME_SECONDS = 9 * 60;
|
|
825
|
+
var JWT_BACKDATE_SECONDS = 60;
|
|
826
|
+
var DEFAULT_REFRESH_SKEW_MS = 5 * 60000;
|
|
827
|
+
var DEFAULT_TIMEOUT_MS = 30000;
|
|
828
|
+
function parseGithubAppPrivateKey(privateKey) {
|
|
829
|
+
let key;
|
|
830
|
+
try {
|
|
831
|
+
key = createPrivateKey(privateKey.trim());
|
|
832
|
+
} catch {
|
|
833
|
+
throw new GithubAuthError("invalid_private_key", "The GitHub App private key is not a readable PEM key");
|
|
834
|
+
}
|
|
835
|
+
if (key.asymmetricKeyType !== "rsa") {
|
|
836
|
+
throw new GithubAuthError("invalid_private_key", "A GitHub App private key must be an RSA key");
|
|
837
|
+
}
|
|
838
|
+
return key;
|
|
839
|
+
}
|
|
840
|
+
function createGithubAppJwt(args) {
|
|
841
|
+
const seconds = Math.floor((args.now ?? Date.now()) / 1000);
|
|
842
|
+
const appId = args.appId.trim();
|
|
843
|
+
if (!appId) {
|
|
844
|
+
throw new GithubAuthError("invalid_app_id", "A GitHub App ID is required");
|
|
845
|
+
}
|
|
846
|
+
const header = { alg: "RS256", typ: "JWT" };
|
|
847
|
+
const payload = {
|
|
848
|
+
iat: seconds - JWT_BACKDATE_SECONDS,
|
|
849
|
+
exp: seconds + JWT_LIFETIME_SECONDS,
|
|
850
|
+
iss: /^\d+$/.test(appId) ? Number(appId) : appId
|
|
851
|
+
};
|
|
852
|
+
const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(payload))}`;
|
|
853
|
+
const signature = sign("sha256", Buffer.from(signingInput), parseGithubAppPrivateKey(args.privateKey));
|
|
854
|
+
return `${signingInput}.${signature.toString("base64url")}`;
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
class GithubAppAuth {
|
|
858
|
+
fetch;
|
|
859
|
+
apiBaseUrl;
|
|
860
|
+
now;
|
|
861
|
+
refreshSkewMs;
|
|
862
|
+
timeoutMs;
|
|
863
|
+
tokens = new Map;
|
|
864
|
+
constructor(options = {}) {
|
|
865
|
+
this.fetch = options.fetch ?? fetch;
|
|
866
|
+
this.apiBaseUrl = (options.apiBaseUrl ?? API_BASE2).replace(/\/+$/, "");
|
|
867
|
+
this.now = options.now ?? Date.now;
|
|
868
|
+
this.refreshSkewMs = options.refreshSkewMs ?? DEFAULT_REFRESH_SKEW_MS;
|
|
869
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
870
|
+
}
|
|
871
|
+
appJwt(args) {
|
|
872
|
+
return createGithubAppJwt({ ...args.app, now: this.now() });
|
|
873
|
+
}
|
|
874
|
+
async installationToken(args) {
|
|
875
|
+
requireInstallationId(args.installationId);
|
|
876
|
+
const repositories = [
|
|
877
|
+
...new Set((args.repositories ?? []).map(repositoryName))
|
|
878
|
+
].sort();
|
|
879
|
+
const permissions = Object.entries(args.permissions ?? {}).sort(([left], [right]) => left.localeCompare(right));
|
|
880
|
+
const appFingerprint = fingerprint(args.app);
|
|
881
|
+
const key = JSON.stringify([
|
|
882
|
+
appFingerprint,
|
|
883
|
+
args.installationId,
|
|
884
|
+
repositories,
|
|
885
|
+
permissions
|
|
886
|
+
]);
|
|
887
|
+
const now = this.now();
|
|
888
|
+
const cached = this.tokens.get(key);
|
|
889
|
+
if (cached && (cached.expiresAt === undefined || cached.expiresAt - this.refreshSkewMs > now)) {
|
|
890
|
+
return cached.pending;
|
|
891
|
+
}
|
|
892
|
+
this.sweep(now);
|
|
893
|
+
const entry = {
|
|
894
|
+
appFingerprint,
|
|
895
|
+
pending: this.mint({
|
|
896
|
+
app: args.app,
|
|
897
|
+
installationId: args.installationId,
|
|
898
|
+
repositories,
|
|
899
|
+
permissions: Object.fromEntries(permissions)
|
|
900
|
+
})
|
|
901
|
+
};
|
|
902
|
+
this.tokens.set(key, entry);
|
|
903
|
+
try {
|
|
904
|
+
const token = await entry.pending;
|
|
905
|
+
entry.expiresAt = token.expiresAt;
|
|
906
|
+
return token;
|
|
907
|
+
} catch (error) {
|
|
908
|
+
if (this.tokens.get(key) === entry)
|
|
909
|
+
this.tokens.delete(key);
|
|
910
|
+
throw error;
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
async listInstallations(args) {
|
|
914
|
+
const installations = [];
|
|
915
|
+
for (let page = 1;; page++) {
|
|
916
|
+
const batch = await this.appRequest({
|
|
917
|
+
app: args.app,
|
|
918
|
+
path: `/app/installations?per_page=100&page=${page}`
|
|
919
|
+
});
|
|
920
|
+
installations.push(...batch.map(mapInstallation));
|
|
921
|
+
if (batch.length < 100)
|
|
922
|
+
return installations;
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
async installation(args) {
|
|
926
|
+
requireInstallationId(args.installationId);
|
|
927
|
+
return mapInstallation(await this.appRequest({
|
|
928
|
+
app: args.app,
|
|
929
|
+
path: `/app/installations/${args.installationId}`
|
|
930
|
+
}));
|
|
931
|
+
}
|
|
932
|
+
async findInstallation(args) {
|
|
933
|
+
const owner = segment(args.owner, "owner");
|
|
934
|
+
const paths = args.repository ? [
|
|
935
|
+
`/repos/${owner}/${segment(repositoryName(args.repository), "repository")}/installation`
|
|
936
|
+
] : [`/orgs/${owner}/installation`, `/users/${owner}/installation`];
|
|
937
|
+
for (const path of paths) {
|
|
938
|
+
try {
|
|
939
|
+
return mapInstallation(await this.appRequest({ app: args.app, path }));
|
|
940
|
+
} catch (error) {
|
|
941
|
+
if (!(error instanceof GithubApiError && error.status === 404)) {
|
|
942
|
+
throw error;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
return null;
|
|
947
|
+
}
|
|
948
|
+
async revokeCachedTokens(args) {
|
|
949
|
+
const appFingerprint = fingerprint(args.app);
|
|
950
|
+
const entries = [...this.tokens].filter(([, entry]) => entry.appFingerprint === appFingerprint);
|
|
951
|
+
for (const [key] of entries)
|
|
952
|
+
this.tokens.delete(key);
|
|
953
|
+
await Promise.all(entries.map(async ([, entry]) => {
|
|
954
|
+
const token = await entry.pending.catch(() => null);
|
|
955
|
+
if (!token || token.expiresAt <= this.now())
|
|
956
|
+
return;
|
|
957
|
+
await this.fetch(`${this.apiBaseUrl}/installation/token`, {
|
|
958
|
+
method: "DELETE",
|
|
959
|
+
headers: headers(token.token),
|
|
960
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
961
|
+
}).catch(() => {
|
|
962
|
+
return;
|
|
963
|
+
});
|
|
964
|
+
}));
|
|
965
|
+
}
|
|
966
|
+
async mint(args) {
|
|
967
|
+
const raw = await this.appRequest({
|
|
968
|
+
app: args.app,
|
|
969
|
+
path: `/app/installations/${args.installationId}/access_tokens`,
|
|
970
|
+
method: "POST",
|
|
971
|
+
body: {
|
|
972
|
+
...args.repositories.length ? { repositories: args.repositories } : {},
|
|
973
|
+
...Object.keys(args.permissions).length ? { permissions: args.permissions } : {}
|
|
974
|
+
}
|
|
975
|
+
});
|
|
976
|
+
const expiresAt = Date.parse(raw.expires_at);
|
|
977
|
+
if (!raw.token || Number.isNaN(expiresAt)) {
|
|
978
|
+
throw new GithubAuthError("invalid_installation_token", "GitHub returned an incomplete installation token");
|
|
979
|
+
}
|
|
980
|
+
return {
|
|
981
|
+
token: raw.token,
|
|
982
|
+
expiresAt,
|
|
983
|
+
permissions: raw.permissions ?? {},
|
|
984
|
+
repositorySelection: raw.repository_selection === "selected" ? "selected" : "all",
|
|
985
|
+
...raw.repositories ? { repositories: raw.repositories.map((repo) => repo.full_name) } : {}
|
|
986
|
+
};
|
|
987
|
+
}
|
|
988
|
+
async appRequest(args) {
|
|
989
|
+
const response = await this.fetch(`${this.apiBaseUrl}${args.path}`, {
|
|
990
|
+
method: args.method ?? "GET",
|
|
991
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
992
|
+
headers: {
|
|
993
|
+
...headers(this.appJwt({ app: args.app })),
|
|
994
|
+
...args.body !== undefined ? { "Content-Type": "application/json" } : {}
|
|
995
|
+
},
|
|
996
|
+
...args.body !== undefined ? { body: JSON.stringify(args.body) } : {}
|
|
997
|
+
});
|
|
998
|
+
if (!response.ok) {
|
|
999
|
+
const body = await response.json().catch(() => ({}));
|
|
1000
|
+
throw new GithubApiError(response.status, body.message ?? `GitHub API returned ${response.status}`);
|
|
1001
|
+
}
|
|
1002
|
+
return await response.json();
|
|
1003
|
+
}
|
|
1004
|
+
sweep(now) {
|
|
1005
|
+
for (const [key, entry] of this.tokens) {
|
|
1006
|
+
if (entry.expiresAt !== undefined && entry.expiresAt <= now) {
|
|
1007
|
+
this.tokens.delete(key);
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
function headers(bearer) {
|
|
1013
|
+
return {
|
|
1014
|
+
Accept: "application/vnd.github+json",
|
|
1015
|
+
Authorization: `Bearer ${bearer}`,
|
|
1016
|
+
"X-GitHub-Api-Version": "2022-11-28"
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
function fingerprint(app) {
|
|
1020
|
+
return createHash("sha256").update(app.appId.trim()).update("\x00").update(app.privateKey.trim()).digest("hex");
|
|
1021
|
+
}
|
|
1022
|
+
function mapInstallation(raw) {
|
|
1023
|
+
return {
|
|
1024
|
+
id: raw.id,
|
|
1025
|
+
account: raw.account ? { login: raw.account.login, id: raw.account.id, type: raw.account.type } : null,
|
|
1026
|
+
repositorySelection: raw.repository_selection === "selected" ? "selected" : "all",
|
|
1027
|
+
permissions: raw.permissions ?? {},
|
|
1028
|
+
events: raw.events ?? [],
|
|
1029
|
+
appSlug: raw.app_slug,
|
|
1030
|
+
suspendedAt: raw.suspended_at
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
function requireInstallationId(value) {
|
|
1034
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
1035
|
+
throw new GithubAuthError("invalid_installation", "A GitHub App installation ID must be a positive integer");
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
function repositoryName(repository) {
|
|
1039
|
+
const name = repository.trim().split("/").pop() ?? "";
|
|
1040
|
+
return segment(name.replace(/\.git$/, ""), "repository");
|
|
1041
|
+
}
|
|
1042
|
+
function segment(value, what) {
|
|
1043
|
+
const trimmed = value.trim();
|
|
1044
|
+
if (!/^[\w.-]+$/.test(trimmed) || trimmed === "." || trimmed === "..") {
|
|
1045
|
+
throw new GithubApiError(400, `Invalid ${what}: ${value}`);
|
|
1046
|
+
}
|
|
1047
|
+
return trimmed;
|
|
1048
|
+
}
|
|
1049
|
+
function base64url(value) {
|
|
1050
|
+
return Buffer.from(value).toString("base64url");
|
|
1051
|
+
}
|
|
1052
|
+
// src/manifest.ts
|
|
1053
|
+
var GITHUB_BASE = "https://github.com";
|
|
1054
|
+
var API_BASE3 = "https://api.github.com";
|
|
1055
|
+
var DEFAULT_GITHUB_APP_PERMISSIONS = {
|
|
1056
|
+
metadata: "read",
|
|
1057
|
+
contents: "write",
|
|
1058
|
+
pull_requests: "write",
|
|
1059
|
+
issues: "write",
|
|
1060
|
+
checks: "write"
|
|
1061
|
+
};
|
|
1062
|
+
var DEFAULT_GITHUB_APP_EVENTS = [
|
|
1063
|
+
"push",
|
|
1064
|
+
"pull_request",
|
|
1065
|
+
"pull_request_review",
|
|
1066
|
+
"pull_request_review_comment",
|
|
1067
|
+
"issue_comment",
|
|
1068
|
+
"check_run",
|
|
1069
|
+
"check_suite"
|
|
1070
|
+
];
|
|
1071
|
+
function buildGithubAppManifest(options) {
|
|
1072
|
+
const name = options.name.trim();
|
|
1073
|
+
if (!name)
|
|
1074
|
+
throw new Error("A GitHub App name is required");
|
|
1075
|
+
return {
|
|
1076
|
+
name,
|
|
1077
|
+
url: options.url,
|
|
1078
|
+
...options.description ? { description: options.description } : {},
|
|
1079
|
+
redirect_url: options.redirectUrl,
|
|
1080
|
+
...options.callbackUrls?.length ? { callback_urls: [...options.callbackUrls] } : {},
|
|
1081
|
+
...options.setupUrl ? { setup_url: options.setupUrl } : {},
|
|
1082
|
+
...options.webhookUrl ? { hook_attributes: { url: options.webhookUrl, active: true } } : {},
|
|
1083
|
+
public: options.public ?? false,
|
|
1084
|
+
default_permissions: {
|
|
1085
|
+
...options.permissions ?? DEFAULT_GITHUB_APP_PERMISSIONS
|
|
1086
|
+
},
|
|
1087
|
+
default_events: options.webhookUrl ? [...options.events ?? DEFAULT_GITHUB_APP_EVENTS] : [],
|
|
1088
|
+
...options.requestOauthOnInstall !== undefined ? { request_oauth_on_install: options.requestOauthOnInstall } : {}
|
|
1089
|
+
};
|
|
1090
|
+
}
|
|
1091
|
+
function githubAppManifestForm(args) {
|
|
1092
|
+
const base = (args.webBaseUrl ?? GITHUB_BASE).replace(/\/+$/, "");
|
|
1093
|
+
if (args.organization && !/^[\w.-]+$/.test(args.organization)) {
|
|
1094
|
+
throw new Error(`Invalid organization: ${args.organization}`);
|
|
1095
|
+
}
|
|
1096
|
+
const action = new URL(args.organization ? `${base}/organizations/${args.organization}/settings/apps/new` : `${base}/settings/apps/new`);
|
|
1097
|
+
action.searchParams.set("state", args.state);
|
|
1098
|
+
return {
|
|
1099
|
+
action: action.toString(),
|
|
1100
|
+
fields: { manifest: JSON.stringify(args.manifest) }
|
|
1101
|
+
};
|
|
1102
|
+
}
|
|
1103
|
+
async function convertGithubAppManifest(args) {
|
|
1104
|
+
if (!/^[\w-]+$/.test(args.code)) {
|
|
1105
|
+
throw new GithubApiError(400, "Invalid manifest code");
|
|
1106
|
+
}
|
|
1107
|
+
const base = (args.apiBaseUrl ?? API_BASE3).replace(/\/+$/, "");
|
|
1108
|
+
const response = await (args.fetch ?? fetch)(`${base}/app-manifests/${args.code}/conversions`, {
|
|
1109
|
+
method: "POST",
|
|
1110
|
+
headers: {
|
|
1111
|
+
Accept: "application/vnd.github+json",
|
|
1112
|
+
"X-GitHub-Api-Version": "2022-11-28"
|
|
1113
|
+
}
|
|
1114
|
+
});
|
|
1115
|
+
if (!response.ok) {
|
|
1116
|
+
const body = await response.json().catch(() => ({}));
|
|
1117
|
+
throw new GithubApiError(response.status, body.message ?? `GitHub API returned ${response.status}`);
|
|
1118
|
+
}
|
|
1119
|
+
const raw = await response.json();
|
|
1120
|
+
if (!raw.id || !raw.pem || !raw.client_id || !raw.client_secret) {
|
|
1121
|
+
throw new GithubApiError(502, "GitHub returned incomplete app credentials");
|
|
1122
|
+
}
|
|
1123
|
+
return {
|
|
1124
|
+
appId: String(raw.id),
|
|
1125
|
+
slug: raw.slug,
|
|
1126
|
+
name: raw.name,
|
|
1127
|
+
owner: raw.owner?.login ?? null,
|
|
1128
|
+
htmlUrl: raw.html_url,
|
|
1129
|
+
clientId: raw.client_id,
|
|
1130
|
+
clientSecret: raw.client_secret,
|
|
1131
|
+
webhookSecret: raw.webhook_secret ?? null,
|
|
1132
|
+
privateKey: raw.pem
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
// src/oauth.ts
|
|
1136
|
+
var GITHUB_BASE2 = "https://github.com";
|
|
1137
|
+
async function postForm(fetchImpl, url, params, signal) {
|
|
1138
|
+
const response = await fetchImpl(url, {
|
|
1139
|
+
...signal ? { signal } : {},
|
|
1140
|
+
method: "POST",
|
|
1141
|
+
headers: {
|
|
1142
|
+
Accept: "application/json",
|
|
1143
|
+
"Content-Type": "application/x-www-form-urlencoded"
|
|
1144
|
+
},
|
|
1145
|
+
body: new URLSearchParams(params).toString()
|
|
1146
|
+
});
|
|
1147
|
+
if (!response.ok) {
|
|
1148
|
+
if (response.status >= 500)
|
|
1149
|
+
throw new GithubApiError(response.status, `GitHub OAuth endpoint returned ${response.status}`);
|
|
1150
|
+
throw new GithubAuthError("http_error", `GitHub OAuth endpoint returned ${response.status}`);
|
|
1151
|
+
}
|
|
1152
|
+
return await response.json();
|
|
1153
|
+
}
|
|
1154
|
+
function toTokenSet(data, now) {
|
|
1155
|
+
if (!data.access_token) {
|
|
1156
|
+
throw new GithubAuthError(data.error ?? "unknown", data.error_description ?? "GitHub returned no access token");
|
|
1157
|
+
}
|
|
1158
|
+
return {
|
|
1159
|
+
accessToken: data.access_token,
|
|
1160
|
+
expiresAt: data.expires_in ? now + data.expires_in * 1000 : null,
|
|
1161
|
+
refreshToken: data.refresh_token ?? null,
|
|
1162
|
+
refreshTokenExpiresAt: data.refresh_token_expires_in ? now + data.refresh_token_expires_in * 1000 : null
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
async function requestDeviceCode(app, opts) {
|
|
1166
|
+
const data = await postForm(opts?.fetch ?? fetch, `${opts?.baseUrl ?? GITHUB_BASE2}/login/device/code`, { client_id: app.clientId });
|
|
1167
|
+
const raw = data;
|
|
1168
|
+
if (!raw.device_code || !raw.user_code || !raw.verification_uri) {
|
|
1169
|
+
throw new GithubAuthError(raw.error ?? "unknown", raw.error_description ?? "GitHub returned an incomplete device grant");
|
|
1170
|
+
}
|
|
1171
|
+
return {
|
|
1172
|
+
deviceCode: raw.device_code,
|
|
1173
|
+
userCode: raw.user_code,
|
|
1174
|
+
verificationUri: raw.verification_uri,
|
|
1175
|
+
expiresIn: raw.expires_in ?? 900,
|
|
1176
|
+
interval: raw.interval ?? 5
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
async function pollDeviceToken(app, deviceCode, opts) {
|
|
1180
|
+
const data = await postForm(opts?.fetch ?? fetch, `${opts?.baseUrl ?? GITHUB_BASE2}/login/oauth/access_token`, {
|
|
1181
|
+
client_id: app.clientId,
|
|
1182
|
+
device_code: deviceCode,
|
|
1183
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code"
|
|
1184
|
+
});
|
|
1185
|
+
if (data.error === "authorization_pending") {
|
|
1186
|
+
return { tokens: null, retryAfter: 0 };
|
|
1187
|
+
}
|
|
1188
|
+
if (data.error === "slow_down") {
|
|
1189
|
+
return { tokens: null, retryAfter: data.interval ?? 5 };
|
|
1190
|
+
}
|
|
1191
|
+
return { tokens: toTokenSet(data, opts?.now ?? Date.now()) };
|
|
1192
|
+
}
|
|
1193
|
+
function buildAuthorizeUrl(app, opts) {
|
|
1194
|
+
const url = new URL(`${opts.baseUrl ?? GITHUB_BASE2}/login/oauth/authorize`);
|
|
1195
|
+
url.searchParams.set("client_id", app.clientId);
|
|
1196
|
+
url.searchParams.set("redirect_uri", opts.redirectUri);
|
|
1197
|
+
url.searchParams.set("state", opts.state);
|
|
1198
|
+
return url.toString();
|
|
1199
|
+
}
|
|
1200
|
+
async function exchangeCode(app, args, opts) {
|
|
1201
|
+
if (!app.clientSecret) {
|
|
1202
|
+
throw new GithubAuthError("missing_client_secret", "The web OAuth flow requires a client secret; use the device flow for public clients");
|
|
1203
|
+
}
|
|
1204
|
+
const data = await postForm(opts?.fetch ?? fetch, `${opts?.baseUrl ?? GITHUB_BASE2}/login/oauth/access_token`, {
|
|
1205
|
+
client_id: app.clientId,
|
|
1206
|
+
client_secret: app.clientSecret,
|
|
1207
|
+
code: args.code,
|
|
1208
|
+
...args.redirectUri ? { redirect_uri: args.redirectUri } : {}
|
|
1209
|
+
});
|
|
1210
|
+
return toTokenSet(data, opts?.now ?? Date.now());
|
|
1211
|
+
}
|
|
1212
|
+
async function refreshAccessToken(app, refreshToken, opts) {
|
|
1213
|
+
const data = await postForm(opts?.fetch ?? fetch, `${opts?.baseUrl ?? GITHUB_BASE2}/login/oauth/access_token`, {
|
|
1214
|
+
client_id: app.clientId,
|
|
1215
|
+
...app.clientSecret ? { client_secret: app.clientSecret } : {},
|
|
1216
|
+
grant_type: "refresh_token",
|
|
1217
|
+
refresh_token: refreshToken
|
|
1218
|
+
}, opts?.signal);
|
|
1219
|
+
return toTokenSet(data, opts?.now ?? Date.now());
|
|
1220
|
+
}
|
|
1221
|
+
function buildInstallationUrl(app) {
|
|
1222
|
+
if (!app.appSlug) {
|
|
1223
|
+
throw new GithubAuthError("missing_app_slug", "GithubAppConfig.appSlug is required to build the installation URL");
|
|
1224
|
+
}
|
|
1225
|
+
return `https://github.com/apps/${app.appSlug}/installations/new`;
|
|
1226
|
+
}
|
|
1227
|
+
function isTokenStale(tokens, now = Date.now(), skewMs = 60000) {
|
|
1228
|
+
return tokens.expiresAt !== null && tokens.expiresAt - skewMs <= now;
|
|
1229
|
+
}
|
|
1230
|
+
async function revokeUserToken(args) {
|
|
1231
|
+
if (!args.app.clientSecret) {
|
|
1232
|
+
throw new GithubAuthError("missing_client_secret", "Revoking a user token requires the app's client secret");
|
|
1233
|
+
}
|
|
1234
|
+
const base = (args.apiBaseUrl ?? "https://api.github.com").replace(/\/+$/, "");
|
|
1235
|
+
const basic = Buffer.from(`${args.app.clientId}:${args.app.clientSecret}`).toString("base64");
|
|
1236
|
+
const response = await (args.fetch ?? fetch)(`${base}/applications/${encodeURIComponent(args.app.clientId)}/token`, {
|
|
1237
|
+
method: "DELETE",
|
|
1238
|
+
headers: {
|
|
1239
|
+
Accept: "application/vnd.github+json",
|
|
1240
|
+
Authorization: `Basic ${basic}`,
|
|
1241
|
+
"Content-Type": "application/json",
|
|
1242
|
+
"X-GitHub-Api-Version": "2022-11-28"
|
|
1243
|
+
},
|
|
1244
|
+
body: JSON.stringify({ access_token: args.accessToken })
|
|
1245
|
+
});
|
|
1246
|
+
if (!response.ok && response.status !== 404) {
|
|
1247
|
+
throw new GithubAuthError("http_error", `GitHub token revocation returned ${response.status}`);
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
// src/rest.ts
|
|
1251
|
+
var API_BASE4 = "https://api.github.com";
|
|
1252
|
+
var DEFAULT_MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
1253
|
+
async function githubRestRequest(request) {
|
|
1254
|
+
const target = githubRestUrl({
|
|
1255
|
+
path: request.path,
|
|
1256
|
+
query: request.query,
|
|
1257
|
+
apiBaseUrl: request.apiBaseUrl
|
|
1258
|
+
});
|
|
1259
|
+
const accept = request.accept ?? "application/vnd.github+json";
|
|
1260
|
+
if (!/^application\/(vnd\.github[\w.+-]*|json)$/.test(accept)) {
|
|
1261
|
+
throw new Error(`Unsupported media type '${accept}'`);
|
|
1262
|
+
}
|
|
1263
|
+
const offset = request.offset ?? 0;
|
|
1264
|
+
if (!Number.isSafeInteger(offset) || offset < 0) {
|
|
1265
|
+
throw new Error("offset must be a non-negative integer");
|
|
1266
|
+
}
|
|
1267
|
+
const hasBody = request.body !== undefined && request.method !== "GET";
|
|
1268
|
+
const response = await (request.fetch ?? fetch)(target, {
|
|
1269
|
+
method: request.method,
|
|
1270
|
+
headers: {
|
|
1271
|
+
Accept: accept,
|
|
1272
|
+
Authorization: `Bearer ${request.token}`,
|
|
1273
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
1274
|
+
...hasBody ? { "Content-Type": "application/json" } : {}
|
|
1275
|
+
},
|
|
1276
|
+
redirect: "manual",
|
|
1277
|
+
...request.signal ? { signal: request.signal } : {},
|
|
1278
|
+
...hasBody ? { body: JSON.stringify(request.body) } : {}
|
|
1279
|
+
});
|
|
1280
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
1281
|
+
const maxBytes = request.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
|
|
1282
|
+
const end = utf8Boundary({
|
|
1283
|
+
bytes,
|
|
1284
|
+
start: offset,
|
|
1285
|
+
end: Math.min(bytes.byteLength, offset + maxBytes)
|
|
1286
|
+
});
|
|
1287
|
+
const whole = offset === 0 && end === bytes.byteLength;
|
|
1288
|
+
const text = new TextDecoder().decode(bytes.slice(offset, end));
|
|
1289
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
1290
|
+
const location = response.headers.get("location");
|
|
1291
|
+
return {
|
|
1292
|
+
status: response.status,
|
|
1293
|
+
contentType,
|
|
1294
|
+
body: whole && contentType.includes("json") ? parseJson(text) : text,
|
|
1295
|
+
...location ? { location } : {},
|
|
1296
|
+
...end < bytes.byteLength ? { truncated: true, nextOffset: end } : {},
|
|
1297
|
+
totalBytes: bytes.byteLength
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
function githubRestUrl(args) {
|
|
1301
|
+
const base = new URL(args.apiBaseUrl ?? API_BASE4);
|
|
1302
|
+
const basePath = base.pathname.replace(/\/+$/, "");
|
|
1303
|
+
const path = args.path.startsWith("/") ? args.path : `/${args.path}`;
|
|
1304
|
+
if (path.includes("..") || path.split("/").includes(".") || path.includes("\\") || path.includes("//") || /[?#]/.test(path) || /%(2e|2f|5c)/i.test(path)) {
|
|
1305
|
+
throw new Error("Paths may not contain '.' or '..' segments, '//', '?', '#', backslashes, or encoded dots and slashes");
|
|
1306
|
+
}
|
|
1307
|
+
const target = new URL(`${basePath}${path}`, base.origin);
|
|
1308
|
+
if (target.origin !== base.origin || basePath && target.pathname !== basePath && !target.pathname.startsWith(`${basePath}/`)) {
|
|
1309
|
+
throw new Error("Requests must stay on the GitHub API");
|
|
1310
|
+
}
|
|
1311
|
+
for (const [key, value] of Object.entries(args.query ?? {})) {
|
|
1312
|
+
target.searchParams.set(key, value);
|
|
1313
|
+
}
|
|
1314
|
+
return target.toString();
|
|
1315
|
+
}
|
|
1316
|
+
function repositoryFromRestPath(path) {
|
|
1317
|
+
const match = /^\/?repos\/([\w.-]+)\/([\w.-]+)(?:\/|$)/.exec(path);
|
|
1318
|
+
if (!match?.[1] || !match[2])
|
|
1319
|
+
return null;
|
|
1320
|
+
return { owner: match[1], name: match[2] };
|
|
1321
|
+
}
|
|
1322
|
+
function utf8Boundary(args) {
|
|
1323
|
+
if (args.end >= args.bytes.byteLength)
|
|
1324
|
+
return args.end;
|
|
1325
|
+
for (let end = args.end;end > args.start; end--) {
|
|
1326
|
+
if (((args.bytes[end] ?? 0) & 192) !== 128)
|
|
1327
|
+
return end;
|
|
1328
|
+
}
|
|
1329
|
+
return args.end;
|
|
1330
|
+
}
|
|
1331
|
+
function parseJson(text) {
|
|
1332
|
+
try {
|
|
1333
|
+
const parsed = JSON.parse(text);
|
|
1334
|
+
return parsed;
|
|
1335
|
+
} catch {
|
|
1336
|
+
return text;
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
export {
|
|
1340
|
+
DEFAULT_GITHUB_APP_EVENTS,
|
|
1341
|
+
DEFAULT_GITHUB_APP_PERMISSIONS,
|
|
1342
|
+
GithubApi,
|
|
1343
|
+
GithubApiError,
|
|
1344
|
+
GithubAppAuth,
|
|
1345
|
+
GithubAuthError,
|
|
1346
|
+
GithubGraphqlError,
|
|
1347
|
+
buildAuthorizeUrl,
|
|
1348
|
+
buildGithubAppManifest,
|
|
1349
|
+
buildInstallationUrl,
|
|
1350
|
+
convertGithubAppManifest,
|
|
1351
|
+
createGithubAppJwt,
|
|
1352
|
+
exchangeCode,
|
|
1353
|
+
gitCredentialsFor,
|
|
1354
|
+
githubAppManifestForm,
|
|
1355
|
+
githubGraphqlUrl,
|
|
1356
|
+
githubRestRequest,
|
|
1357
|
+
githubRestUrl,
|
|
1358
|
+
isGithubRemoteUrl,
|
|
1359
|
+
isTokenStale,
|
|
1360
|
+
parseGithubAppPrivateKey,
|
|
1361
|
+
pollDeviceToken,
|
|
1362
|
+
pullRequestFromUrl,
|
|
1363
|
+
refreshAccessToken,
|
|
1364
|
+
repoFullNameFromUrl,
|
|
1365
|
+
repositoryFromRestPath,
|
|
1366
|
+
requestDeviceCode,
|
|
1367
|
+
revokeUserToken
|
|
1368
|
+
};
|
|
1369
|
+
|
|
1370
|
+
//# debugId=1F974E11391150E964756E2164756E21
|
|
1371
|
+
//# sourceMappingURL=index.js.map
|