@vite-hub/forge 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,4161 @@
1
+ import { $ as toDate, B as milestoneId, C as createListing, D as forgeIterable, F as latestCommentOf, G as requireIssueOrPull, H as rateLimitOf, J as sleep, K as requireThread, L as memo, M as isFirstPage, N as isSecondaryRateLimit, O as getManyConcurrently, P as iteratePages, Q as teamOrg, S as createFetcher, T as degradesToWarning, U as rateLimitPart, V as phased, W as rateLimitReset, X as summariseChecks, Y as soleMergeMethod, _t as reactionContent, a as ForgeApiError, at as versionAtLeast, b as anySignal, c as InsufficientScopeError, ct as REACTION_CONTENTS, d as NotFoundError, dt as isResolvedThread, et as toFileStatus, f as RateLimitedError, g as UnsupportedOperationError, i as ForbiddenError, it as toWarning, j as hostOf, l as MergeBlockedError, lt as githubShapedWeb, n as BranchMovedError, nt as toPage, o as ForgeError, p as ReadOnlyError, q as resolveToken, rt as toPullStats, s as ForgeTimeoutError, st as OWNER_NAME, t as AuthenticationRequiredError, tt as toMergeError, u as MergeConflictError, ut as isNamespaceRef, v as abortable, x as checkRunState, y as actorLogin } from "./utils-CA_4WJhJ-DNgT61X2.js";
2
+ import { C as verb, E as signRs256Jwt, S as toFileContent, _ as reviewState, a as verifyHmacSignature, b as supportOnly, c as changeBase64, d as eventTime, f as existingFiles, g as perKind, h as isSha, l as defineForgeProvider, m as inDirectories, p as fromBase64, r as nativeEventsFor, s as WRITE_VERBS, t as eventKindsOf, y as splitMessage } from "./webhooks-DgHwxxYz-D1V2LOr1.js";
3
+ import { t as toAuthorAssociation } from "./association-Cm0dUTDU-CDDhJnIh.js";
4
+ //#region ../../node_modules/.pnpm/forges@https+++pkg.pr.new+danielroe+forges@40d50b2f8bdc5585becfae405e1a3b8a325f7202/node_modules/forges/dist/web-DTc-BDSX.mjs
5
+ const RESERVED_PATHS = [
6
+ "about",
7
+ "account",
8
+ "apps",
9
+ "codespaces",
10
+ "collections",
11
+ "contact",
12
+ "customer-stories",
13
+ "dashboard",
14
+ "enterprise",
15
+ "enterprises",
16
+ "events",
17
+ "explore",
18
+ "features",
19
+ "gist",
20
+ "issues",
21
+ "join",
22
+ "login",
23
+ "logout",
24
+ "marketplace",
25
+ "new",
26
+ "notifications",
27
+ "organizations",
28
+ "orgs",
29
+ "pricing",
30
+ "pulls",
31
+ "search",
32
+ "security",
33
+ "settings",
34
+ "signup",
35
+ "site",
36
+ "sponsors",
37
+ "stars",
38
+ "topics",
39
+ "trending",
40
+ "users",
41
+ "watching"
42
+ ];
43
+ const REFERENCES = {
44
+ threads: [{
45
+ prefix: "#",
46
+ kind: "issue"
47
+ }, {
48
+ prefix: "GH-",
49
+ kind: "issue",
50
+ sameRepo: true
51
+ }],
52
+ repo: OWNER_NAME,
53
+ commits: true
54
+ };
55
+ function isGheCom(host) {
56
+ return /^api\.[^.]+\.ghe\.com$/.test(host);
57
+ }
58
+ /** The web host for an API host: `api.github.com` and `api.<name>.ghe.com` drop the `api.` prefix. */
59
+ function webHost(host) {
60
+ return host === "api.github.com" || isGheCom(host) ? host.slice(4) : host;
61
+ }
62
+ const GITHUB_WEB = {
63
+ forge: "github",
64
+ baseUrl: "https://api.github.com",
65
+ instance: webHost,
66
+ links: ({ baseUrl }) => {
67
+ const host = new URL(baseUrl).host;
68
+ const enterprise = host !== "api.github.com" && !isGheCom(host);
69
+ return githubShapedWeb(enterprise ? baseUrl.replace(/\/api\/v3$/, "") : `https://${webHost(host)}`, {
70
+ pull: "pull",
71
+ discussions: true,
72
+ ...host === "api.github.com" ? { rawOrigin: "https://raw.githubusercontent.com" } : {},
73
+ commentFragment: "issuecomment-",
74
+ file: (at) => `/blob/${encodeURIComponent(at)}`,
75
+ lineFragment: (line) => `L${line}`,
76
+ reserved: RESERVED_PATHS,
77
+ references: REFERENCES
78
+ });
79
+ }
80
+ };
81
+ //#endregion
82
+ //#region ../../node_modules/.pnpm/forges@https+++pkg.pr.new+danielroe+forges@40d50b2f8bdc5585becfae405e1a3b8a325f7202/node_modules/forges/dist/github-Cd65-36w.mjs
83
+ const TOKEN_PREFIXES = [
84
+ ["ghp_", "classic"],
85
+ ["gho_", "classic"],
86
+ ["github_pat_", "fine-grained"],
87
+ ["ghu_", "app-user"],
88
+ ["ghs_", "installation"]
89
+ ];
90
+ /** The kind of a GitHub token, from its `kind` or the prefix of `token`; `undefined` when neither tells. */
91
+ function tokenKindOf(auth, token = typeof auth.token === "string" ? auth.token : void 0) {
92
+ return auth.kind ?? (token === void 0 ? void 0 : TOKEN_PREFIXES.find(([prefix]) => token.startsWith(prefix))?.[1]);
93
+ }
94
+ const JWT_LIFETIME_SECONDS = 540;
95
+ const REFRESH_MARGIN_MS = 6e4;
96
+ function createAppCredentials(auth, context) {
97
+ let jwt;
98
+ const tokens = /* @__PURE__ */ new Map();
99
+ const exchanges = /* @__PURE__ */ new Map();
100
+ async function appJwt() {
101
+ if (jwt && jwt.expiresAt > Date.now() + REFRESH_MARGIN_MS) return jwt.value;
102
+ const now = Math.floor(Date.now() / 1e3);
103
+ const value = signRs256Jwt(auth.privateKey, {
104
+ iss: String(auth.appId),
105
+ iat: now - 60,
106
+ exp: now + JWT_LIFETIME_SECONDS
107
+ });
108
+ const entry = {
109
+ value,
110
+ expiresAt: (now + JWT_LIFETIME_SECONDS) * 1e3
111
+ };
112
+ jwt = entry;
113
+ value.catch(() => {
114
+ if (jwt === entry) jwt = void 0;
115
+ });
116
+ return value;
117
+ }
118
+ const fetcher = createFetcher({
119
+ ...context,
120
+ authHeaders: async () => ({ authorization: `Bearer ${await appJwt()}` })
121
+ });
122
+ async function installationTokenDetails(installationId, options) {
123
+ options?.signal?.throwIfAborted();
124
+ const cached = tokens.get(installationId);
125
+ if (cached && cached.expiresAt.getTime() > Date.now() + REFRESH_MARGIN_MS) return cached;
126
+ let exchange = exchanges.get(installationId);
127
+ if (!exchange) {
128
+ exchange = fetcher.json(`/app/installations/${installationId}/access_tokens`, { method: "POST" }).then(({ data }) => {
129
+ const token = {
130
+ token: data.token,
131
+ expiresAt: new Date(data.expires_at),
132
+ permissions: data.permissions ?? {},
133
+ repositorySelection: data.repository_selection
134
+ };
135
+ tokens.set(installationId, token);
136
+ return token;
137
+ });
138
+ const forget = () => exchanges.delete(installationId);
139
+ exchange.then(forget, forget);
140
+ exchanges.set(installationId, exchange);
141
+ }
142
+ return abortable(exchange, options?.signal);
143
+ }
144
+ return {
145
+ appJwt,
146
+ installationTokenDetails,
147
+ installationToken: async (installationId, options) => (await installationTokenDetails(installationId, options)).token
148
+ };
149
+ }
150
+ function createAuthHeaders(auth, credentials) {
151
+ if (!auth || auth.type === "anonymous") return async () => ({});
152
+ if (auth.type === "token") return async () => ({ authorization: `Bearer ${await resolveToken(auth)}` });
153
+ const app = credentials;
154
+ const installationId = auth.installationId;
155
+ if (installationId === void 0) return async () => ({ authorization: `Bearer ${await app.appJwt()}` });
156
+ return async () => ({ authorization: `Bearer ${await app.installationToken(String(installationId))}` });
157
+ }
158
+ /** Native GitHub event names per normalised kind, for hook subscriptions. */
159
+ const GITHUB_NATIVE_EVENTS = {
160
+ comment: [
161
+ "issue_comment",
162
+ "commit_comment",
163
+ "discussion_comment"
164
+ ],
165
+ review: ["pull_request_review"],
166
+ review_comment: ["pull_request_review_comment"],
167
+ state_change: [
168
+ "issues",
169
+ "pull_request",
170
+ "discussion"
171
+ ],
172
+ label: [
173
+ "issues",
174
+ "pull_request",
175
+ "label"
176
+ ],
177
+ assignment: ["issues", "pull_request"],
178
+ push: ["push"],
179
+ ref: ["create", "delete"],
180
+ repo: ["repository", "public"],
181
+ installation: ["installation", "installation_repositories"],
182
+ membership: [
183
+ "member",
184
+ "membership",
185
+ "organization",
186
+ "team"
187
+ ],
188
+ release: ["release"],
189
+ star: ["star"],
190
+ fork: ["fork"],
191
+ wiki: ["gollum"],
192
+ issue_type: ["issues"]
193
+ };
194
+ /** Normalised kinds and actions GitHub deliveries translate into. */
195
+ const GITHUB_WEBHOOK_EVENTS = [
196
+ {
197
+ kind: "comment",
198
+ action: "created"
199
+ },
200
+ {
201
+ kind: "comment",
202
+ action: "edited"
203
+ },
204
+ {
205
+ kind: "comment",
206
+ action: "deleted"
207
+ },
208
+ {
209
+ kind: "review",
210
+ action: "submitted"
211
+ },
212
+ {
213
+ kind: "review_comment",
214
+ action: "created"
215
+ },
216
+ {
217
+ kind: "review_comment",
218
+ action: "edited"
219
+ },
220
+ {
221
+ kind: "review_comment",
222
+ action: "deleted"
223
+ },
224
+ {
225
+ kind: "state_change",
226
+ action: "opened"
227
+ },
228
+ {
229
+ kind: "state_change",
230
+ action: "closed"
231
+ },
232
+ {
233
+ kind: "state_change",
234
+ action: "reopened"
235
+ },
236
+ {
237
+ kind: "state_change",
238
+ action: "merged"
239
+ },
240
+ {
241
+ kind: "state_change",
242
+ action: "ready_for_review"
243
+ },
244
+ {
245
+ kind: "state_change",
246
+ action: "converted_to_draft"
247
+ },
248
+ {
249
+ kind: "label",
250
+ action: "labelled"
251
+ },
252
+ {
253
+ kind: "label",
254
+ action: "unlabelled"
255
+ },
256
+ {
257
+ kind: "assignment",
258
+ action: "assigned"
259
+ },
260
+ {
261
+ kind: "assignment",
262
+ action: "unassigned"
263
+ },
264
+ {
265
+ kind: "assignment",
266
+ action: "review_requested"
267
+ },
268
+ { kind: "push" },
269
+ {
270
+ kind: "ref",
271
+ action: "created"
272
+ },
273
+ {
274
+ kind: "ref",
275
+ action: "deleted"
276
+ },
277
+ {
278
+ kind: "repo",
279
+ action: "renamed"
280
+ },
281
+ {
282
+ kind: "repo",
283
+ action: "transferred"
284
+ },
285
+ {
286
+ kind: "repo",
287
+ action: "archived"
288
+ },
289
+ {
290
+ kind: "repo",
291
+ action: "unarchived"
292
+ },
293
+ {
294
+ kind: "repo",
295
+ action: "edited"
296
+ },
297
+ { kind: "installation" },
298
+ { kind: "membership" },
299
+ {
300
+ kind: "release",
301
+ action: "created"
302
+ },
303
+ {
304
+ kind: "release",
305
+ action: "published"
306
+ },
307
+ {
308
+ kind: "release",
309
+ action: "edited"
310
+ },
311
+ {
312
+ kind: "release",
313
+ action: "deleted"
314
+ },
315
+ {
316
+ kind: "release",
317
+ action: "other"
318
+ },
319
+ {
320
+ kind: "star",
321
+ action: "created"
322
+ },
323
+ {
324
+ kind: "star",
325
+ action: "deleted"
326
+ },
327
+ {
328
+ kind: "fork",
329
+ action: "created"
330
+ },
331
+ {
332
+ kind: "wiki",
333
+ action: "created"
334
+ },
335
+ {
336
+ kind: "wiki",
337
+ action: "edited"
338
+ },
339
+ {
340
+ kind: "issue_type",
341
+ action: "typed"
342
+ },
343
+ {
344
+ kind: "issue_type",
345
+ action: "untyped"
346
+ }
347
+ ];
348
+ const FORGE = "github";
349
+ function toActor(instance, user) {
350
+ if (!user?.login) return;
351
+ return {
352
+ forge: FORGE,
353
+ instance,
354
+ login: user.login,
355
+ id: String(user.id ?? user.login),
356
+ name: user.name ?? void 0,
357
+ avatarUrl: user.avatar_url,
358
+ url: user.html_url,
359
+ typeRaw: user.type,
360
+ isBotHint: user.type === "Bot" || user.login.endsWith("[bot]"),
361
+ ...user.type === "Bot" && user.login.endsWith("[bot]") ? { app: { slug: user.login.slice(0, -5) } } : {}
362
+ };
363
+ }
364
+ function toUser(instance, user) {
365
+ return {
366
+ ...toActor(instance, user),
367
+ bio: user.bio ?? void 0,
368
+ company: user.company ?? void 0,
369
+ location: user.location ?? void 0,
370
+ websiteUrl: user.blog || void 0,
371
+ createdAt: toDate(user.created_at),
372
+ followers: user.followers,
373
+ following: user.following,
374
+ publicRepos: user.public_repos,
375
+ raw: user
376
+ };
377
+ }
378
+ function toRepoRef(instance, repo) {
379
+ const [owner, name] = repo.full_name.split("/");
380
+ return {
381
+ forge: FORGE,
382
+ instance,
383
+ owner: repo.owner?.login ?? owner ?? "",
384
+ name: repo.name ?? name ?? "",
385
+ externalId: repo.id === void 0 ? void 0 : String(repo.id)
386
+ };
387
+ }
388
+ /** Reads `owner` and `name` out of an API repository URL, which search results carry instead of a nested repository. */
389
+ function repoRefFromApiUrl(instance, url) {
390
+ const [, owner, name] = url?.match(/\/repos\/([^/]+)\/([^/]+)$/) ?? [];
391
+ return owner && name ? {
392
+ forge: FORGE,
393
+ instance,
394
+ owner,
395
+ name
396
+ } : void 0;
397
+ }
398
+ const MERGE_COMMIT_TITLES = {
399
+ PR_TITLE: "pull_request_title",
400
+ COMMIT_OR_PR_TITLE: "commit_or_pull_request_title",
401
+ MERGE_MESSAGE: "merge_message"
402
+ };
403
+ const MERGE_COMMIT_MESSAGES = {
404
+ PR_BODY: "pull_request_body",
405
+ PR_TITLE: "pull_request_title",
406
+ COMMIT_MESSAGES: "commit_messages",
407
+ BLANK: "blank"
408
+ };
409
+ function toMergeCommitDefaults(title, message) {
410
+ return title || message ? {
411
+ title: MERGE_COMMIT_TITLES[title ?? ""],
412
+ titleRaw: title,
413
+ message: MERGE_COMMIT_MESSAGES[message ?? ""],
414
+ messageRaw: message
415
+ } : void 0;
416
+ }
417
+ function toMergeCommit(raw) {
418
+ const merge = toMergeCommitDefaults(raw.merge_commit_title, raw.merge_commit_message);
419
+ const squash = toMergeCommitDefaults(raw.squash_merge_commit_title, raw.squash_merge_commit_message);
420
+ return merge || squash ? {
421
+ merge,
422
+ squash
423
+ } : void 0;
424
+ }
425
+ function toRepo(instance, raw) {
426
+ const visibility = raw.visibility === "internal" ? "internal" : raw.private || raw.visibility === "private" ? "private" : "public";
427
+ return {
428
+ ref: toRepoRef(instance, raw),
429
+ description: raw.description ?? void 0,
430
+ defaultBranch: raw.default_branch,
431
+ visibility,
432
+ visibilityRaw: raw.visibility ?? (raw.private === void 0 ? void 0 : raw.private ? "private" : "public"),
433
+ isFork: raw.fork ?? false,
434
+ isArchived: raw.archived ?? false,
435
+ parent: raw.parent ? toRepoRef(instance, raw.parent) : void 0,
436
+ topics: raw.topics ?? [],
437
+ url: raw.html_url,
438
+ cloneUrls: raw.clone_url || raw.ssh_url ? {
439
+ https: raw.clone_url,
440
+ ssh: raw.ssh_url
441
+ } : void 0,
442
+ createdAt: toDate(raw.created_at),
443
+ updatedAt: toDate(raw.updated_at),
444
+ pushedAt: toDate(raw.pushed_at),
445
+ owner: toActor(instance, raw.owner),
446
+ language: raw.language ?? void 0,
447
+ homepage: raw.homepage || void 0,
448
+ licence: raw.license?.spdx_id && raw.license.spdx_id !== "NOASSERTION" ? raw.license.spdx_id : void 0,
449
+ stars: raw.stargazers_count,
450
+ forks: raw.forks_count,
451
+ watchers: raw.subscribers_count,
452
+ mergeMethods: raw.allow_merge_commit === void 0 && raw.allow_squash_merge === void 0 && raw.allow_rebase_merge === void 0 ? void 0 : [
453
+ ...raw.allow_merge_commit ? ["merge"] : [],
454
+ ...raw.allow_squash_merge ? ["squash"] : [],
455
+ ...raw.allow_rebase_merge ? ["rebase"] : []
456
+ ],
457
+ deleteBranchOnMerge: raw.delete_branch_on_merge,
458
+ mergeCommit: toMergeCommit(raw),
459
+ features: raw.has_issues === void 0 ? void 0 : {
460
+ issues: raw.has_issues,
461
+ pullRequests: true,
462
+ discussions: raw.has_discussions ?? false,
463
+ wiki: raw.has_wiki ?? false,
464
+ projects: raw.has_projects ?? false,
465
+ releases: true
466
+ },
467
+ permissions: raw.permissions ? {
468
+ admin: raw.permissions.admin,
469
+ maintain: raw.permissions.maintain ?? raw.permissions.admin,
470
+ push: raw.permissions.push,
471
+ triage: raw.permissions.triage ?? raw.permissions.push,
472
+ pull: raw.permissions.pull
473
+ } : void 0,
474
+ raw
475
+ };
476
+ }
477
+ function toReactions(raw) {
478
+ if (!raw) return;
479
+ const counts = Object.fromEntries(REACTION_CONTENTS.flatMap((name) => raw[name] ? [[name, raw[name]]] : []));
480
+ return {
481
+ total: raw.total_count ?? Object.values(counts).reduce((sum, count) => sum + count, 0),
482
+ counts
483
+ };
484
+ }
485
+ function toMilestone(raw) {
486
+ return raw ? {
487
+ id: String(raw.number ?? raw.id ?? ""),
488
+ title: raw.title,
489
+ state: raw.state === "closed" ? "closed" : "open",
490
+ description: raw.description ?? void 0,
491
+ dueOn: toDate(raw.due_on),
492
+ url: raw.html_url,
493
+ raw
494
+ } : void 0;
495
+ }
496
+ function toIssueType(raw) {
497
+ return raw ? {
498
+ id: raw.node_id,
499
+ name: raw.name,
500
+ description: raw.description || void 0,
501
+ colour: raw.color ?? void 0,
502
+ enabled: raw.is_enabled,
503
+ raw
504
+ } : void 0;
505
+ }
506
+ /** GitHub's `role_name`, or the permission block when a listing reports only that. */
507
+ function toRole(raw) {
508
+ switch (raw.role_name) {
509
+ case "admin":
510
+ case "maintain":
511
+ case "write":
512
+ case "triage":
513
+ case "read": return raw.role_name;
514
+ }
515
+ const permissions = raw.permissions;
516
+ if (!permissions) return "none";
517
+ return permissions.admin ? "admin" : permissions.maintain ? "maintain" : permissions.push ? "write" : permissions.triage ? "triage" : permissions.pull ? "read" : "none";
518
+ }
519
+ function toCollaborator(instance, raw) {
520
+ return {
521
+ actor: toActor(instance, raw),
522
+ role: toRole(raw),
523
+ roleRaw: raw.role_name,
524
+ raw
525
+ };
526
+ }
527
+ function toContributor(instance, raw) {
528
+ if (!("login" in raw)) return {
529
+ name: raw.name || void 0,
530
+ email: raw.email || void 0,
531
+ contributions: raw.contributions,
532
+ raw
533
+ };
534
+ return {
535
+ actor: toActor(instance, raw),
536
+ contributions: raw.contributions,
537
+ raw
538
+ };
539
+ }
540
+ function toContributorStats(instance, raw) {
541
+ return {
542
+ actor: toActor(instance, raw.author),
543
+ commits: raw.total,
544
+ weeks: raw.weeks.map((week) => ({
545
+ week: /* @__PURE__ */ new Date(week.w * 1e3),
546
+ additions: week.a ?? 0,
547
+ deletions: week.d ?? 0,
548
+ commits: week.c ?? 0
549
+ })),
550
+ raw
551
+ };
552
+ }
553
+ function toTeam(instance, org, raw) {
554
+ const parent = raw.parent ? {
555
+ forge: FORGE,
556
+ instance,
557
+ org,
558
+ id: String(raw.parent.id),
559
+ slug: raw.parent.slug
560
+ } : void 0;
561
+ return {
562
+ ref: {
563
+ forge: FORGE,
564
+ instance,
565
+ org,
566
+ id: String(raw.id),
567
+ slug: raw.slug
568
+ },
569
+ name: raw.name,
570
+ description: raw.description ?? void 0,
571
+ permission: raw.permission,
572
+ visibilityRaw: raw.privacy,
573
+ parent,
574
+ url: raw.html_url,
575
+ raw
576
+ };
577
+ }
578
+ function toThreadKind(subjectType) {
579
+ switch (subjectType) {
580
+ case "PullRequest": return "pull_request";
581
+ case "Discussion": return "discussion";
582
+ case "Issue": return "issue";
583
+ default: return;
584
+ }
585
+ }
586
+ function toThreadState(issue) {
587
+ if (issue.merged || issue.merged_at || issue.pull_request?.merged_at) return "merged";
588
+ if (issue.state === "open" || issue.state === "closed") return issue.state;
589
+ return "unknown";
590
+ }
591
+ function numberFromUrl(url) {
592
+ return /\/(?:issues|pulls|commits|discussions)\/([^/?#]+)/.exec(url ?? "")?.[1];
593
+ }
594
+ const REASONS = {
595
+ approval_requested: "approval_requested",
596
+ assign: "assigned",
597
+ author: "author",
598
+ ci_activity: "ci_activity",
599
+ comment: "comment",
600
+ invitation: "invitation",
601
+ manual: "manual",
602
+ mention: "mention",
603
+ review_requested: "review_requested",
604
+ security_alert: "security_alert",
605
+ security_advisory_credit: "security_alert",
606
+ state_change: "state_change",
607
+ subscribed: "subscribed",
608
+ team_mention: "team_mention"
609
+ };
610
+ function toReason(reason) {
611
+ return REASONS[reason] ?? "unknown";
612
+ }
613
+ const SECURITY_SUBJECTS = /* @__PURE__ */ new Set([
614
+ "RepositoryVulnerabilityAlert",
615
+ "RepositoryDependabotAlertsThread",
616
+ "SecretScanningAlert",
617
+ "RepositoryAdvisory"
618
+ ]);
619
+ const SECURITY_SUBJECTS_KIND = {
620
+ RepositoryVulnerabilityAlert: "dependency",
621
+ RepositoryDependabotAlertsThread: "dependency",
622
+ SecretScanningAlert: "secret",
623
+ RepositoryAdvisory: "advisory"
624
+ };
625
+ function lastSegment(url) {
626
+ return /\/([^/?#]+)\/?$/.exec(url ?? "")?.[1];
627
+ }
628
+ function toSubject(instance, raw) {
629
+ const repo = toRepoRef(instance, raw.repository);
630
+ const type = raw.subject.type;
631
+ const kind = toThreadKind(type);
632
+ if (kind) return {
633
+ type: "thread",
634
+ thread: {
635
+ forge: FORGE,
636
+ instance,
637
+ repo,
638
+ kind,
639
+ typeRaw: type,
640
+ number: numberFromUrl(raw.subject.url)
641
+ }
642
+ };
643
+ const sha = type === "Commit" ? numberFromUrl(raw.subject.url) : void 0;
644
+ if (sha) return {
645
+ type: "commit",
646
+ commit: {
647
+ forge: FORGE,
648
+ instance,
649
+ repo,
650
+ sha
651
+ }
652
+ };
653
+ if (type === "Release") return {
654
+ type: "release",
655
+ release: {
656
+ forge: FORGE,
657
+ instance,
658
+ repo,
659
+ id: lastSegment(raw.subject.url) ?? raw.id
660
+ }
661
+ };
662
+ if (SECURITY_SUBJECTS.has(type)) {
663
+ const kind = SECURITY_SUBJECTS_KIND[type];
664
+ return {
665
+ type: "security_alert",
666
+ alert: {
667
+ forge: FORGE,
668
+ instance,
669
+ repo,
670
+ id: lastSegment(raw.subject.url) ?? raw.id,
671
+ ...kind ? { kind } : {}
672
+ }
673
+ };
674
+ }
675
+ if (type === "RepositoryInvitation") return {
676
+ type: "repo",
677
+ repo
678
+ };
679
+ return {
680
+ type: "other",
681
+ typeRaw: type,
682
+ repo,
683
+ id: lastSegment(raw.subject.url),
684
+ url: raw.subject.url ?? void 0
685
+ };
686
+ }
687
+ function toNotification(instance, raw) {
688
+ const subject = toSubject(instance, raw);
689
+ const latestComment = latestCommentOf(subject, raw.subject.latest_comment_url);
690
+ return {
691
+ ref: {
692
+ forge: FORGE,
693
+ instance,
694
+ id: raw.id
695
+ },
696
+ subject,
697
+ subjectTypeRaw: raw.subject.type,
698
+ reason: toReason(raw.reason),
699
+ reasonRaw: raw.reason,
700
+ unread: raw.unread,
701
+ title: raw.subject.title,
702
+ subjectState: "unknown",
703
+ updatedAt: toDate(raw.updated_at) ?? /* @__PURE__ */ new Date(0),
704
+ lastReadAt: toDate(raw.last_read_at),
705
+ url: raw.subject.url ?? raw.url,
706
+ ...latestComment ? { latestComment } : {},
707
+ raw
708
+ };
709
+ }
710
+ function toLabel(raw) {
711
+ return {
712
+ name: raw.name,
713
+ colour: raw.color ?? void 0,
714
+ description: raw.description ?? void 0
715
+ };
716
+ }
717
+ function toLabels(labels) {
718
+ return (labels ?? []).flatMap((label) => {
719
+ if (typeof label === "string") return [{ name: label }];
720
+ return label.name ? [{
721
+ name: label.name,
722
+ colour: label.color ?? void 0,
723
+ description: label.description ?? void 0
724
+ }] : [];
725
+ });
726
+ }
727
+ function toReviewers(instance, raw) {
728
+ const users = (raw.requested_reviewers ?? []).flatMap((user) => {
729
+ const actor = toActor(instance, user);
730
+ return actor ? [{
731
+ actor,
732
+ state: "pending",
733
+ stateRaw: "requested"
734
+ }] : [];
735
+ });
736
+ const teams = (raw.requested_teams ?? []).map((team) => ({
737
+ actor: {
738
+ forge: FORGE,
739
+ instance,
740
+ login: team.slug,
741
+ id: String(team.id),
742
+ name: team.name,
743
+ url: team.html_url,
744
+ typeRaw: "Team",
745
+ isBotHint: false
746
+ },
747
+ state: "pending",
748
+ stateRaw: "requested",
749
+ isTeam: true
750
+ }));
751
+ return [...users, ...teams];
752
+ }
753
+ /** Builds a thread from an issue, a pull request, or a pull request as returned by the issues API. */
754
+ function toThread(ref, raw) {
755
+ const kind = raw.pull_request || raw.head ? "pull_request" : ref.kind;
756
+ return {
757
+ ref: {
758
+ ...ref,
759
+ kind,
760
+ externalId: raw.node_id ?? ref.externalId
761
+ },
762
+ kind,
763
+ title: raw.title,
764
+ body: raw.body ?? void 0,
765
+ state: toThreadState(raw),
766
+ stateRaw: raw.state,
767
+ stateReason: raw.state_reason ?? void 0,
768
+ isDraft: raw.draft ?? false,
769
+ author: toActor(ref.instance, raw.user),
770
+ ...toAuthorAssociation(raw.author_association),
771
+ assignees: (raw.assignees ?? []).flatMap((user) => toActor(ref.instance, user) ?? []),
772
+ reviewers: toReviewers(ref.instance, raw),
773
+ labels: toLabels(raw.labels),
774
+ url: raw.html_url,
775
+ createdAt: toDate(raw.created_at),
776
+ updatedAt: toDate(raw.updated_at),
777
+ closedAt: toDate(raw.closed_at),
778
+ mergedAt: toDate(raw.merged_at ?? raw.pull_request?.merged_at),
779
+ mergedBy: toActor(ref.instance, raw.merged_by),
780
+ lastActivityAt: toDate(raw.updated_at),
781
+ locked: raw.locked,
782
+ commentCount: raw.comments,
783
+ milestone: toMilestone(raw.milestone),
784
+ issueType: toIssueType(raw.type),
785
+ reactions: toReactions(raw.reactions),
786
+ branches: raw.head && raw.base ? {
787
+ head: {
788
+ ref: raw.head.ref,
789
+ sha: raw.head.sha,
790
+ repo: raw.head.repo ? toRepoRef(ref.instance, raw.head.repo) : void 0
791
+ },
792
+ base: {
793
+ ref: raw.base.ref,
794
+ sha: raw.base.sha
795
+ },
796
+ mergeCommitSha: raw.merge_commit_sha ?? void 0
797
+ } : void 0,
798
+ stats: toPullStats({
799
+ additions: raw.additions,
800
+ deletions: raw.deletions,
801
+ changedFileCount: raw.changed_files,
802
+ commitCount: raw.commits
803
+ }),
804
+ raw
805
+ };
806
+ }
807
+ function toComment(thread, raw) {
808
+ return {
809
+ ref: {
810
+ forge: FORGE,
811
+ instance: thread.instance,
812
+ thread,
813
+ id: String(raw.id)
814
+ },
815
+ ...commentFields(thread.instance, raw)
816
+ };
817
+ }
818
+ function toCommitComment(commit, raw) {
819
+ return {
820
+ ref: {
821
+ forge: FORGE,
822
+ instance: commit.instance,
823
+ commit,
824
+ id: String(raw.id)
825
+ },
826
+ ...commentFields(commit.instance, raw)
827
+ };
828
+ }
829
+ function commentFields(instance, raw) {
830
+ return {
831
+ body: raw.body ?? "",
832
+ author: toActor(instance, raw.user),
833
+ ...toAuthorAssociation(raw.author_association),
834
+ createdAt: toDate(raw.created_at),
835
+ updatedAt: toDate(raw.updated_at),
836
+ url: raw.html_url,
837
+ reactions: toReactions(raw.reactions),
838
+ raw
839
+ };
840
+ }
841
+ const EVENT_KINDS = {
842
+ "commented": "comment",
843
+ "reviewed": "review",
844
+ "line_commented": "review_comment",
845
+ "review_requested": "assignment",
846
+ "review_request_removed": "assignment",
847
+ "committed": "commit",
848
+ "labeled": "label",
849
+ "unlabeled": "label",
850
+ "closed": "state_change",
851
+ "reopened": "state_change",
852
+ "merged": "state_change",
853
+ "convert_to_draft": "state_change",
854
+ "ready_for_review": "state_change",
855
+ "assigned": "assignment",
856
+ "unassigned": "assignment",
857
+ "mentioned": "mention",
858
+ "cross-referenced": "referenced",
859
+ "referenced": "referenced",
860
+ "reaction": "reaction"
861
+ };
862
+ function toEventKind(event) {
863
+ return EVENT_KINDS[event ?? ""] ?? "other";
864
+ }
865
+ function summarise(entry, kind, actor) {
866
+ const who = actor?.login ?? "someone";
867
+ switch (kind) {
868
+ case "comment": return `${who} commented`;
869
+ case "review": return `${who} reviewed (${entry.state ?? "commented"})`;
870
+ case "review_comment": return `${who} commented on a line`;
871
+ case "commit": return `${entry.author?.name ?? who} committed ${entry.sha?.slice(0, 7) ?? "a commit"}`;
872
+ case "label": return `${who} ${entry.event === "unlabeled" ? "removed" : "added"} label ${entry.label?.name ?? ""}`.trim();
873
+ case "state_change": return `${who} ${entry.event ?? "changed state"}`;
874
+ case "referenced": return `${who} referenced this`;
875
+ case "assignment":
876
+ if (entry.event === "review_requested" || entry.event === "review_request_removed") return `${who} ${entry.event === "review_requested" ? "requested review from" : "removed the review request for"} ${entry.requested_reviewer?.login ?? ""}`.trim();
877
+ return `${who} ${entry.event === "unassigned" ? "unassigned" : "assigned"} ${entry.assignee?.login ?? ""}`.trim();
878
+ default: return `${who} ${entry.event ?? "acted"}`;
879
+ }
880
+ }
881
+ /** A `cross-referenced` entry names the thread that mentioned this one; a `referenced` entry names a commit. */
882
+ function crossReference(instance, thread, entry) {
883
+ const source = entry.source?.issue;
884
+ if (source) {
885
+ const repo = source.repository ? toRepoRef(instance, source.repository) : thread.repo;
886
+ return {
887
+ type: "referenced",
888
+ from: {
889
+ forge: FORGE,
890
+ instance,
891
+ repo,
892
+ kind: source.pull_request ? "pull_request" : "issue",
893
+ number: String(source.number)
894
+ },
895
+ fromRepo: repo
896
+ };
897
+ }
898
+ return entry.commit_id ? {
899
+ type: "referenced",
900
+ from: {
901
+ forge: FORGE,
902
+ instance,
903
+ repo: thread.repo,
904
+ sha: entry.commit_id
905
+ },
906
+ fromRepo: thread.repo
907
+ } : { type: "referenced" };
908
+ }
909
+ function timelineDetail(instance, thread, entry, kind) {
910
+ switch (kind) {
911
+ case "comment": return {
912
+ type: "comment",
913
+ comment: entry.id !== void 0 ? {
914
+ forge: FORGE,
915
+ instance,
916
+ thread,
917
+ id: String(entry.id)
918
+ } : void 0,
919
+ body: entry.body ?? void 0
920
+ };
921
+ case "review": return {
922
+ type: "review",
923
+ state: reviewState(entry.state),
924
+ stateRaw: entry.state,
925
+ body: entry.body ?? void 0,
926
+ review: entry.id !== void 0 ? {
927
+ forge: FORGE,
928
+ instance,
929
+ thread,
930
+ id: String(entry.id)
931
+ } : void 0
932
+ };
933
+ case "label": return entry.label ? {
934
+ type: "label",
935
+ label: entry.label.name
936
+ } : void 0;
937
+ case "assignment": return {
938
+ type: "assignment",
939
+ assignee: toActor(instance, entry.assignee ?? entry.requested_reviewer)
940
+ };
941
+ case "referenced": return crossReference(instance, thread, entry);
942
+ case "state_change": return entry.event === "convert_to_draft" || entry.event === "ready_for_review" ? {
943
+ type: "state_change",
944
+ state: "open",
945
+ draft: entry.event === "convert_to_draft"
946
+ } : {
947
+ type: "state_change",
948
+ state: entry.event === "merged" ? "merged" : entry.event === "closed" ? "closed" : "open",
949
+ reason: entry.state_reason ?? void 0
950
+ };
951
+ default: return;
952
+ }
953
+ }
954
+ function toEvent(instance, thread, entry, source = "poll") {
955
+ const kind = toEventKind(entry.event);
956
+ const actor = toActor(instance, entry.actor ?? entry.user);
957
+ return {
958
+ forge: FORGE,
959
+ instance,
960
+ id: String(entry.node_id ?? entry.id ?? entry.sha ?? `${thread.number ?? ""}-${entry.event}-${entry.created_at}`),
961
+ kind,
962
+ kindRaw: entry.event,
963
+ detail: timelineDetail(instance, thread, entry, kind),
964
+ summary: summarise(entry, kind, actor),
965
+ ...eventTime(toDate(entry.created_at ?? entry.submitted_at ?? entry.author?.date ?? entry.committer?.date), /* @__PURE__ */ new Date(0)),
966
+ actor,
967
+ repo: thread.repo,
968
+ thread,
969
+ source,
970
+ payload: entry
971
+ };
972
+ }
973
+ function statusState(state) {
974
+ return state === "success" ? "success" : state === "pending" ? "pending" : state === "failure" || state === "error" ? "failure" : "unknown";
975
+ }
976
+ const ACTIONS_JOB_URL = /\/actions\/runs\/(\d+)\/job\/\d+$/;
977
+ function toCheckRun(repo, raw) {
978
+ const runId = raw.html_url?.match(ACTIONS_JOB_URL)?.[1];
979
+ return {
980
+ ref: {
981
+ forge: FORGE,
982
+ instance: repo.instance,
983
+ repo,
984
+ id: String(raw.id),
985
+ type: "check_run",
986
+ ...raw.app?.slug ? { app: raw.app.slug } : {}
987
+ },
988
+ name: raw.name,
989
+ state: checkRunState(raw.status, raw.conclusion),
990
+ stateRaw: raw.status,
991
+ conclusionRaw: raw.conclusion ?? void 0,
992
+ url: raw.html_url ?? raw.details_url ?? void 0,
993
+ startedAt: toDate(raw.started_at),
994
+ completedAt: toDate(raw.completed_at),
995
+ ...runId ? { run: {
996
+ forge: FORGE,
997
+ instance: repo.instance,
998
+ repo,
999
+ id: runId
1000
+ } } : {},
1001
+ raw
1002
+ };
1003
+ }
1004
+ function toStatusCheck(repo, raw) {
1005
+ const state = statusState(raw.state);
1006
+ return {
1007
+ ref: {
1008
+ forge: FORGE,
1009
+ instance: repo.instance,
1010
+ repo,
1011
+ id: String(raw.id),
1012
+ type: "status"
1013
+ },
1014
+ name: raw.context,
1015
+ state,
1016
+ stateRaw: raw.state,
1017
+ url: raw.target_url ?? void 0,
1018
+ startedAt: toDate(raw.created_at),
1019
+ completedAt: state === "pending" ? void 0 : toDate(raw.updated_at),
1020
+ raw
1021
+ };
1022
+ }
1023
+ function toRelease(repo, raw) {
1024
+ const ref = {
1025
+ forge: FORGE,
1026
+ instance: repo.instance,
1027
+ repo,
1028
+ id: String(raw.id),
1029
+ tag: raw.tag_name
1030
+ };
1031
+ return {
1032
+ ref,
1033
+ name: raw.name ?? void 0,
1034
+ tag: raw.tag_name,
1035
+ body: raw.body ?? void 0,
1036
+ isDraft: raw.draft,
1037
+ isPrerelease: raw.prerelease,
1038
+ immutable: raw.immutable,
1039
+ author: toActor(repo.instance, raw.author),
1040
+ publishedAt: toDate(raw.published_at),
1041
+ createdAt: toDate(raw.created_at),
1042
+ url: raw.html_url,
1043
+ assets: raw.assets?.map((asset) => ({
1044
+ ...asset.id === void 0 ? {} : { ref: {
1045
+ forge: FORGE,
1046
+ instance: repo.instance,
1047
+ repo,
1048
+ release: ref,
1049
+ id: String(asset.id)
1050
+ } },
1051
+ name: asset.name,
1052
+ url: asset.browser_download_url,
1053
+ size: asset.size,
1054
+ downloadCount: asset.download_count,
1055
+ contentType: asset.content_type
1056
+ })),
1057
+ raw
1058
+ };
1059
+ }
1060
+ function toSeverity(raw) {
1061
+ switch (raw?.toLowerCase()) {
1062
+ case "critical": return "critical";
1063
+ case "high":
1064
+ case "error": return "high";
1065
+ case "medium":
1066
+ case "moderate":
1067
+ case "warning": return "medium";
1068
+ case "low":
1069
+ case "note": return "low";
1070
+ default: return "unknown";
1071
+ }
1072
+ }
1073
+ function alertState(raw) {
1074
+ return raw === "open" ? "open" : raw === "fixed" ? "fixed" : raw === "dismissed" || raw === "auto_dismissed" ? "dismissed" : "unknown";
1075
+ }
1076
+ function toDependabotAlert(repo, raw) {
1077
+ const severityRaw = raw.security_vulnerability?.severity ?? raw.security_advisory?.severity;
1078
+ const pkg = raw.dependency?.package;
1079
+ return {
1080
+ ref: {
1081
+ forge: FORGE,
1082
+ instance: repo.instance,
1083
+ repo,
1084
+ id: String(raw.number),
1085
+ kind: "dependency",
1086
+ severityRaw
1087
+ },
1088
+ kind: "dependency",
1089
+ kindRaw: "dependabot",
1090
+ severity: toSeverity(severityRaw),
1091
+ severityRaw,
1092
+ state: alertState(raw.state),
1093
+ stateRaw: raw.state,
1094
+ title: raw.security_advisory?.summary ?? `Vulnerable dependency ${pkg?.name ?? ""}`.trim(),
1095
+ ...pkg ? { package: {
1096
+ ecosystem: pkg.ecosystem,
1097
+ name: pkg.name,
1098
+ vulnerableRange: raw.security_vulnerability?.vulnerable_version_range,
1099
+ fixedIn: raw.security_vulnerability?.first_patched_version?.identifier
1100
+ } } : {},
1101
+ url: raw.html_url,
1102
+ createdAt: toDate(raw.created_at),
1103
+ updatedAt: toDate(raw.updated_at),
1104
+ dismissedAt: toDate(raw.dismissed_at),
1105
+ raw
1106
+ };
1107
+ }
1108
+ function toCodeScanningAlert(repo, raw) {
1109
+ const severityRaw = raw.rule?.security_severity_level ?? raw.rule?.severity ?? void 0;
1110
+ return {
1111
+ ref: {
1112
+ forge: FORGE,
1113
+ instance: repo.instance,
1114
+ repo,
1115
+ id: String(raw.number),
1116
+ kind: "code_scanning",
1117
+ severityRaw
1118
+ },
1119
+ kind: "code_scanning",
1120
+ kindRaw: raw.tool?.name ?? "code_scanning",
1121
+ severity: toSeverity(severityRaw),
1122
+ severityRaw,
1123
+ state: alertState(raw.state),
1124
+ stateRaw: raw.state,
1125
+ title: raw.rule?.description ?? raw.rule?.name ?? raw.rule?.id ?? "Code scanning alert",
1126
+ url: raw.html_url,
1127
+ createdAt: toDate(raw.created_at),
1128
+ updatedAt: toDate(raw.updated_at),
1129
+ dismissedAt: toDate(raw.dismissed_at),
1130
+ raw
1131
+ };
1132
+ }
1133
+ /** Secret scanning reports no severity. A revoked secret is fixed; any other resolution dismisses the alert. */
1134
+ function toSecretScanningAlert(repo, raw) {
1135
+ const state = raw.state === "open" ? "open" : raw.state === "resolved" ? raw.resolution === "revoked" ? "fixed" : "dismissed" : "unknown";
1136
+ return {
1137
+ ref: {
1138
+ forge: FORGE,
1139
+ instance: repo.instance,
1140
+ repo,
1141
+ id: String(raw.number),
1142
+ kind: "secret"
1143
+ },
1144
+ kind: "secret",
1145
+ kindRaw: raw.secret_type ?? "secret_scanning",
1146
+ severity: "unknown",
1147
+ state,
1148
+ stateRaw: raw.resolution ? `${raw.state}:${raw.resolution}` : raw.state,
1149
+ title: raw.secret_type_display_name ?? raw.secret_type ?? "Secret scanning alert",
1150
+ url: raw.html_url,
1151
+ createdAt: toDate(raw.created_at),
1152
+ updatedAt: toDate(raw.updated_at),
1153
+ dismissedAt: state === "dismissed" ? toDate(raw.resolved_at) : void 0,
1154
+ raw
1155
+ };
1156
+ }
1157
+ /** A private vulnerability report in triage, or a draft, is open; a published advisory is fixed; a closed or withdrawn one is dismissed. */
1158
+ function toRepositoryAdvisory(repo, raw) {
1159
+ const state = raw.state === "triage" || raw.state === "draft" ? "open" : raw.state === "published" ? "fixed" : raw.state === "closed" || raw.state === "withdrawn" ? "dismissed" : "unknown";
1160
+ const severityRaw = raw.severity ?? void 0;
1161
+ const vulnerability = raw.vulnerabilities?.find((item) => item.package?.name);
1162
+ return {
1163
+ ref: {
1164
+ forge: FORGE,
1165
+ instance: repo.instance,
1166
+ repo,
1167
+ id: raw.ghsa_id,
1168
+ kind: "advisory",
1169
+ severityRaw
1170
+ },
1171
+ kind: "advisory",
1172
+ kindRaw: "repository_advisory",
1173
+ severity: toSeverity(severityRaw),
1174
+ severityRaw,
1175
+ state,
1176
+ stateRaw: raw.state,
1177
+ title: raw.summary,
1178
+ ...vulnerability?.package?.name ? { package: {
1179
+ ecosystem: vulnerability.package.ecosystem,
1180
+ name: vulnerability.package.name,
1181
+ vulnerableRange: vulnerability.vulnerable_version_range ?? void 0,
1182
+ fixedIn: vulnerability.patched_versions ?? void 0
1183
+ } } : {},
1184
+ url: raw.html_url,
1185
+ createdAt: toDate(raw.created_at),
1186
+ updatedAt: toDate(raw.updated_at),
1187
+ dismissedAt: state === "dismissed" ? toDate(raw.withdrawn_at ?? raw.closed_at) : void 0,
1188
+ raw
1189
+ };
1190
+ }
1191
+ function toReviewComment(thread, raw, reviewThread) {
1192
+ return {
1193
+ ref: {
1194
+ forge: FORGE,
1195
+ instance: thread.instance,
1196
+ thread,
1197
+ id: String(raw.id)
1198
+ },
1199
+ body: raw.body ?? "",
1200
+ author: toActor(thread.instance, raw.user),
1201
+ path: raw.path,
1202
+ line: raw.line ?? raw.original_line ?? void 0,
1203
+ side: raw.side?.toLowerCase() === "left" ? "left" : raw.side ? "right" : void 0,
1204
+ inReplyTo: raw.in_reply_to_id === null || raw.in_reply_to_id === void 0 ? void 0 : String(raw.in_reply_to_id),
1205
+ thread: reviewThread,
1206
+ createdAt: toDate(raw.created_at),
1207
+ url: raw.html_url,
1208
+ raw
1209
+ };
1210
+ }
1211
+ function toReview(thread, raw, comments) {
1212
+ return {
1213
+ ref: {
1214
+ forge: FORGE,
1215
+ instance: thread.instance,
1216
+ thread,
1217
+ id: String(raw.id)
1218
+ },
1219
+ author: toActor(thread.instance, raw.user),
1220
+ state: reviewState(raw.state),
1221
+ stateRaw: raw.state,
1222
+ body: raw.body || void 0,
1223
+ submittedAt: toDate(raw.submitted_at ?? void 0),
1224
+ comments,
1225
+ url: raw.html_url,
1226
+ raw
1227
+ };
1228
+ }
1229
+ function toWorkflowRun(repo, raw) {
1230
+ return {
1231
+ ref: {
1232
+ forge: FORGE,
1233
+ instance: repo.instance,
1234
+ repo,
1235
+ id: String(raw.id)
1236
+ },
1237
+ name: raw.name || raw.display_title || String(raw.id),
1238
+ state: checkRunState(raw.status ?? "queued", raw.conclusion),
1239
+ stateRaw: raw.status ?? "unknown",
1240
+ number: raw.run_number === void 0 ? void 0 : String(raw.run_number),
1241
+ eventRaw: raw.event,
1242
+ branch: raw.head_branch ?? void 0,
1243
+ sha: raw.head_sha,
1244
+ url: raw.html_url,
1245
+ actor: toActor(repo.instance, raw.actor),
1246
+ createdAt: toDate(raw.created_at),
1247
+ startedAt: toDate(raw.run_started_at),
1248
+ completedAt: raw.status === "completed" ? toDate(raw.updated_at) : void 0,
1249
+ raw
1250
+ };
1251
+ }
1252
+ function toWorkflowJob(run, raw) {
1253
+ return {
1254
+ ref: {
1255
+ forge: FORGE,
1256
+ instance: run.instance,
1257
+ repo: run.repo,
1258
+ id: String(raw.id),
1259
+ run
1260
+ },
1261
+ name: raw.name,
1262
+ state: checkRunState(raw.status ?? "queued", raw.conclusion),
1263
+ stateRaw: raw.status ?? "unknown",
1264
+ url: raw.html_url ?? void 0,
1265
+ startedAt: toDate(raw.started_at),
1266
+ completedAt: toDate(raw.completed_at),
1267
+ raw
1268
+ };
1269
+ }
1270
+ function toChangedFile(raw) {
1271
+ return {
1272
+ path: raw.filename,
1273
+ previousPath: raw.previous_filename,
1274
+ status: toFileStatus(raw.status),
1275
+ statusRaw: raw.status,
1276
+ additions: raw.additions,
1277
+ deletions: raw.deletions,
1278
+ patch: raw.patch,
1279
+ sha: raw.sha
1280
+ };
1281
+ }
1282
+ function toCommit(repo, raw) {
1283
+ return {
1284
+ ref: {
1285
+ forge: FORGE,
1286
+ instance: repo.instance,
1287
+ repo,
1288
+ sha: raw.sha
1289
+ },
1290
+ sha: raw.sha,
1291
+ message: raw.commit.message,
1292
+ author: {
1293
+ actor: toActor(repo.instance, raw.author),
1294
+ name: raw.commit.author?.name,
1295
+ email: raw.commit.author?.email,
1296
+ date: toDate(raw.commit.author?.date)
1297
+ },
1298
+ committer: {
1299
+ actor: toActor(repo.instance, raw.committer),
1300
+ name: raw.commit.committer?.name,
1301
+ email: raw.commit.committer?.email,
1302
+ date: toDate(raw.commit.committer?.date)
1303
+ },
1304
+ parents: raw.parents?.map((parent) => parent.sha) ?? [],
1305
+ url: raw.html_url,
1306
+ ...raw.stats ? { stats: {
1307
+ additions: raw.stats.additions ?? 0,
1308
+ deletions: raw.stats.deletions ?? 0,
1309
+ total: raw.stats.total
1310
+ } } : {},
1311
+ ...raw.files ? { files: raw.files.map(toChangedFile) } : {},
1312
+ raw
1313
+ };
1314
+ }
1315
+ /** A commit from the Git database API, which matches no accounts. */
1316
+ function toGitCommit(repo, raw) {
1317
+ return {
1318
+ ref: {
1319
+ forge: FORGE,
1320
+ instance: repo.instance,
1321
+ repo,
1322
+ sha: raw.sha
1323
+ },
1324
+ sha: raw.sha,
1325
+ message: raw.message,
1326
+ author: {
1327
+ name: raw.author?.name,
1328
+ email: raw.author?.email,
1329
+ date: toDate(raw.author?.date)
1330
+ },
1331
+ committer: {
1332
+ name: raw.committer?.name,
1333
+ email: raw.committer?.email,
1334
+ date: toDate(raw.committer?.date)
1335
+ },
1336
+ parents: raw.parents?.map((parent) => parent.sha) ?? [],
1337
+ url: raw.html_url,
1338
+ raw
1339
+ };
1340
+ }
1341
+ function toBranch(raw, defaultBranch) {
1342
+ return {
1343
+ name: raw.name,
1344
+ sha: raw.commit.sha,
1345
+ isDefault: defaultBranch === void 0 ? void 0 : raw.name === defaultBranch,
1346
+ isProtected: raw.protected,
1347
+ raw
1348
+ };
1349
+ }
1350
+ /** Merges rulesets with classic protection; `protection` is undefined when it's off or only an admin could read it. */
1351
+ function toBranchRules(branch, rules, protection, warnings) {
1352
+ const checks = /* @__PURE__ */ new Map();
1353
+ const add = (name, appId) => {
1354
+ const check = appId == null ? { name } : {
1355
+ name,
1356
+ appId: String(appId)
1357
+ };
1358
+ checks.set(`${check.appId ?? ""}\0${name}`, check);
1359
+ };
1360
+ const approvals = [];
1361
+ for (const rule of rules) {
1362
+ if (rule.type === "required_status_checks") for (const check of rule.parameters?.required_status_checks ?? []) add(check.context, check.integration_id);
1363
+ if (rule.type === "pull_request") approvals.push(rule.parameters?.required_approving_review_count ?? 0);
1364
+ }
1365
+ const classic = branch.protection?.enabled ? branch.protection.required_status_checks : void 0;
1366
+ if (classic && classic.enforcement_level !== "off") for (const check of classic.checks?.length ? classic.checks : classic.contexts?.map((context) => ({
1367
+ context,
1368
+ app_id: void 0
1369
+ })) ?? []) add(check.context, check.app_id);
1370
+ if (protection) approvals.push(protection.required_pull_request_reviews?.required_approving_review_count ?? 0);
1371
+ const known = protection || !branch.protection?.enabled;
1372
+ const pinned = new Set([...checks.values()].filter((check) => check.appId).map((check) => check.name));
1373
+ return {
1374
+ branch: branch.name,
1375
+ requiredChecks: [...checks.values()].filter((check) => check.appId || !pinned.has(check.name)),
1376
+ requiredApprovals: known ? Math.max(0, ...approvals) : approvals.length ? Math.max(...approvals) : void 0,
1377
+ ...warnings.length ? { warnings } : {},
1378
+ raw: {
1379
+ branch,
1380
+ rules,
1381
+ protection
1382
+ }
1383
+ };
1384
+ }
1385
+ function toTag(raw) {
1386
+ return {
1387
+ name: raw.name,
1388
+ sha: raw.commit.sha,
1389
+ raw
1390
+ };
1391
+ }
1392
+ const TREE_TYPES = {
1393
+ blob: "file",
1394
+ tree: "directory",
1395
+ commit: "submodule"
1396
+ };
1397
+ function toTreeEntry(raw) {
1398
+ return {
1399
+ path: raw.path,
1400
+ type: raw.mode === "120000" ? "symlink" : TREE_TYPES[raw.type ?? ""] ?? "file",
1401
+ sha: raw.sha,
1402
+ size: raw.size,
1403
+ mode: raw.mode
1404
+ };
1405
+ }
1406
+ function toWebhook(target, raw) {
1407
+ const nativeEvents = raw.events ?? [];
1408
+ return {
1409
+ ref: {
1410
+ forge: FORGE,
1411
+ instance: target.instance,
1412
+ target,
1413
+ id: String(raw.id)
1414
+ },
1415
+ url: raw.config?.url ?? "",
1416
+ events: eventKindsOf(GITHUB_NATIVE_EVENTS, nativeEvents),
1417
+ nativeEvents,
1418
+ active: raw.active ?? true,
1419
+ contentType: raw.config?.content_type === "form" ? "form" : "json",
1420
+ createdAt: toDate(raw.created_at),
1421
+ updatedAt: toDate(raw.updated_at),
1422
+ raw
1423
+ };
1424
+ }
1425
+ function toWebhookDelivery(hook, raw) {
1426
+ const status = raw.status_code ?? 0;
1427
+ return {
1428
+ ref: {
1429
+ forge: FORGE,
1430
+ instance: hook.instance,
1431
+ hook,
1432
+ id: String(raw.id),
1433
+ guid: raw.guid
1434
+ },
1435
+ event: raw.action ? `${raw.event}.${raw.action}` : raw.event ?? "",
1436
+ status,
1437
+ ok: status >= 200 && status < 300,
1438
+ deliveredAt: toDate(raw.delivered_at),
1439
+ duration: raw.duration,
1440
+ raw
1441
+ };
1442
+ }
1443
+ function graphqlUrl(baseUrl) {
1444
+ const url = new URL(baseUrl);
1445
+ if (url.host === "api.github.com") return "https://api.github.com/graphql";
1446
+ return `${url.origin}${url.pathname.replace(/\/v3\/?$/, "")}/graphql`;
1447
+ }
1448
+ /**
1449
+ * A failed GraphQL response as an error: `InsufficientScopeError` when the token lacks a scope a field needs, and
1450
+ * `RateLimitedError` for a rate limit, which GitHub reports with a `200`.
1451
+ */
1452
+ function graphqlError(operationName, errors, url, context, response) {
1453
+ const message = `GraphQL ${operationName ?? "request"} failed: ${errors?.map((error) => error.message).join("; ") || "Empty GraphQL response"}`;
1454
+ const body = JSON.stringify(errors ?? null).slice(0, 512);
1455
+ const errorContext = {
1456
+ forge: FORGE,
1457
+ instance: context.instance,
1458
+ url,
1459
+ method: "POST"
1460
+ };
1461
+ const secondary = errors?.some((error) => isSecondaryRateLimit(error.message)) ?? false;
1462
+ if (secondary || errors?.some((error) => error.type === "RATE_LIMITED")) {
1463
+ const budget = response && rateLimitOf(response);
1464
+ const resetAt = response && (rateLimitReset(response, budget) ?? (secondary ? void 0 : budget?.resetAt));
1465
+ return new RateLimitedError(message, 200, body, {
1466
+ ...errorContext,
1467
+ resetAt,
1468
+ secondary
1469
+ });
1470
+ }
1471
+ const scopeError = errors?.find((error) => error.type === "INSUFFICIENT_SCOPES");
1472
+ if (!scopeError) return new ForgeApiError(message, 200, body, errorContext);
1473
+ return new InsufficientScopeError(message, 200, body, {
1474
+ ...errorContext,
1475
+ acceptedScopes: quotedScopes(scopeError.message.match(/requires one of the following scopes: \[([^\]]*)\]/)?.[1]),
1476
+ grantedScopes: quotedScopes(scopeError.message.match(/has only been granted the: \[([^\]]*)\]/)?.[1])
1477
+ });
1478
+ }
1479
+ function quotedScopes(list) {
1480
+ return list === void 0 ? void 0 : [...list.matchAll(/'([^']+)'/g)].map((match) => match[1]);
1481
+ }
1482
+ const OPERATION_TYPES = /* @__PURE__ */ new Set([
1483
+ "query",
1484
+ "mutation",
1485
+ "subscription"
1486
+ ]);
1487
+ /** The operations a GraphQL document declares, read from its top level so that fields, variables, strings and comments don't count. */
1488
+ function graphqlOperations(document) {
1489
+ const operations = [];
1490
+ let depth = 0;
1491
+ let definitionStart = true;
1492
+ let awaitingName;
1493
+ for (const [token] of document.matchAll(/"""(?:\\"""|[\s\S])*?"""|"(?:\\.|[^"\\\n\r])*"|#[^\n\r]*|[{}()]|[$@]?[_a-z]\w*/gi)) {
1494
+ if (token[0] === "\"" || token[0] === "#") continue;
1495
+ if (token === "{" || token === "(") {
1496
+ if (depth === 0 && definitionStart && token === "{") operations.push({ type: "query" });
1497
+ depth++;
1498
+ definitionStart = false;
1499
+ awaitingName = void 0;
1500
+ } else if (token === "}" || token === ")") {
1501
+ depth--;
1502
+ definitionStart = depth === 0 && token === "}";
1503
+ } else if (depth === 0) {
1504
+ if (awaitingName && /^[_a-z]/i.test(token)) awaitingName.name = token;
1505
+ awaitingName = definitionStart && OPERATION_TYPES.has(token) ? { type: token } : void 0;
1506
+ if (awaitingName) operations.push(awaitingName);
1507
+ definitionStart = false;
1508
+ }
1509
+ }
1510
+ return operations;
1511
+ }
1512
+ function createGraphQLClient(fetcher, url, context) {
1513
+ return async (document, variables, options) => {
1514
+ const query = typeof document === "string" ? (await import("./graphql-DG5aJBT3-DceyFYdM.js"))[document] : document.query;
1515
+ const operationName = graphqlOperations(query)[0]?.name;
1516
+ const { data, response } = await fetcher.json(url, {
1517
+ method: "POST",
1518
+ json: {
1519
+ query,
1520
+ variables,
1521
+ operationName
1522
+ },
1523
+ signal: options?.signal
1524
+ });
1525
+ if (data.errors?.length || !data.data) throw graphqlError(operationName, data.errors, url, context, response);
1526
+ return data.data;
1527
+ };
1528
+ }
1529
+ const SIGNATURE_HEADER = "x-hub-signature-256";
1530
+ function verifyGitHubSignature(delivery, secret) {
1531
+ return verifyHmacSignature(delivery, secret, {
1532
+ header: SIGNATURE_HEADER,
1533
+ prefix: "sha256="
1534
+ });
1535
+ }
1536
+ const githubWebhooks = ({ options, instance }) => ({
1537
+ events: GITHUB_WEBHOOK_EVENTS,
1538
+ verify: (delivery) => verifyGitHubSignature(delivery, options.webhookSecret),
1539
+ translate: async (delivery) => (await import("./events-CeChclTf-CX-gD8oy.js")).translateGitHubWebhook(instance, delivery)
1540
+ });
1541
+ const DISCUSSION_CLOSE_REASONS = {
1542
+ completed: "resolved",
1543
+ duplicate: "duplicate"
1544
+ };
1545
+ const COLLABORATOR_PERMISSIONS = {
1546
+ read: "pull",
1547
+ write: "push"
1548
+ };
1549
+ /** GitHub Enterprise Server versions that support marking a notification done. */
1550
+ const GHES_MARK_DONE = "3.13";
1551
+ /** GitHub Enterprise Server versions with the Dependabot alerts REST API. */
1552
+ const GHES_DEPENDABOT_ALERTS = "3.8";
1553
+ const GRAPHQL_BATCH = 20;
1554
+ const LOCK_REASONS = {
1555
+ off_topic: "off-topic",
1556
+ too_heated: "too heated",
1557
+ resolved: "resolved",
1558
+ spam: "spam"
1559
+ };
1560
+ const REVIEW_CONTEXT_TTL = 3e5;
1561
+ const POLL_DELAYS = [
1562
+ 500,
1563
+ 1e3,
1564
+ 2e3
1565
+ ];
1566
+ const CONTRIBUTOR_STATS_DELAYS = [
1567
+ 500,
1568
+ 1e3,
1569
+ 2e3,
1570
+ 4e3,
1571
+ 8e3
1572
+ ];
1573
+ const ISSUE_LIKE = {
1574
+ issue: true,
1575
+ pull_request: true,
1576
+ discussion: true
1577
+ };
1578
+ function repoPath(repo) {
1579
+ return `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
1580
+ }
1581
+ function branchPath(branch) {
1582
+ return branch.split("/").map(encodeURIComponent).join("/");
1583
+ }
1584
+ const ZERO_OID = "0".repeat(40);
1585
+ /**
1586
+ * GitHub's refusal to move a branch that is no longer at the commit a write built on, as a 409 `BranchMovedError`,
1587
+ * and to delete a file that does not exist, as a 404 `NotFoundError`, whatever the status of the response.
1588
+ */
1589
+ function commitError(error) {
1590
+ if (!(error instanceof ForgeApiError) || error.constructor !== ForgeApiError) return error;
1591
+ const text = `${error.message} ${error.body}`;
1592
+ const context = {
1593
+ forge: error.forge,
1594
+ instance: error.instance,
1595
+ url: error.url,
1596
+ method: error.method
1597
+ };
1598
+ if (/Expected branch to point to|not a fast[- ]forward/i.test(text)) return new BranchMovedError("The branch no longer points at the commit the change was made on", 409, error.body, context, { cause: error });
1599
+ if (/requested for deletion which does not exist/i.test(text)) return new NotFoundError("A file to delete does not exist", 404, error.body, context, { cause: error });
1600
+ return error;
1601
+ }
1602
+ /** GitHub's `422` for a head that moved since `expected_head_sha`, as `BranchMovedError`, and for a conflict, as `MergeConflictError`. */
1603
+ function updateBranchError(error) {
1604
+ if (!(error instanceof ForgeApiError) || error.constructor !== ForgeApiError || error.status !== 422) return error;
1605
+ const context = {
1606
+ forge: error.forge,
1607
+ instance: error.instance,
1608
+ url: error.url,
1609
+ method: error.method
1610
+ };
1611
+ if (/expected head sha/i.test(error.body)) return new BranchMovedError("The head branch no longer points at the expected sha", error.status, error.body, context, { cause: error });
1612
+ if (/conflict/i.test(error.body)) return new MergeConflictError("The head branch conflicts with its base", error.status, error.body, context, { cause: error });
1613
+ return error;
1614
+ }
1615
+ function threadPath(ref) {
1616
+ switch (ref.kind) {
1617
+ case "pull_request": return `${repoPath(ref.repo)}/pulls/${encodeURIComponent(ref.number)}`;
1618
+ default: return `${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}`;
1619
+ }
1620
+ }
1621
+ function installationId(installation) {
1622
+ return typeof installation === "string" ? installation : installation.id;
1623
+ }
1624
+ /**
1625
+ * Free text as legacy search reads it: advanced search parses parentheses and
1626
+ * an unclosed quote as syntax, so those are dropped outside quoted phrases.
1627
+ */
1628
+ function advancedFreeText(text) {
1629
+ const parts = text.split("\"");
1630
+ if (parts.length % 2 === 0) {
1631
+ const unclosed = parts.pop();
1632
+ parts.push(`${parts.pop()} ${unclosed}`);
1633
+ }
1634
+ return parts.map((part, index) => index % 2 ? part : part.replace(/[()\s]+/g, " ")).join("\"").trim();
1635
+ }
1636
+ function setupGitHub({ options, baseUrl, instance, origin: context, fetcher, createFetcher, derive, state: credentials }) {
1637
+ const list = createListing(fetcher, "per_page");
1638
+ const auth = options.auth ?? { type: "anonymous" };
1639
+ /** GitHub GraphQL needs a credential, so anonymous providers stay on REST. */
1640
+ const anonymous = auth.type === "anonymous";
1641
+ /** An app without an installation reaches only the `/app` endpoints. */
1642
+ const appItself = auth.type === "app" && auth.installationId === void 0;
1643
+ const tokenKind = auth.type === "token" ? tokenKindOf(auth) : void 0;
1644
+ /** An installation, whether from app credentials or its token, acts as no account. */
1645
+ const installation = auth.type === "app" || tokenKind === "installation";
1646
+ /** GitHub serves notifications only to classic personal access tokens and OAuth app tokens. */
1647
+ const notificationsAuth = auth.type === "token" && (tokenKind === void 0 || tokenKind === "classic");
1648
+ const host = hostOf(baseUrl);
1649
+ /** GitHub Enterprise Server; `ghe.com` data residency hosts follow github.com. */
1650
+ const enterprise = host !== "api.github.com" && !isGheCom(host);
1651
+ const graphql = createGraphQLClient(fetcher, graphqlUrl(baseUrl), { instance });
1652
+ /**
1653
+ * Discussion notification subjects carry no URL. The repo's most recently
1654
+ * updated discussions are listed and matched on an exact, unique title.
1655
+ */
1656
+ async function resolveDiscussionNumbers(items) {
1657
+ const pending = items.filter((item) => item.subject.type === "thread" && item.subject.thread.kind === "discussion" && !item.subject.thread.number);
1658
+ if (!pending.length) return [];
1659
+ const repos = [...new Map(pending.map((item) => {
1660
+ const repo = item.subject.thread.repo;
1661
+ return [`${repo.owner}/${repo.name}`, repo];
1662
+ })).values()];
1663
+ let result;
1664
+ try {
1665
+ const { query, variables } = (await import("./graphql-DG5aJBT3-DceyFYdM.js")).recentDiscussionsQuery(repos);
1666
+ result = await graphql({ query }, variables);
1667
+ } catch (error) {
1668
+ if (error instanceof InsufficientScopeError || error instanceof ForgeApiError && error.status === 200) return [toWarning("discussion_unresolved", error)];
1669
+ throw error;
1670
+ }
1671
+ for (const item of pending) {
1672
+ const thread = item.subject.thread;
1673
+ const index = repos.findIndex((repo) => repo.owner === thread.repo.owner && repo.name === thread.repo.name);
1674
+ const matches = (result[`r${index}`]?.discussions.nodes ?? []).filter((node) => node.title === item.title);
1675
+ if (matches.length === 1) item.subject = {
1676
+ type: "thread",
1677
+ thread: {
1678
+ ...thread,
1679
+ number: String(matches[0].number),
1680
+ externalId: matches[0].id
1681
+ }
1682
+ };
1683
+ }
1684
+ return [];
1685
+ }
1686
+ /** When each polled path may be read again, from GitHub's `X-Poll-Interval`. */
1687
+ const nextPoll = /* @__PURE__ */ new Map();
1688
+ function throttledPage(path, listOptions, subject) {
1689
+ const at = nextPoll.get(path) ?? 0;
1690
+ const wait = at - Date.now();
1691
+ if (!isFirstPage(listOptions.cursor) || listOptions.force || wait <= 0) return;
1692
+ const warning = {
1693
+ code: "feed_throttled",
1694
+ message: `GitHub asked to wait ${Math.ceil(wait / 1e3)}s more before reading ${subject} again; no request was sent. Read it later, or pass force: true`
1695
+ };
1696
+ return {
1697
+ items: [],
1698
+ throttled: true,
1699
+ nextPollAt: new Date(at),
1700
+ warnings: [warning],
1701
+ ...listOptions.cursor?.etag ? { etag: listOptions.cursor.etag } : {}
1702
+ };
1703
+ }
1704
+ function recordPoll(path, cursor, response) {
1705
+ const interval = Number(response.headers.get("x-poll-interval"));
1706
+ if (!isFirstPage(cursor) || !(interval > 0)) return {};
1707
+ const at = Date.now() + interval * 1e3;
1708
+ nextPoll.set(path, at);
1709
+ return { nextPollAt: new Date(at) };
1710
+ }
1711
+ async function notificationPage(listOptions = {}) {
1712
+ const throttled = throttledPage("/notifications", listOptions, "notifications");
1713
+ if (throttled) return throttled;
1714
+ const result = await fetcher.json(listOptions.cursor?.nextUrl ?? "/notifications", {
1715
+ query: listOptions.cursor?.nextUrl ? void 0 : {
1716
+ all: listOptions.all ?? false,
1717
+ since: listOptions.since?.toISOString(),
1718
+ per_page: listOptions.perPage
1719
+ },
1720
+ etag: listOptions.cursor?.nextUrl ? void 0 : listOptions.cursor?.etag,
1721
+ signal: listOptions.signal
1722
+ });
1723
+ const items = (result.data ?? []).map((raw) => toNotification(instance, raw));
1724
+ const warnings = await resolveDiscussionNumbers(items);
1725
+ const etag = listOptions.cursor?.nextUrl ? void 0 : result.cursor?.etag ?? listOptions.cursor?.etag;
1726
+ return {
1727
+ items,
1728
+ cursor: result.cursor?.nextUrl ? result.cursor : void 0,
1729
+ ...etag ? { etag } : {},
1730
+ notModified: result.notModified,
1731
+ warnings: warnings.length ? warnings : void 0,
1732
+ ...recordPoll("/notifications", listOptions.cursor, result.response),
1733
+ ...rateLimitPart(result.response)
1734
+ };
1735
+ }
1736
+ async function discussionId(ref, options) {
1737
+ if (ref.externalId) return ref.externalId;
1738
+ return (await getDiscussion(ref, options)).ref.externalId;
1739
+ }
1740
+ async function getDiscussion(ref, options) {
1741
+ const discussion = (await graphql("DISCUSSION_THREAD", {
1742
+ owner: ref.repo.owner,
1743
+ name: ref.repo.name,
1744
+ number: Number(ref.number)
1745
+ }, options)).repository?.discussion;
1746
+ if (!discussion) throw new NotFoundError(`Discussion ${ref.number} not found`, 404, "", context);
1747
+ return (await import("./graphql-DG5aJBT3-DceyFYdM.js")).toDiscussionThread(ref, discussion);
1748
+ }
1749
+ async function discussionCommentPage(ref, listOptions) {
1750
+ const comments = (await graphql("DISCUSSION_COMMENTS", {
1751
+ owner: ref.repo.owner,
1752
+ name: ref.repo.name,
1753
+ number: Number(ref.number),
1754
+ after: listOptions.cursor?.token ?? null
1755
+ }, listOptions)).repository?.discussion?.comments;
1756
+ return {
1757
+ items: (comments?.nodes ?? []).flatMap((comment) => [{
1758
+ comment,
1759
+ isReply: false
1760
+ }, ...(comment.replies?.nodes ?? []).map((reply) => ({
1761
+ comment: reply,
1762
+ isReply: true
1763
+ }))]),
1764
+ cursor: comments?.pageInfo.hasNextPage && comments.pageInfo.endCursor ? { token: comments.pageInfo.endCursor } : void 0
1765
+ };
1766
+ }
1767
+ async function get(thread, options) {
1768
+ const ref = requireThread(thread, context);
1769
+ if (ref.kind === "discussion") return getDiscussion(ref, options);
1770
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
1771
+ const result = toThread(ref, data);
1772
+ if (ref.kind === "pull_request" && data.head?.sha) try {
1773
+ const checks = await headChecks(ref.repo, data.head.sha, options?.signal);
1774
+ result.checks = summariseChecks(checks.items.map((check) => check.state), data.html_url ? `${data.html_url}/checks` : void 0);
1775
+ if (checks.warnings?.length) result.warnings = [...result.warnings ?? [], ...checks.warnings];
1776
+ } catch (error) {
1777
+ if (!degradesToWarning(error)) throw error;
1778
+ result.warnings = [...result.warnings ?? [], toWarning("checks_unreadable", error, ref.number)];
1779
+ }
1780
+ return result;
1781
+ }
1782
+ async function headChecks(repo, sha, signal) {
1783
+ let checkRunTotal;
1784
+ const [runs, status] = await Promise.allSettled([Array.fromAsync(fetcher.items(`${repoPath(repo)}/commits/${sha}/check-runs`, {
1785
+ query: { per_page: 100 },
1786
+ select: (body, next) => {
1787
+ const { check_runs, total_count } = body;
1788
+ checkRunTotal = total_count;
1789
+ return {
1790
+ items: check_runs,
1791
+ next
1792
+ };
1793
+ },
1794
+ signal
1795
+ }), (raw) => toCheckRun(repo, raw)), Array.fromAsync(fetcher.items(`${repoPath(repo)}/commits/${sha}/status`, {
1796
+ query: { per_page: 100 },
1797
+ select: (body, next) => ({
1798
+ items: body.statuses,
1799
+ next
1800
+ }),
1801
+ signal
1802
+ }), (raw) => toStatusCheck(repo, raw))]);
1803
+ if (signal?.aborted) throw signal.reason;
1804
+ if (runs.status === "rejected" && status.status === "rejected") throw runs.reason;
1805
+ for (const result of [runs, status]) if (result.status === "rejected" && !degradesToWarning(result.reason)) throw result.reason;
1806
+ const statuses = status.status === "fulfilled" ? status.value : [];
1807
+ const total = runs.status === "fulfilled" && status.status === "fulfilled" && checkRunTotal !== void 0 ? checkRunTotal + statuses.length : void 0;
1808
+ return {
1809
+ items: [...runs.status === "fulfilled" ? runs.value : [], ...statuses],
1810
+ ...total !== void 0 ? { total } : {},
1811
+ warnings: [...runs.status === "rejected" ? [toWarning("checks_unreadable", runs.reason, "check-runs")] : [], ...status.status === "rejected" ? [toWarning("checks_unreadable", status.reason, "statuses")] : []]
1812
+ };
1813
+ }
1814
+ async function getMany(refs, options) {
1815
+ if (anonymous) return getManyConcurrently(refs, (ref, getOptions) => ref.kind === "discussion" ? Promise.reject(new UnsupportedOperationError("github does not read discussions without credentials", context)) : get(ref, getOptions), options);
1816
+ const results = Array.from({ length: refs.length });
1817
+ const batchable = [];
1818
+ for (const [index, ref] of refs.entries()) if (!isResolvedThread(ref)) results[index] = {
1819
+ ok: false,
1820
+ ref,
1821
+ warning: toWarning("thread_unresolved", /* @__PURE__ */ new Error("Thread ref has no number"), ref.number)
1822
+ };
1823
+ else batchable.push({
1824
+ index,
1825
+ ref
1826
+ });
1827
+ if (!batchable.length) return results;
1828
+ const g = await import("./graphql-DG5aJBT3-DceyFYdM.js");
1829
+ for (let start = 0; start < batchable.length; start += GRAPHQL_BATCH) {
1830
+ const chunk = batchable.slice(start, start + GRAPHQL_BATCH);
1831
+ const { query, variables } = g.threadsBatchQuery(chunk.map((item) => item.ref));
1832
+ const url = graphqlUrl(baseUrl);
1833
+ const { data, response } = await fetcher.json(url, {
1834
+ method: "POST",
1835
+ json: {
1836
+ query,
1837
+ variables,
1838
+ operationName: "ThreadsBatch"
1839
+ },
1840
+ signal: options?.signal
1841
+ });
1842
+ const failure = data.data ? void 0 : graphqlError("ThreadsBatch", data.errors, url, { instance }, response);
1843
+ if (failure instanceof RateLimitedError) throw failure;
1844
+ chunk.forEach(({ index, ref }, offset) => {
1845
+ const node = data.data?.[`t${offset}`];
1846
+ const discussion = ref.kind === "discussion" ? node?.discussion : void 0;
1847
+ const issueOrPullRequest = ref.kind === "discussion" ? void 0 : node?.issueOrPullRequest;
1848
+ if (failure) {
1849
+ results[index] = {
1850
+ ok: false,
1851
+ ref,
1852
+ warning: toWarning(failure instanceof InsufficientScopeError ? "insufficient_scope" : "thread_unreadable", failure, ref.number)
1853
+ };
1854
+ return;
1855
+ }
1856
+ if (!discussion && !issueOrPullRequest) {
1857
+ const error = data.errors?.find((error) => error.path?.[0] === `t${offset}`);
1858
+ if (error?.type === "INSUFFICIENT_SCOPES") {
1859
+ results[index] = {
1860
+ ok: false,
1861
+ ref,
1862
+ warning: toWarning("insufficient_scope", graphqlError("ThreadsBatch", [error], url, { instance }), ref.number)
1863
+ };
1864
+ return;
1865
+ }
1866
+ results[index] = {
1867
+ ok: false,
1868
+ ref,
1869
+ warning: {
1870
+ code: "thread_unreadable",
1871
+ message: error?.message ?? "Not found",
1872
+ subject: ref.number
1873
+ }
1874
+ };
1875
+ return;
1876
+ }
1877
+ results[index] = {
1878
+ ok: true,
1879
+ ref,
1880
+ thread: discussion ? g.toDiscussionThread(ref, discussion) : g.toGraphQLThread(ref, issueOrPullRequest)
1881
+ };
1882
+ });
1883
+ }
1884
+ return results;
1885
+ }
1886
+ async function listPage(repo, query = {}) {
1887
+ const state = query.state ?? "open";
1888
+ const direction = query.direction ?? "desc";
1889
+ const createdAfter = query.createdAfter?.getTime();
1890
+ if (query.kind === "discussion") {
1891
+ if (query.assignee) return {
1892
+ items: [],
1893
+ warnings: [{
1894
+ code: "filter_unsupported",
1895
+ message: "Discussions have no assignees"
1896
+ }]
1897
+ };
1898
+ if (query.milestone && query.milestone !== "none") return {
1899
+ items: [],
1900
+ warnings: [{
1901
+ code: "filter_unsupported",
1902
+ message: "Discussions have no milestones"
1903
+ }]
1904
+ };
1905
+ const warnings = isFirstPage(query.cursor) && query.sort === "comments" ? [{
1906
+ code: "sort_unsupported",
1907
+ message: "Discussions cannot be sorted by comments; sorted by update time"
1908
+ }] : [];
1909
+ for (const filter of ["involves", "mentions"]) if (isFirstPage(query.cursor) && query[filter]) warnings.push({
1910
+ code: "filter_unsupported",
1911
+ message: `GitHub lists discussions without a ${filter} filter; it was ignored`
1912
+ });
1913
+ const data = await graphql("DISCUSSIONS_LIST", {
1914
+ owner: repo.owner,
1915
+ name: repo.name,
1916
+ first: Math.min(query.perPage ?? 50, 100),
1917
+ after: query.cursor?.token ?? null,
1918
+ field: query.sort === "created" || !query.sort ? "CREATED_AT" : "UPDATED_AT",
1919
+ direction: direction.toUpperCase()
1920
+ }, query);
1921
+ const { toDiscussionThread } = await import("./graphql-DG5aJBT3-DceyFYdM.js");
1922
+ const discussions = data.repository?.discussions;
1923
+ return {
1924
+ items: (discussions?.nodes ?? []).map((node) => toDiscussionThread({
1925
+ forge: FORGE,
1926
+ instance,
1927
+ repo,
1928
+ kind: "discussion",
1929
+ number: String(node.number)
1930
+ }, node)).filter((thread) => (state === "all" || thread.state === state) && (!query.author || thread.author?.login === query.author) && (!query.labels?.length || query.labels.every((label) => thread.labels.some((item) => item.name === label))) && (!query.since || (thread.updatedAt?.getTime() ?? 0) >= query.since.getTime()) && (createdAfter === void 0 || (thread.createdAt?.getTime() ?? 0) >= createdAfter)),
1931
+ cursor: discussions?.pageInfo.hasNextPage && discussions.pageInfo.endCursor ? { token: discussions.pageInfo.endCursor } : void 0,
1932
+ ...warnings.length ? { warnings } : {}
1933
+ };
1934
+ }
1935
+ if (state === "merged") {
1936
+ const page = await searchThreadsPage({
1937
+ repo,
1938
+ kind: "pull_request",
1939
+ labels: query.labels,
1940
+ author: query.author,
1941
+ assignee: query.assignee,
1942
+ involves: query.involves,
1943
+ since: query.since,
1944
+ queryRaw: [
1945
+ "is:merged",
1946
+ query.createdAfter && `created:>=${query.createdAfter.toISOString()}`,
1947
+ query.mentions && `mentions:${query.mentions}`,
1948
+ query.milestone && (query.milestone === "none" ? "no:milestone" : `milestone:"${query.milestone.replaceAll("\"", "")}"`)
1949
+ ].filter(Boolean).join(" "),
1950
+ sort: query.sort ?? "created",
1951
+ direction,
1952
+ perPage: query.perPage,
1953
+ cursor: query.cursor,
1954
+ signal: query.signal
1955
+ });
1956
+ await withPullChecks(page, query);
1957
+ return page;
1958
+ }
1959
+ const milestone = query.milestone === void 0 || query.milestone === "none" || !isFirstPage(query.cursor) ? query.milestone : await milestoneNumber(repo, query.milestone, query);
1960
+ if (milestone === null) return { items: [] };
1961
+ const warnings = isFirstPage(query.cursor) && query.involves ? [{
1962
+ code: "filter_unsupported",
1963
+ message: "GitHub lists issues and pull requests without an involves filter; it was ignored. search.threads() has one"
1964
+ }] : [];
1965
+ const pullsOnly = query.kind === "pull_request" && !query.labels?.length && !query.author && !query.assignee && !query.mentions && !query.milestone && !query.since && query.sort !== "comments";
1966
+ const result = await fetcher.page(`${repoPath(repo)}/${pullsOnly ? "pulls" : "issues"}`, {
1967
+ query: {
1968
+ state,
1969
+ labels: query.labels?.join(","),
1970
+ creator: query.author,
1971
+ assignee: query.assignee,
1972
+ mentioned: query.mentions,
1973
+ milestone,
1974
+ since: query.since?.toISOString(),
1975
+ sort: query.sort ?? "created",
1976
+ direction,
1977
+ per_page: query.perPage
1978
+ },
1979
+ cursor: query.cursor,
1980
+ signal: query.signal
1981
+ });
1982
+ const older = (raw) => createdAfter !== void 0 && (Date.parse(raw.created_at ?? "") || 0) < createdAfter;
1983
+ const page = toPage(result, (raw) => {
1984
+ const isPull = Boolean(raw.pull_request || raw.head);
1985
+ if (query.kind === "issue" && isPull || query.kind === "pull_request" && !isPull || older(raw)) return;
1986
+ return toThread({
1987
+ forge: FORGE,
1988
+ instance,
1989
+ repo,
1990
+ kind: isPull ? "pull_request" : "issue",
1991
+ number: String(raw.number)
1992
+ }, raw);
1993
+ });
1994
+ const ordered = (query.sort ?? "created") === "created" && direction === "desc";
1995
+ await withPullChecks(page, query);
1996
+ const listed = warnings.length ? {
1997
+ ...page,
1998
+ warnings: [...warnings, ...page.warnings ?? []]
1999
+ } : page;
2000
+ return ordered && (result.data ?? []).some(older) ? {
2001
+ ...listed,
2002
+ cursor: void 0
2003
+ } : listed;
2004
+ }
2005
+ /** The number of the milestone titled `title`, or `null` when the repository has none by that title. */
2006
+ async function milestoneNumber(repo, title, options) {
2007
+ for await (const milestone of iteratePages((page) => milestonesPage(repo, page), {
2008
+ state: "all",
2009
+ signal: options.signal
2010
+ })) if (milestone.title === title) return milestone.id;
2011
+ return null;
2012
+ }
2013
+ /** Fills `checks`, and a missing `commentCount`, on every pull in the page with one batched read. */
2014
+ async function withPullChecks(page, options) {
2015
+ const pulls = page.items.filter((thread) => thread.kind === "pull_request");
2016
+ if (!pulls.length || anonymous) return;
2017
+ try {
2018
+ const results = await getMany(pulls.map((thread) => thread.ref), options);
2019
+ for (const [index, result] of results.entries()) if (result.ok) {
2020
+ pulls[index].checks = result.thread.checks ?? pulls[index].checks;
2021
+ pulls[index].commentCount ??= result.thread.commentCount;
2022
+ pulls[index].mergedBy ??= result.thread.mergedBy;
2023
+ }
2024
+ } catch (error) {
2025
+ if (!degradesToWarning(error)) throw error;
2026
+ page.warnings = [...page.warnings ?? [], toWarning("checks_unreadable", error)];
2027
+ }
2028
+ }
2029
+ async function commentsPage(thread, listOptions = {}) {
2030
+ const ref = requireThread(thread, context);
2031
+ if (ref.kind === "discussion") {
2032
+ const [page, { toDiscussionComment }] = await Promise.all([discussionCommentPage(ref, listOptions), import("./graphql-DG5aJBT3-DceyFYdM.js")]);
2033
+ return {
2034
+ ...page,
2035
+ items: page.items.map(({ comment }) => toDiscussionComment(ref, comment))
2036
+ };
2037
+ }
2038
+ return list(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/comments`, listOptions, (raw) => toComment(ref, raw), { query: { since: listOptions.since?.toISOString() } });
2039
+ }
2040
+ /** Discussion comment ids are node ids already; other comments are read for theirs. */
2041
+ async function commentNodeId(ref, options) {
2042
+ if ("thread" in ref && ref.thread.kind === "discussion") return ref.id;
2043
+ const { data } = await fetcher.json("commit" in ref ? commitCommentPath(ref) : commentPath(ref), { signal: options?.signal });
2044
+ if (!data.node_id) throw new NotFoundError(`Comment ${ref.id} has no node id`, 404, "", context);
2045
+ return data.node_id;
2046
+ }
2047
+ function commentPath(ref) {
2048
+ return `${repoPath(ref.thread.repo)}/issues/comments/${encodeURIComponent(ref.id)}`;
2049
+ }
2050
+ function commitCommentPath(ref) {
2051
+ return `${repoPath(ref.commit.repo)}/comments/${encodeURIComponent(ref.id)}`;
2052
+ }
2053
+ async function setState(thread, state, options_ = {}) {
2054
+ const ref = requireThread(thread, context);
2055
+ if (ref.kind === "discussion") {
2056
+ const reason = options_.reasonRaw ?? (options_.reason && DISCUSSION_CLOSE_REASONS[options_.reason]);
2057
+ if (state === "closed" && options_.reason && !reason) throw new UnsupportedOperationError(`GitHub discussions have no ${options_.reason} close reason; pass reasonRaw: 'outdated'`, context);
2058
+ const id = await discussionId(ref, options_);
2059
+ const data = state === "closed" ? (await graphql("CLOSE_DISCUSSION", {
2060
+ id,
2061
+ reason: reason?.toUpperCase() ?? null
2062
+ }, options_)).closeDiscussion : (await graphql("REOPEN_DISCUSSION", { id }, options_)).reopenDiscussion;
2063
+ return (await import("./graphql-DG5aJBT3-DceyFYdM.js")).toDiscussionThread(ref, data.discussion);
2064
+ }
2065
+ const reason = options_.reasonRaw ?? options_.reason;
2066
+ const { data } = await fetcher.json(threadPath(ref), {
2067
+ method: "PATCH",
2068
+ json: ref.kind === "issue" && state === "closed" && reason ? {
2069
+ state,
2070
+ state_reason: reason
2071
+ } : { state },
2072
+ signal: options_.signal
2073
+ });
2074
+ return toThread(ref, data);
2075
+ }
2076
+ async function merge(thread, options_ = {}) {
2077
+ const ref = requireThread(thread, context);
2078
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only pull requests can be merged", context);
2079
+ if (options_.whenChecksPass) throw new UnsupportedOperationError("GitHub auto-merge is not available through the REST API", context);
2080
+ if (options_.method === "rebase_merge" || options_.method === "fast_forward_only") throw new UnsupportedOperationError(`GitHub does not support the ${options_.method} merge method`, context);
2081
+ let method = options_.method;
2082
+ if (!method) {
2083
+ const { data: repo } = await fetcher.json(repoPath(ref.repo), { signal: options_.signal });
2084
+ method = soleMergeMethod({
2085
+ merge: repo.allow_merge_commit,
2086
+ squash: repo.allow_squash_merge,
2087
+ rebase: repo.allow_rebase_merge
2088
+ }, context);
2089
+ }
2090
+ return directMerge(ref, method, options_);
2091
+ }
2092
+ async function directMerge(ref, method, mergeOptions) {
2093
+ const path = `${threadPath(ref)}/merge`;
2094
+ const { sha, title, message } = mergeOptions;
2095
+ const body = {
2096
+ merge_method: method,
2097
+ sha,
2098
+ commit_title: title,
2099
+ commit_message: message
2100
+ };
2101
+ const timeout = options.timeout ?? 3e4;
2102
+ const budget = new AbortController();
2103
+ const signal = mergeOptions.signal ? anySignal([budget.signal, mergeOptions.signal]) : budget.signal;
2104
+ const timer = setTimeout(() => budget.abort(new DOMException("Merge timed out", "TimeoutError")), timeout);
2105
+ const timedOut = (url, requestMethod, cause, uuid) => new ForgeTimeoutError(uuid ? `Merge request ${uuid} for pull request ${ref.number} was still pending after ${timeout}ms; GitHub may still complete it` : `Merge of pull request ${ref.number} got no response within ${timeout}ms; GitHub may still complete it`, timeout, {
2106
+ ...context,
2107
+ url,
2108
+ method: requestMethod
2109
+ }, { cause });
2110
+ let url = fetcher.resolve(`${path}-async`);
2111
+ let requestMethod = "PUT";
2112
+ let uuid;
2113
+ try {
2114
+ let state;
2115
+ let status;
2116
+ try {
2117
+ const { data, response } = await fetcher.json(`${path}-async`, {
2118
+ method: "PUT",
2119
+ json: {
2120
+ ...body,
2121
+ merge_action: "direct_merge"
2122
+ },
2123
+ signal
2124
+ });
2125
+ state = data;
2126
+ status = response.status;
2127
+ } catch (error) {
2128
+ if (budget.signal.aborted) throw error;
2129
+ if (enterprise && error instanceof NotFoundError) {
2130
+ url = fetcher.resolve(path);
2131
+ const { data } = await fetcher.json(path, {
2132
+ method: "PUT",
2133
+ json: body,
2134
+ mapError: toMergeError,
2135
+ signal
2136
+ });
2137
+ return {
2138
+ status: "merged",
2139
+ sha: data?.sha,
2140
+ raw: data
2141
+ };
2142
+ }
2143
+ state = pendingMergeFrom(error, method, sha, title, message);
2144
+ status = 409;
2145
+ }
2146
+ for (let attempt = 0; state.status === "pending"; attempt++) {
2147
+ uuid = state.details?.uuid;
2148
+ if (!uuid) throw new ForgeApiError("GitHub reported a pending merge without a request id", status, JSON.stringify(state).slice(0, 512), {
2149
+ ...context,
2150
+ url,
2151
+ method: requestMethod
2152
+ });
2153
+ const poll = `${path}-async/${encodeURIComponent(uuid)}`;
2154
+ url = fetcher.resolve(poll);
2155
+ requestMethod = "GET";
2156
+ await sleep(POLL_DELAYS[Math.min(attempt, POLL_DELAYS.length - 1)], signal);
2157
+ const { data, response } = await fetcher.json(poll, { signal });
2158
+ state = data;
2159
+ status = response.status;
2160
+ }
2161
+ const errorContext = {
2162
+ ...context,
2163
+ url,
2164
+ method: requestMethod
2165
+ };
2166
+ const excerpt = JSON.stringify(state).slice(0, 512);
2167
+ switch (state.status) {
2168
+ case "merged": return {
2169
+ status: "merged",
2170
+ sha: state.details?.sha,
2171
+ raw: state
2172
+ };
2173
+ case "enqueued": throw new MergeBlockedError("Pull request was added to a merge queue and has not merged", status, excerpt, errorContext);
2174
+ case "failed": throw new MergeBlockedError(state.details?.message || "GitHub could not merge the pull request", status, excerpt, errorContext);
2175
+ default: throw new ForgeApiError(`GitHub reported an unknown merge status ${JSON.stringify(state.status)}`, status, excerpt, errorContext);
2176
+ }
2177
+ } catch (error) {
2178
+ throw budget.signal.aborted ? timedOut(url, requestMethod, error, uuid) : error;
2179
+ } finally {
2180
+ clearTimeout(timer);
2181
+ }
2182
+ }
2183
+ function pendingMergeFrom(error, method, sha, title, message) {
2184
+ if (!(error instanceof ForgeApiError)) throw error;
2185
+ if (isPlainApiError(error, 400)) throw new MergeBlockedError("Pull request cannot be merged in its current state", 400, error.body, {
2186
+ ...context,
2187
+ url: error.url,
2188
+ method: error.method
2189
+ }, { cause: error });
2190
+ if (!isPlainApiError(error, 409)) throw toMergeError(error);
2191
+ let pending;
2192
+ try {
2193
+ pending = JSON.parse(error.body);
2194
+ } catch {}
2195
+ const details = pending?.details;
2196
+ if (!details?.uuid) throw toMergeError(error);
2197
+ if (title !== void 0 || message !== void 0 || details.merge_action !== "direct_merge" || details.merge_method !== method || details.bypass_rules || sha !== void 0 && details.expected_head_sha !== sha) throw new MergeBlockedError("Another merge request is pending whose options do not match or cannot be verified", 409, error.body, {
2198
+ ...context,
2199
+ url: error.url,
2200
+ method: error.method
2201
+ }, { cause: error });
2202
+ return {
2203
+ status: "pending",
2204
+ details
2205
+ };
2206
+ }
2207
+ function isPlainApiError(error, status) {
2208
+ return error instanceof ForgeApiError && error.constructor === ForgeApiError && error.status === status;
2209
+ }
2210
+ /** A merge goes through REST, which takes no method; a rebase goes through GraphQL, after a read for the pull request's node id. */
2211
+ async function updateBranch(thread, updateOptions = {}) {
2212
+ const ref = requirePull(thread, "updated");
2213
+ const { sha, signal } = updateOptions;
2214
+ if (updateOptions.method === "rebase") {
2215
+ const { data: pull } = await fetcher.json(threadPath(ref), { signal });
2216
+ if (sha !== void 0 && pull.head?.sha !== sha) throw new BranchMovedError(`Head branch of pull request ${ref.number} is at ${pull.head?.sha}, not ${sha}`, 409, "", context);
2217
+ return {
2218
+ status: "queued",
2219
+ raw: (await graphql("UPDATE_PULL_REQUEST_BRANCH", {
2220
+ id: pull.node_id,
2221
+ sha: sha ?? null,
2222
+ method: "REBASE"
2223
+ }, updateOptions)).updatePullRequestBranch
2224
+ };
2225
+ }
2226
+ const { data } = await fetcher.json(`${threadPath(ref)}/update-branch`, {
2227
+ method: "PUT",
2228
+ json: sha === void 0 ? {} : { expected_head_sha: sha },
2229
+ mapError: updateBranchError,
2230
+ signal
2231
+ });
2232
+ return {
2233
+ status: "queued",
2234
+ raw: data
2235
+ };
2236
+ }
2237
+ const REVIEW_EVENTS = {
2238
+ approve: "APPROVE",
2239
+ request_changes: "REQUEST_CHANGES",
2240
+ comment: "COMMENT"
2241
+ };
2242
+ function requirePull(thread, action) {
2243
+ const ref = requireThread(thread, context);
2244
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError(`Only pull requests can be ${action}`, context);
2245
+ return ref;
2246
+ }
2247
+ function reviewCommentInput(comments) {
2248
+ return comments?.map((comment) => ({
2249
+ path: comment.path,
2250
+ body: comment.body,
2251
+ line: comment.line,
2252
+ start_line: comment.startLine,
2253
+ side: comment.side?.toUpperCase()
2254
+ }));
2255
+ }
2256
+ /** Resolvable conversations, by the id of each comment in them; empty when GraphQL is unreachable. */
2257
+ async function reviewThreadsByComment(ref, options) {
2258
+ const byComment = /* @__PURE__ */ new Map();
2259
+ if (anonymous) return byComment;
2260
+ let data;
2261
+ try {
2262
+ data = await graphql("REVIEW_THREADS", {
2263
+ owner: ref.repo.owner,
2264
+ name: ref.repo.name,
2265
+ number: Number(ref.number)
2266
+ }, options);
2267
+ } catch (error) {
2268
+ if (error instanceof ForgeError) return byComment;
2269
+ throw error;
2270
+ }
2271
+ for (const node of data.repository?.pullRequest?.reviewThreads.nodes ?? []) for (const comment of node.comments.nodes) if (comment.databaseId !== null) byComment.set(String(comment.databaseId), {
2272
+ id: node.id,
2273
+ resolved: node.isResolved
2274
+ });
2275
+ return byComment;
2276
+ }
2277
+ /** Review comments and conversations read for a pull's first page of reviews, reused by its later pages. */
2278
+ const reviewContext = /* @__PURE__ */ new Map();
2279
+ async function reviewsPage(thread, listOptions = {}) {
2280
+ const ref = requirePull(thread, "reviewed");
2281
+ const result = await fetcher.page(`${threadPath(ref)}/reviews`, {
2282
+ query: { per_page: listOptions.perPage },
2283
+ cursor: listOptions.cursor,
2284
+ signal: listOptions.signal,
2285
+ conditional: false
2286
+ });
2287
+ const now = Date.now();
2288
+ for (const [path, entry] of reviewContext) if (now - entry.at >= REVIEW_CONTEXT_TTL) reviewContext.delete(path);
2289
+ const key = threadPath(ref);
2290
+ const kept = !isFirstPage(listOptions.cursor) && reviewContext.get(key) || {
2291
+ at: now,
2292
+ read: Promise.all([Array.fromAsync(fetcher.items(`${key}/comments`, {
2293
+ query: { per_page: 100 },
2294
+ signal: listOptions.signal
2295
+ })), reviewThreadsByComment(ref, listOptions)])
2296
+ };
2297
+ reviewContext.delete(key);
2298
+ const [comments, byComment] = await kept.read;
2299
+ if (result.cursor) reviewContext.set(key, kept);
2300
+ return toPage(result, (raw) => toReview(ref, raw, comments.filter((comment) => String(comment.pull_request_review_id ?? "") === String(raw.id)).map((comment) => toReviewComment(ref, comment, byComment.get(String(comment.id))))));
2301
+ }
2302
+ async function createReview(thread, input, options) {
2303
+ const ref = requirePull(thread, "reviewed");
2304
+ const { data } = await fetcher.json(`${threadPath(ref)}/reviews`, {
2305
+ method: "POST",
2306
+ json: {
2307
+ event: input.event ? REVIEW_EVENTS[input.event] : void 0,
2308
+ body: input.body,
2309
+ comments: reviewCommentInput(input.comments)
2310
+ },
2311
+ signal: options?.signal
2312
+ });
2313
+ return toReview(ref, data, []);
2314
+ }
2315
+ async function getComment(ref, options) {
2316
+ const thread = requireThread(ref.thread, context);
2317
+ if (thread.kind === "discussion") {
2318
+ const data = await graphql("GET_DISCUSSION_COMMENT", { id: ref.id }, options);
2319
+ if (!data.node?.id) throw new NotFoundError(`Comment ${ref.id} not found`, 404, "", context);
2320
+ return (await import("./graphql-DG5aJBT3-DceyFYdM.js")).toDiscussionComment(thread, data.node);
2321
+ }
2322
+ const { data } = await fetcher.json(commentPath(ref), { signal: options?.signal });
2323
+ return toComment(thread, data);
2324
+ }
2325
+ async function getReview(ref, options) {
2326
+ const pull = requirePull(ref.thread, "reviewed");
2327
+ const path = `${threadPath(pull)}/reviews/${encodeURIComponent(ref.id)}`;
2328
+ const [{ data }, comments, byComment] = await Promise.all([
2329
+ fetcher.json(path, { signal: options?.signal }),
2330
+ Array.fromAsync(fetcher.items(`${path}/comments`, {
2331
+ query: { per_page: 100 },
2332
+ signal: options?.signal
2333
+ })),
2334
+ reviewThreadsByComment(pull, options)
2335
+ ]);
2336
+ return toReview(pull, data, comments.map((comment) => toReviewComment(pull, comment, byComment.get(String(comment.id)))));
2337
+ }
2338
+ async function getCheck(ref, options) {
2339
+ if (ref.type !== "check_run") throw new UnsupportedOperationError(`GitHub cannot read a ${ref.type} by id; only check runs can be read on their own`, context);
2340
+ const { data } = await fetcher.json(`${repoPath(ref.repo)}/check-runs/${encodeURIComponent(ref.id)}`, { signal: options?.signal });
2341
+ return toCheckRun(ref.repo, data);
2342
+ }
2343
+ async function getJob(ref, options) {
2344
+ const { data } = await fetcher.json(`${repoPath(ref.repo)}/actions/jobs/${encodeURIComponent(ref.id)}`, { signal: options?.signal });
2345
+ const run = ref.run ?? (data.run_id === void 0 ? void 0 : {
2346
+ forge: "github",
2347
+ instance,
2348
+ repo: ref.repo,
2349
+ id: String(data.run_id)
2350
+ });
2351
+ if (!run) throw new UnsupportedOperationError(`GitHub returned job ${ref.id} without its run, and the ref names no run`, context);
2352
+ return toWorkflowJob(run, data);
2353
+ }
2354
+ async function subscriptionNode(thread, options) {
2355
+ const ref = requireThread(thread, context);
2356
+ if (ref.kind !== "issue" && ref.kind !== "pull_request" && ref.kind !== "discussion") throw new UnsupportedOperationError(`GitHub has no subscription for a ${ref.kind}`, context);
2357
+ const data = await graphql("SUBSCRIPTION_STATE", {
2358
+ owner: ref.repo.owner,
2359
+ name: ref.repo.name,
2360
+ number: Number(ref.number),
2361
+ discussion: ref.kind === "discussion"
2362
+ }, options);
2363
+ const node = ref.kind === "discussion" ? data.repository?.discussion : data.repository?.issueOrPullRequest;
2364
+ if (!node) throw new NotFoundError(`Thread ${ref.number} not found`, 404, "", context);
2365
+ return {
2366
+ id: node.id,
2367
+ state: node.viewerSubscription
2368
+ };
2369
+ }
2370
+ async function closingPage(ref, document, listOptions) {
2371
+ const [data, { toGraphQLThread }] = await Promise.all([graphql(document, {
2372
+ owner: ref.repo.owner,
2373
+ name: ref.repo.name,
2374
+ number: Number(ref.number),
2375
+ first: Math.min(listOptions.perPage ?? 50, 100),
2376
+ after: listOptions.cursor?.token ?? null
2377
+ }, listOptions), import("./graphql-DG5aJBT3-DceyFYdM.js")]);
2378
+ const references = data.repository?.thread?.references;
2379
+ if (!references) throw new NotFoundError(`Thread ${ref.number} not found`, 404, "", context);
2380
+ return {
2381
+ items: references.nodes.map((node) => {
2382
+ const repo = {
2383
+ forge: FORGE,
2384
+ instance,
2385
+ owner: node.repository.owner.login,
2386
+ name: node.repository.name,
2387
+ externalId: node.repository.databaseId === void 0 ? void 0 : String(node.repository.databaseId)
2388
+ };
2389
+ return toGraphQLThread({
2390
+ forge: FORGE,
2391
+ instance,
2392
+ repo,
2393
+ kind: node.__typename === "PullRequest" ? "pull_request" : "issue",
2394
+ number: String(node.number)
2395
+ }, node);
2396
+ }),
2397
+ cursor: references.pageInfo.hasNextPage && references.pageInfo.endCursor ? { token: references.pageInfo.endCursor } : void 0
2398
+ };
2399
+ }
2400
+ async function setSubscription(thread, state, options) {
2401
+ const { id } = await subscriptionNode(thread, options);
2402
+ await graphql("UPDATE_SUBSCRIPTION", {
2403
+ id,
2404
+ state
2405
+ }, options);
2406
+ }
2407
+ async function reposPage(repoFetcher, path, wrapped, listOptions = {}) {
2408
+ return toPage(await repoFetcher.page(path, {
2409
+ query: { per_page: listOptions.perPage },
2410
+ cursor: listOptions.cursor,
2411
+ signal: listOptions.signal,
2412
+ select: wrapped ? (body, next) => ({
2413
+ items: body.repositories,
2414
+ next
2415
+ }) : void 0
2416
+ }), (raw) => toRepo(instance, raw));
2417
+ }
2418
+ /** The authenticated login, read once and reused; reactions are deleted by id, so removing one needs it. */
2419
+ const viewerLogin = memo(async () => (await fetcher.json("/user")).data.login);
2420
+ /** `/users/{owner}/repos` serves organisations too, but lists only public repositories. */
2421
+ async function ownerReposPage(owner, query = {}) {
2422
+ const visibility = query.visibility === "all" ? void 0 : query.visibility;
2423
+ const read = (path, params) => list(path, query, (raw) => toRepo(instance, raw), { query: {
2424
+ ...params,
2425
+ sort: query.sort === "name" ? "full_name" : query.sort,
2426
+ direction: query.direction
2427
+ } });
2428
+ const userRepos = () => read(`/users/${encodeURIComponent(owner.owner)}/repos`, { type: "owner" });
2429
+ if (visibility === "public") return userRepos();
2430
+ try {
2431
+ return await read(`/orgs/${encodeURIComponent(owner.owner)}/repos`, { type: visibility === "internal" ? void 0 : visibility });
2432
+ } catch (error) {
2433
+ if (!(error instanceof NotFoundError) || !isFirstPage(query.cursor)) throw error;
2434
+ }
2435
+ if (auth.type === "token" && !installation && (await viewerLogin()).toLowerCase() === owner.owner.toLowerCase()) return read("/user/repos", {
2436
+ affiliation: "owner",
2437
+ visibility: visibility === "internal" ? void 0 : visibility
2438
+ });
2439
+ if (visibility) return {
2440
+ items: [],
2441
+ warnings: [{
2442
+ code: "filter_unsupported",
2443
+ message: "GitHub lists only the public repositories of another user"
2444
+ }]
2445
+ };
2446
+ return userRepos();
2447
+ }
2448
+ /** Repository hooks, or organisation hooks for a namespace ref. */
2449
+ function hooksPath(target) {
2450
+ return isNamespaceRef(target) ? `/orgs/${encodeURIComponent(target.owner)}/hooks` : `${repoPath(target)}/hooks`;
2451
+ }
2452
+ function hookConfig(input) {
2453
+ return {
2454
+ ...input.url ? { url: input.url } : {},
2455
+ content_type: input.contentType ?? "json",
2456
+ ...input.secret ? { secret: input.secret } : {}
2457
+ };
2458
+ }
2459
+ /**
2460
+ * The hook endpoints respond with `404` when the credential lacks
2461
+ * `admin:repo_hook` or `admin:org_hook`, so the status alone is misleading.
2462
+ */
2463
+ function scopeIs404(error) {
2464
+ if (error instanceof NotFoundError) return new ForbiddenError("GitHub responded with 404 for a webhook endpoint, which it also does when the credential lacks admin:repo_hook or admin:org_hook", 404, error.body, "resource_protected", {
2465
+ forge: error.forge,
2466
+ instance: error.instance,
2467
+ url: error.url,
2468
+ method: error.method,
2469
+ reasonRaw: "hook_scope_404"
2470
+ }, { cause: error });
2471
+ return error;
2472
+ }
2473
+ /** GitHub responds with `403` to a re-request of another app's check run, and names a missing permission as `Resource not accessible by ...`. */
2474
+ function notOwnerOfCheckRun(error) {
2475
+ if (error.acceptedScopes?.length && !error.acceptedScopes.some((scope) => error.grantedScopes?.includes(scope)) || /not accessible by/i.test(error.body)) return error;
2476
+ return new ForbiddenError("GitHub refused to re-request a check run that another app created", error.status, error.body, "not_owner", {
2477
+ forge: error.forge,
2478
+ instance: error.instance,
2479
+ url: error.url,
2480
+ method: error.method
2481
+ }, { cause: error });
2482
+ }
2483
+ /** GitHub responds with `422` to a change of the tag, target or draft state of an immutable release. */
2484
+ function immutableReleaseIs422(error) {
2485
+ if (!(error instanceof ForgeApiError) || error.constructor !== ForgeApiError || error.status !== 422) return error;
2486
+ const reasonRaw = error.body.match(/\w+ cannot be changed when release is immutable/)?.[0];
2487
+ if (!reasonRaw) return error;
2488
+ return new ForbiddenError("GitHub refused the change because the release is immutable", error.status, error.body, "immutable_release", {
2489
+ forge: error.forge,
2490
+ instance: error.instance,
2491
+ url: error.url,
2492
+ method: error.method,
2493
+ reasonRaw
2494
+ }, { cause: error });
2495
+ }
2496
+ /** GitHub search qualifiers, in the order the docs list them. */
2497
+ function searchQualifiers(query) {
2498
+ const qualifiers = [];
2499
+ const advanced = !query.kind;
2500
+ /** In advanced search a bare `OR` binds looser than the other qualifiers, so caller syntax is grouped. */
2501
+ const group = (value) => advanced ? `(${value})` : value;
2502
+ const text = advanced && query.text ? advancedFreeText(query.text) : query.text;
2503
+ if (text) qualifiers.push(group(text));
2504
+ if (query.repo) qualifiers.push(`repo:${query.repo.owner}/${query.repo.name}`);
2505
+ else if (query.owner) qualifiers.push(`user:${query.owner}`);
2506
+ qualifiers.push(query.kind ? query.kind === "pull_request" ? "is:pr" : "is:issue" : "(is:issue OR is:pr)");
2507
+ if (query.state && query.state !== "all") qualifiers.push(`state:${query.state}`);
2508
+ for (const [name, value] of [
2509
+ ["author", query.author],
2510
+ ["involves", query.involves],
2511
+ ["assignee", query.assignee]
2512
+ ]) if (value) qualifiers.push(`${name}:${value}`);
2513
+ for (const label of query.labels ?? []) qualifiers.push(`label:"${label}"`);
2514
+ if (query.since) qualifiers.push(`updated:>=${query.since.toISOString()}`);
2515
+ if (query.queryRaw) qualifiers.push(group(query.queryRaw));
2516
+ return qualifiers;
2517
+ }
2518
+ /**
2519
+ * GitHub requires a kind in issue search; naming both needs advanced search.
2520
+ * GitHub Enterprise Server may predate it, and GitHub App user access tokens
2521
+ * can't search both kinds at once, so those read issues, then pull requests.
2522
+ */
2523
+ async function searchThreadsPage(query) {
2524
+ if (!query.kind && (enterprise || auth.type === "token" && tokenKindOf(auth, await resolveToken(auth)) === "app-user")) return phased(["issue", "pull_request"].map((kind) => (cursor) => searchIssuesPage({
2525
+ ...query,
2526
+ kind,
2527
+ cursor
2528
+ })), query.cursor);
2529
+ return searchIssuesPage(query);
2530
+ }
2531
+ async function searchIssuesPage(query) {
2532
+ const result = await fetcher.page("/search/issues", {
2533
+ query: {
2534
+ q: searchQualifiers(query).join(" "),
2535
+ advanced_search: query.kind ? void 0 : "true",
2536
+ sort: query.sort && query.sort !== "relevance" ? query.sort : void 0,
2537
+ order: query.direction,
2538
+ per_page: query.perPage
2539
+ },
2540
+ cursor: query.cursor,
2541
+ signal: query.signal,
2542
+ select: (body, next) => {
2543
+ const { items, total_count } = body;
2544
+ return {
2545
+ items,
2546
+ next,
2547
+ total: total_count
2548
+ };
2549
+ }
2550
+ });
2551
+ return toPage(result, (raw) => {
2552
+ const repo = query.repo ?? repoRefFromApiUrl(instance, raw.repository_url);
2553
+ if (!repo) return;
2554
+ const isPull = Boolean(raw.pull_request);
2555
+ return toThread({
2556
+ forge: FORGE,
2557
+ instance,
2558
+ repo,
2559
+ kind: isPull ? "pull_request" : "issue",
2560
+ number: String(raw.number)
2561
+ }, raw);
2562
+ });
2563
+ }
2564
+ function milestonesPage(repo, listOptions = {}) {
2565
+ return list(`${repoPath(repo)}/milestones`, listOptions, (raw) => toMilestone(raw), { query: { state: listOptions.state ?? "open" } });
2566
+ }
2567
+ async function contributorStats(repo, statsOptions = {}) {
2568
+ const path = `${repoPath(repo)}/stats/contributors`;
2569
+ for (let attempt = 0;; attempt++) {
2570
+ const { data, response } = await fetcher.json(path, { signal: statsOptions.signal });
2571
+ if (response.status !== 202) return (data ?? []).map((raw) => toContributorStats(instance, raw));
2572
+ if (attempt >= CONTRIBUTOR_STATS_DELAYS.length) throw new ForgeApiError(`GitHub is still computing the contributor statistics of ${repo.owner}/${repo.name}`, 202, "", {
2573
+ ...context,
2574
+ url: fetcher.resolve(path),
2575
+ method: "GET"
2576
+ });
2577
+ await sleep(CONTRIBUTOR_STATS_DELAYS[attempt], statsOptions.signal);
2578
+ }
2579
+ }
2580
+ const REPO_SEARCH_SORTS = {
2581
+ updated: "updated",
2582
+ stars: "stars"
2583
+ };
2584
+ async function searchReposPage(query) {
2585
+ const qualifiers = [
2586
+ query.text,
2587
+ query.owner && `user:${query.owner}`,
2588
+ query.language && `language:${query.language}`,
2589
+ query.queryRaw
2590
+ ].filter(Boolean);
2591
+ const warnings = query.sort === "created" ? [{
2592
+ code: "sort_unsupported",
2593
+ message: "GitHub repository search cannot sort by creation time; sorted by relevance"
2594
+ }] : [];
2595
+ const result = await fetcher.page("/search/repositories", {
2596
+ query: {
2597
+ q: qualifiers.join(" "),
2598
+ sort: query.sort ? REPO_SEARCH_SORTS[query.sort] : void 0,
2599
+ order: query.direction,
2600
+ per_page: query.perPage
2601
+ },
2602
+ cursor: query.cursor,
2603
+ signal: query.signal,
2604
+ select: (body, next) => {
2605
+ const { items, total_count } = body;
2606
+ return {
2607
+ items,
2608
+ next,
2609
+ total: total_count
2610
+ };
2611
+ }
2612
+ });
2613
+ return toPage(result, (raw) => toRepo(instance, raw), warnings);
2614
+ }
2615
+ const COMMIT_SEARCH_SORTS = {
2616
+ author_date: "author-date",
2617
+ committer_date: "committer-date"
2618
+ };
2619
+ async function searchCommitsPage(query) {
2620
+ const qualifiers = [
2621
+ query.text,
2622
+ query.repo && `repo:${query.repo.owner}/${query.repo.name}`,
2623
+ query.author && `author:${query.author}`,
2624
+ query.committer && `committer:${query.committer}`,
2625
+ query.since && `author-date:>=${query.since.toISOString()}`,
2626
+ query.until && `author-date:<=${query.until.toISOString()}`,
2627
+ query.queryRaw
2628
+ ].filter(Boolean);
2629
+ const result = await fetcher.page("/search/commits", {
2630
+ query: {
2631
+ q: qualifiers.join(" "),
2632
+ sort: query.sort && COMMIT_SEARCH_SORTS[query.sort],
2633
+ order: query.direction,
2634
+ per_page: query.perPage
2635
+ },
2636
+ cursor: query.cursor,
2637
+ signal: query.signal,
2638
+ select: (body, next) => {
2639
+ const { items, total_count } = body;
2640
+ return {
2641
+ items,
2642
+ next,
2643
+ total: total_count
2644
+ };
2645
+ }
2646
+ });
2647
+ return toPage(result, (raw) => {
2648
+ const repo = query.repo ?? (raw.repository && toRepoRef(instance, raw.repository));
2649
+ return repo && toCommit(repo, raw);
2650
+ });
2651
+ }
2652
+ /** The excerpts only come with the text match media type. */
2653
+ async function searchCodePage(query) {
2654
+ const qualifiers = [
2655
+ query.text,
2656
+ query.repo ? `repo:${query.repo.owner}/${query.repo.name}` : query.owner && `user:${query.owner}`,
2657
+ query.queryRaw
2658
+ ].filter(Boolean);
2659
+ let incomplete = false;
2660
+ const result = await fetcher.page("/search/code", {
2661
+ query: {
2662
+ q: qualifiers.join(" "),
2663
+ per_page: query.perPage
2664
+ },
2665
+ headers: { accept: "application/vnd.github.text-match+json" },
2666
+ cursor: query.cursor,
2667
+ signal: query.signal,
2668
+ select: (body, next) => {
2669
+ const { items, incomplete_results, total_count } = body;
2670
+ incomplete = incomplete_results === true;
2671
+ return {
2672
+ items,
2673
+ next,
2674
+ total: total_count
2675
+ };
2676
+ }
2677
+ });
2678
+ return toPage(result, (raw) => ({
2679
+ repo: query.repo ?? toRepoRef(instance, raw.repository),
2680
+ path: raw.path,
2681
+ ref: new URL(raw.url).searchParams.get("ref") ?? void 0,
2682
+ fragments: (raw.text_matches ?? []).filter((match) => match.property === "content").map((match) => ({ text: match.fragment })),
2683
+ url: raw.html_url,
2684
+ raw
2685
+ }), incomplete ? [{
2686
+ code: "search_incomplete",
2687
+ message: "GitHub stopped the search before it finished; the page may be missing matches"
2688
+ }] : []);
2689
+ }
2690
+ async function feedPage(path, listOptions = {}) {
2691
+ const throttled = throttledPage(path, listOptions, "this feed");
2692
+ if (throttled) return throttled;
2693
+ const result = await fetcher.page(path, {
2694
+ query: { per_page: listOptions.perPage },
2695
+ cursor: listOptions.cursor,
2696
+ signal: listOptions.signal
2697
+ });
2698
+ const poll = recordPoll(path, listOptions.cursor, result.response);
2699
+ const { toFeedEvents } = await import("./events-CeChclTf-CX-gD8oy.js");
2700
+ const page = toPage(result, (raw) => toFeedEvents(instance, raw));
2701
+ return {
2702
+ ...page,
2703
+ items: page.items.flat(),
2704
+ ...poll
2705
+ };
2706
+ }
2707
+ function createInstallationsApi(app) {
2708
+ const appFetcher = createFetcher({
2709
+ baseUrl,
2710
+ authHeaders: async () => ({ authorization: `Bearer ${await app.appJwt()}` })
2711
+ });
2712
+ const auth = options.auth;
2713
+ function toInstallation(raw) {
2714
+ return {
2715
+ forge: FORGE,
2716
+ instance,
2717
+ id: String(raw.id),
2718
+ account: toActor(instance, raw.account),
2719
+ targetTypeRaw: raw.target_type,
2720
+ repositorySelectionRaw: raw.repository_selection,
2721
+ raw
2722
+ };
2723
+ }
2724
+ function provider(installation) {
2725
+ return derive({
2726
+ ...options,
2727
+ auth: {
2728
+ ...auth,
2729
+ installationId: installationId(installation)
2730
+ }
2731
+ }, app);
2732
+ }
2733
+ async function listPage(listOptions = {}) {
2734
+ return toPage(await appFetcher.page("/app/installations", {
2735
+ query: { per_page: listOptions.perPage },
2736
+ cursor: listOptions.cursor,
2737
+ signal: listOptions.signal
2738
+ }), toInstallation);
2739
+ }
2740
+ return {
2741
+ listPage,
2742
+ async get(installation, options) {
2743
+ return toInstallation((await appFetcher.json(`/app/installations/${installationId(installation)}`, { signal: options?.signal })).data);
2744
+ },
2745
+ token: (installation, options) => app.installationTokenDetails(installationId(installation), options),
2746
+ reposPage(installation, listOptions) {
2747
+ const id = installationId(installation);
2748
+ return reposPage(createFetcher({
2749
+ baseUrl,
2750
+ authHeaders: async () => ({ authorization: `Bearer ${await app.installationToken(id)}` })
2751
+ }), "/installation/repositories", true, listOptions);
2752
+ },
2753
+ provider,
2754
+ providers() {
2755
+ return forgeIterable(async function* () {
2756
+ for await (const installation of iteratePages(listPage)) yield {
2757
+ installation,
2758
+ provider: provider(installation)
2759
+ };
2760
+ });
2761
+ }
2762
+ };
2763
+ }
2764
+ /** github.com serves file bytes from a CDN outside the REST API rate limit. */
2765
+ const rawFetcher = host === "api.github.com" ? createFetcher({
2766
+ baseUrl: "https://raw.githubusercontent.com",
2767
+ authHeaders: createAuthHeaders(options.auth, credentials)
2768
+ }) : void 0;
2769
+ async function readFile(repo, path, fileOptions = {}) {
2770
+ const encoded = path.split("/").map(encodeURIComponent).join("/");
2771
+ if (fileOptions.metadata === false && rawFetcher) {
2772
+ const response = await rawFetcher.raw(`/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}/${encodeURIComponent(fileOptions.ref ?? "HEAD")}/${encoded}`, { signal: fileOptions.signal });
2773
+ const bytes = new Uint8Array(await response.arrayBuffer());
2774
+ return toFileContent(bytes, {
2775
+ path,
2776
+ size: bytes.byteLength
2777
+ }, fileOptions, context);
2778
+ }
2779
+ const { data } = await fetcher.json(`${repoPath(repo)}/contents/${encoded}`, {
2780
+ query: { ref: fileOptions.ref },
2781
+ signal: fileOptions.signal
2782
+ });
2783
+ const file = {
2784
+ path: data.path,
2785
+ sha: data.sha,
2786
+ size: data.size,
2787
+ url: data.html_url ?? void 0
2788
+ };
2789
+ const content = data.encoding === "base64" && data.content !== void 0 ? data.content : (await fetcher.json(`${repoPath(repo)}/git/blobs/${data.sha}`, { signal: fileOptions.signal })).data.content;
2790
+ return toFileContent(fromBase64(content), file, fileOptions, context);
2791
+ }
2792
+ async function templates(repo, options = {}) {
2793
+ const signal = options.signal;
2794
+ return (await import("./templates-Bn8a-pd2-D9DhJEVD.js")).readTemplates(repo, options.kind ? [options.kind] : ["issue", "pull_request"], {
2795
+ list: async (ref, path) => {
2796
+ const { data } = await fetcher.json(`${repoPath(ref)}/contents${path ? `/${path.split("/").map(encodeURIComponent).join("/")}` : ""}`, { signal });
2797
+ return Array.isArray(data) ? data : [];
2798
+ },
2799
+ read: async (ref, path) => (await readFile(ref, path, {
2800
+ as: "text",
2801
+ signal
2802
+ })).content,
2803
+ repository: async (ref) => (await fetcher.json(repoPath(ref), { signal })).data
2804
+ });
2805
+ }
2806
+ async function treePage(repo, treeOptions = {}) {
2807
+ const ref = treeOptions.ref ?? "HEAD";
2808
+ const target = treeOptions.path ? `${ref}:${treeOptions.path.replace(/^\/|\/$/g, "")}` : ref;
2809
+ const { data, response } = await fetcher.json(`${repoPath(repo)}/git/trees/${encodeURIComponent(target)}`, {
2810
+ query: treeOptions.recursive ? { recursive: "1" } : {},
2811
+ signal: treeOptions.signal
2812
+ });
2813
+ const warnings = data.truncated ? [{
2814
+ code: "tree_truncated",
2815
+ message: "GitHub truncated the tree; read it directory by directory instead",
2816
+ subject: target
2817
+ }] : [];
2818
+ return toPage({
2819
+ data: data.tree,
2820
+ response,
2821
+ notModified: false
2822
+ }, toTreeEntry, warnings);
2823
+ }
2824
+ async function compare(repo, base, head, options = {}) {
2825
+ const path = `${repoPath(repo)}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`;
2826
+ const limit = options.commitLimit;
2827
+ const perPage = limit === void 0 ? void 0 : Math.min(100, Math.max(1, limit));
2828
+ const { data } = await fetcher.json(path, {
2829
+ query: { per_page: perPage },
2830
+ signal: options.signal
2831
+ });
2832
+ let commits = data.commits ?? [];
2833
+ const total = data.total_commits ?? data.ahead_by;
2834
+ if (limit !== void 0 && perPage !== void 0 && total !== void 0 && total > commits.length) {
2835
+ const first = Math.floor(Math.max(0, total - limit) / perPage) + 1;
2836
+ const pages = Array.from({ length: Math.ceil(total / perPage) - first + 1 }, (_, index) => first + index);
2837
+ commits = (await Promise.all(pages.map(async (page) => page === 1 ? commits : (await fetcher.json(path, {
2838
+ query: {
2839
+ per_page: perPage,
2840
+ page
2841
+ },
2842
+ signal: options.signal
2843
+ })).data.commits ?? []))).flat();
2844
+ }
2845
+ return {
2846
+ base,
2847
+ head,
2848
+ aheadBy: data.ahead_by,
2849
+ behindBy: data.behind_by,
2850
+ mergeBaseSha: data.merge_base_commit?.sha,
2851
+ commits: commits.map((raw) => toCommit(repo, raw)).toReversed(),
2852
+ files: (data.files ?? []).map(toChangedFile),
2853
+ raw: data
2854
+ };
2855
+ }
2856
+ async function commitsPage(repo, query = {}) {
2857
+ return list(`${repoPath(repo)}/commits`, query, (raw) => toCommit(repo, raw), { query: {
2858
+ sha: query.ref,
2859
+ path: query.path,
2860
+ author: query.author,
2861
+ since: query.since?.toISOString(),
2862
+ until: query.until?.toISOString()
2863
+ } });
2864
+ }
2865
+ async function releasesPage(repo, listOptions = {}) {
2866
+ return list(`${repoPath(repo)}/releases`, listOptions, (raw) => toRelease(repo, raw));
2867
+ }
2868
+ /** The commit that `input` builds on: `createFrom` resolved, `expectedHead`, or the head of the branch. */
2869
+ async function commitParent(repo, input, options) {
2870
+ if (input.createFrom !== void 0) return isSha(input.createFrom) ? input.createFrom : (await fetcher.json(`${repoPath(repo)}/commits/${encodeURIComponent(input.createFrom)}`, { signal: options?.signal })).data.sha;
2871
+ return input.expectedHead ?? (await fetcher.json(`${repoPath(repo)}/git/ref/heads/${branchPath(input.branch)}`, { signal: options?.signal })).data.object.sha;
2872
+ }
2873
+ /** Moves `branch` from `before` to `after` only if it is still at `before`. The zero oid stands for a branch that does not exist. */
2874
+ async function swapBranch(repo, branch, before, after, options) {
2875
+ const { repository } = await graphql("REPOSITORY_ID", {
2876
+ owner: repo.owner,
2877
+ name: repo.name
2878
+ }, options);
2879
+ if (!repository) throw new NotFoundError(`${repo.owner}/${repo.name} does not exist`, 404, "", context);
2880
+ await graphql("UPDATE_REFS", { input: {
2881
+ repositoryId: repository.id,
2882
+ refUpdates: [{
2883
+ name: `refs/heads/${branch}`,
2884
+ beforeOid: before,
2885
+ afterOid: after
2886
+ }]
2887
+ } }, options);
2888
+ }
2889
+ /** One `createCommitOnBranch` mutation, which GitHub signs and attributes to the credential's account. */
2890
+ async function commitOnBranch(repo, input, options) {
2891
+ const head = await commitParent(repo, input, options);
2892
+ if (input.createFrom !== void 0) await fetcher.json(`${repoPath(repo)}/git/refs`, {
2893
+ method: "POST",
2894
+ json: {
2895
+ ref: `refs/heads/${input.branch}`,
2896
+ sha: head
2897
+ },
2898
+ signal: options?.signal
2899
+ });
2900
+ const fileChanges = {
2901
+ additions: input.changes.flatMap((change) => change.content === null ? [] : [{
2902
+ path: change.path,
2903
+ contents: changeBase64(change.content)
2904
+ }]),
2905
+ deletions: input.changes.flatMap((change) => change.content === null ? [{ path: change.path }] : [])
2906
+ };
2907
+ try {
2908
+ const [data, { toGraphQLCommit }] = await Promise.all([graphql("CREATE_COMMIT_ON_BRANCH", { input: {
2909
+ branch: {
2910
+ repositoryNameWithOwner: `${repo.owner}/${repo.name}`,
2911
+ branchName: input.branch
2912
+ },
2913
+ expectedHeadOid: head,
2914
+ message: splitMessage(input.message),
2915
+ fileChanges
2916
+ } }, options), import("./graphql-DG5aJBT3-DceyFYdM.js")]);
2917
+ return toGraphQLCommit(repo, data.createCommitOnBranch.commit);
2918
+ } catch (error) {
2919
+ if (input.createFrom !== void 0) await swapBranch(repo, input.branch, head, ZERO_OID).catch(() => {});
2920
+ throw commitError(error);
2921
+ }
2922
+ }
2923
+ /** Blobs, a tree, a commit and a ref update through the Git database API, which can name an author. */
2924
+ async function commitTree(repo, input, options) {
2925
+ const signal = options?.signal;
2926
+ const parent = await commitParent(repo, input, options);
2927
+ const tree = async (directory) => (await fetcher.json(`${repoPath(repo)}/git/trees/${encodeURIComponent(directory ? `${parent}:${directory}` : parent)}`, { signal })).data;
2928
+ const root = memo(() => tree(""));
2929
+ const existing = await existingFiles(input.changes, inDirectories(async (directory) => {
2930
+ try {
2931
+ const data = directory ? await tree(directory) : await root();
2932
+ return new Map(data.tree.filter((entry) => entry.type === "blob").map((entry) => [directory ? `${directory}/${entry.path}` : entry.path, entry]));
2933
+ } catch (error) {
2934
+ if (error instanceof NotFoundError) return;
2935
+ throw error;
2936
+ }
2937
+ }), context);
2938
+ const entries = await Promise.all(input.changes.map(async ({ path, content }) => {
2939
+ const mode = existing.get(path)?.mode ?? "100644";
2940
+ if (content === null || typeof content === "string") return {
2941
+ path,
2942
+ mode,
2943
+ type: "blob",
2944
+ ...content === null ? { sha: null } : { content }
2945
+ };
2946
+ const { data } = await fetcher.json(`${repoPath(repo)}/git/blobs`, {
2947
+ method: "POST",
2948
+ json: {
2949
+ content: changeBase64(content),
2950
+ encoding: "base64"
2951
+ },
2952
+ signal
2953
+ });
2954
+ return {
2955
+ path,
2956
+ mode,
2957
+ type: "blob",
2958
+ sha: data.sha
2959
+ };
2960
+ }));
2961
+ const { data: created } = await fetcher.json(`${repoPath(repo)}/git/trees`, {
2962
+ method: "POST",
2963
+ json: {
2964
+ base_tree: (await root()).sha,
2965
+ tree: entries
2966
+ },
2967
+ signal
2968
+ });
2969
+ const { data: commit } = await fetcher.json(`${repoPath(repo)}/git/commits`, {
2970
+ method: "POST",
2971
+ json: {
2972
+ message: input.message,
2973
+ tree: created.sha,
2974
+ parents: [parent],
2975
+ author: input.author
2976
+ },
2977
+ signal
2978
+ });
2979
+ try {
2980
+ await swapBranch(repo, input.branch, input.createFrom === void 0 ? parent : ZERO_OID, commit.sha, options);
2981
+ } catch (error) {
2982
+ if (input.createFrom !== void 0) throw error;
2983
+ const { data } = await fetcher.json(`${repoPath(repo)}/git/ref/heads/${branchPath(input.branch)}`, { signal });
2984
+ if (data.object.sha !== parent && error instanceof ForgeApiError) throw new BranchMovedError(`${input.branch} is at ${data.object.sha}, not ${parent}`, 409, error.body, context, { cause: error });
2985
+ throw error;
2986
+ }
2987
+ return toGitCommit(repo, commit);
2988
+ }
2989
+ async function writeRelease(repo, path, method, input, options) {
2990
+ const { data } = await fetcher.json(path, {
2991
+ method,
2992
+ json: {
2993
+ tag_name: input.tag,
2994
+ target_commitish: input.target,
2995
+ name: input.name,
2996
+ body: input.body,
2997
+ draft: input.draft,
2998
+ prerelease: input.prerelease
2999
+ },
3000
+ mapError: immutableReleaseIs422,
3001
+ signal: options?.signal
3002
+ });
3003
+ return toRelease(repo, data);
3004
+ }
3005
+ const ALERT_SOURCES = {
3006
+ dependency: {
3007
+ path: "dependabot/alerts",
3008
+ states: {
3009
+ open: "open",
3010
+ closed: "fixed,dismissed,auto_dismissed"
3011
+ },
3012
+ map: toDependabotAlert
3013
+ },
3014
+ code_scanning: {
3015
+ path: "code-scanning/alerts",
3016
+ states: {
3017
+ open: "open",
3018
+ closed: "closed"
3019
+ },
3020
+ map: toCodeScanningAlert
3021
+ },
3022
+ secret: {
3023
+ path: "secret-scanning/alerts",
3024
+ states: {
3025
+ open: "open",
3026
+ closed: "resolved"
3027
+ },
3028
+ map: toSecretScanningAlert
3029
+ },
3030
+ advisory: {
3031
+ path: "security-advisories",
3032
+ states: {
3033
+ open: void 0,
3034
+ closed: void 0
3035
+ },
3036
+ map: toRepositoryAdvisory
3037
+ }
3038
+ };
3039
+ async function alertsPage(repo, listOptions = {}) {
3040
+ const kinds = listOptions.kind ? [listOptions.kind] : Object.keys(ALERT_SOURCES);
3041
+ return phased(kinds.map((kind) => async (cursor) => {
3042
+ const source = ALERT_SOURCES[kind];
3043
+ const state = listOptions.state ?? "open";
3044
+ const filter = state === "all" ? void 0 : source.states[state];
3045
+ try {
3046
+ const result = await fetcher.page(`${repoPath(repo)}/${source.path}`, {
3047
+ query: {
3048
+ state: filter,
3049
+ per_page: listOptions.perPage
3050
+ },
3051
+ cursor,
3052
+ signal: listOptions.signal
3053
+ });
3054
+ return toPage(result, (raw) => {
3055
+ const alert = source.map(repo, raw);
3056
+ return filter || state === "all" || alert.state === "open" === (state === "open") ? alert : void 0;
3057
+ });
3058
+ } catch (error) {
3059
+ if (!listOptions.kind && (error instanceof InsufficientScopeError || error instanceof NotFoundError)) return {
3060
+ items: [],
3061
+ warnings: [toWarning(error instanceof InsufficientScopeError ? "insufficient_scope" : "alerts_unavailable", error, kind)]
3062
+ };
3063
+ throw error;
3064
+ }
3065
+ }), listOptions.cursor);
3066
+ }
3067
+ /** The GraphQL node id of an issue, pull request or discussion. */
3068
+ async function nodeId(thread, options) {
3069
+ const ref = requireThread(thread, context);
3070
+ return ref.externalId ?? (await subscriptionNode(ref, options)).id;
3071
+ }
3072
+ function reactionPath(target) {
3073
+ if ("thread" in target) return `${repoPath(target.thread.repo)}/issues/comments/${encodeURIComponent(target.id)}/reactions`;
3074
+ const ref = requireIssueOrPull(target, context, "react to");
3075
+ return `${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/reactions`;
3076
+ }
3077
+ async function reactionsPage(target, listOptions = {}) {
3078
+ const thread = "thread" in target ? target.thread : target;
3079
+ if (thread.kind === "discussion") {
3080
+ const id = "thread" in target ? target.id : await nodeId(thread, listOptions);
3081
+ const [data, { toGraphQLActor, GRAPHQL_REACTIONS }] = await Promise.all([graphql("NODE_REACTIONS", {
3082
+ id,
3083
+ after: listOptions.cursor?.token ?? null
3084
+ }, listOptions), import("./graphql-DG5aJBT3-DceyFYdM.js")]);
3085
+ const reactions = data.node?.reactions;
3086
+ return {
3087
+ items: (reactions?.nodes ?? []).flatMap((raw) => {
3088
+ const actor = toGraphQLActor(instance, raw.user);
3089
+ return actor ? [{
3090
+ content: reactionContent(GRAPHQL_REACTIONS[raw.content] ?? raw.content),
3091
+ contentRaw: raw.content,
3092
+ actor,
3093
+ createdAt: toDate(raw.createdAt),
3094
+ raw
3095
+ }] : [];
3096
+ }),
3097
+ cursor: reactions?.pageInfo.hasNextPage && reactions.pageInfo.endCursor ? { token: reactions.pageInfo.endCursor } : void 0,
3098
+ ...reactions?.totalCount !== void 0 ? { total: reactions.totalCount } : {}
3099
+ };
3100
+ }
3101
+ const result = await fetcher.page(reactionPath(target), {
3102
+ query: { per_page: listOptions.perPage },
3103
+ cursor: listOptions.cursor,
3104
+ signal: listOptions.signal
3105
+ });
3106
+ return toPage(result, (raw) => {
3107
+ const actor = toActor(instance, raw.user);
3108
+ return actor && {
3109
+ content: reactionContent(raw.content),
3110
+ contentRaw: raw.content,
3111
+ actor,
3112
+ createdAt: toDate(raw.created_at),
3113
+ raw
3114
+ };
3115
+ });
3116
+ }
3117
+ async function react(target, reaction, options) {
3118
+ const thread = "thread" in target ? target.thread : target;
3119
+ if (thread.kind === "discussion") {
3120
+ await graphql("ADD_REACTION", {
3121
+ id: "thread" in target ? target.id : await nodeId(thread, options),
3122
+ content: (await import("./graphql-DG5aJBT3-DceyFYdM.js")).REACTION_CONTENT[reaction]
3123
+ }, options);
3124
+ return;
3125
+ }
3126
+ await fetcher.raw(reactionPath(target), {
3127
+ method: "POST",
3128
+ json: { content: reaction },
3129
+ signal: options?.signal
3130
+ });
3131
+ }
3132
+ async function unreact(target, reaction, options) {
3133
+ const thread = "thread" in target ? target.thread : target;
3134
+ if (thread.kind === "discussion") {
3135
+ await graphql("REMOVE_REACTION", {
3136
+ id: "thread" in target ? target.id : await nodeId(thread, options),
3137
+ content: (await import("./graphql-DG5aJBT3-DceyFYdM.js")).REACTION_CONTENT[reaction]
3138
+ }, options);
3139
+ return;
3140
+ }
3141
+ const path = reactionPath(target);
3142
+ const { data } = await fetcher.json(path, {
3143
+ query: {
3144
+ content: reaction,
3145
+ per_page: 100
3146
+ },
3147
+ signal: options?.signal
3148
+ });
3149
+ const login = await viewerLogin();
3150
+ const mine = data.find((item) => item.content === reaction && item.user?.login === login);
3151
+ if (mine) await fetcher.raw(`${path}/${encodeURIComponent(mine.id)}`, {
3152
+ method: "DELETE",
3153
+ signal: options?.signal
3154
+ });
3155
+ }
3156
+ async function issuePatch(thread, json, action, signal) {
3157
+ const ref = requireIssueOrPull(thread, context, action);
3158
+ return (await fetcher.json(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}`, {
3159
+ method: "PATCH",
3160
+ json,
3161
+ signal
3162
+ })).data;
3163
+ }
3164
+ /** Check runs need an installation credential; a token writes a commit status instead. */
3165
+ const canWriteCheckRuns = auth.type === "app" && auth.installationId !== void 0;
3166
+ const STATUS_STATES = {
3167
+ pending: "pending",
3168
+ success: "success",
3169
+ failure: "failure",
3170
+ neutral: "success",
3171
+ unknown: "pending"
3172
+ };
3173
+ const CHECK_RUN_CONCLUSIONS = {
3174
+ success: "success",
3175
+ failure: "failure",
3176
+ neutral: "neutral"
3177
+ };
3178
+ async function report(repo, sha, input, options) {
3179
+ if (canWriteCheckRuns) {
3180
+ const conclusion = CHECK_RUN_CONCLUSIONS[input.state];
3181
+ const { data } = await fetcher.json(`${repoPath(repo)}/check-runs`, {
3182
+ method: "POST",
3183
+ json: {
3184
+ name: input.name,
3185
+ head_sha: sha,
3186
+ status: conclusion ? "completed" : "in_progress",
3187
+ conclusion,
3188
+ details_url: input.url,
3189
+ external_id: input.externalId,
3190
+ output: input.description ? {
3191
+ title: input.name,
3192
+ summary: input.description
3193
+ } : void 0
3194
+ },
3195
+ signal: options?.signal
3196
+ });
3197
+ return toCheckRun(repo, data);
3198
+ }
3199
+ const { data } = await fetcher.json(`${repoPath(repo)}/statuses/${sha}`, {
3200
+ method: "POST",
3201
+ json: {
3202
+ state: STATUS_STATES[input.state],
3203
+ context: input.name,
3204
+ description: input.description,
3205
+ target_url: input.url
3206
+ },
3207
+ signal: options?.signal
3208
+ });
3209
+ return toStatusCheck(repo, data);
3210
+ }
3211
+ async function runsPage(repo, query = {}) {
3212
+ const result = await fetcher.page(`${repoPath(repo)}/actions/runs`, {
3213
+ query: {
3214
+ branch: query.branch,
3215
+ status: query.state === "pending" ? "in_progress" : query.state === "success" ? "success" : query.state === "failure" ? "failure" : void 0,
3216
+ per_page: query.perPage
3217
+ },
3218
+ cursor: query.cursor,
3219
+ signal: query.signal,
3220
+ select: (body, next) => {
3221
+ const { workflow_runs, total_count } = body;
3222
+ return {
3223
+ items: workflow_runs,
3224
+ next,
3225
+ total: total_count
3226
+ };
3227
+ }
3228
+ });
3229
+ return toPage(result, (raw) => toWorkflowRun(repo, raw));
3230
+ }
3231
+ const spec = {
3232
+ extensions: { graphql: ((document, variables = {}, graphqlOptions) => {
3233
+ const query = String(document);
3234
+ return options.readOnly && graphqlOperations(query).some(({ type }) => type === "mutation") ? Promise.reject(new ReadOnlyError("GraphQL mutations are writes and this github provider is read-only", context)) : graphql({ query }, variables, graphqlOptions);
3235
+ }) },
3236
+ checks: {
3237
+ list: verb(true, (repo, sha, options) => headChecks(repo, sha, options?.signal)),
3238
+ get: verb(true, getCheck),
3239
+ report: verb(true, report),
3240
+ rerun: verb(true, async (ref, options) => {
3241
+ if (ref.type !== "check_run") throw new UnsupportedOperationError(`GitHub cannot re-run a ${ref.type}; only check runs can be re-requested`, context);
3242
+ const rerunJob = () => fetcher.raw(`${repoPath(ref.repo)}/actions/jobs/${encodeURIComponent(ref.id)}/rerun`, {
3243
+ method: "POST",
3244
+ signal: options?.signal
3245
+ });
3246
+ if (ref.app === "github-actions") {
3247
+ await rerunJob();
3248
+ return;
3249
+ }
3250
+ try {
3251
+ await fetcher.raw(`${repoPath(ref.repo)}/check-runs/${encodeURIComponent(ref.id)}/rerequest`, {
3252
+ method: "POST",
3253
+ signal: options?.signal
3254
+ });
3255
+ } catch (error) {
3256
+ if (!(error instanceof InsufficientScopeError) && !(error instanceof ForgeApiError && error.status === 422)) throw error;
3257
+ try {
3258
+ await rerunJob();
3259
+ } catch (rerunError) {
3260
+ if (!(rerunError instanceof NotFoundError)) throw rerunError;
3261
+ throw error instanceof InsufficientScopeError ? notOwnerOfCheckRun(error) : error;
3262
+ }
3263
+ }
3264
+ })
3265
+ },
3266
+ ci: {
3267
+ runsPage: verb(true, runsPage),
3268
+ getRun: verb(true, async (ref, options) => toWorkflowRun(ref.repo, (await fetcher.json(`${repoPath(ref.repo)}/actions/runs/${encodeURIComponent(ref.id)}`, { signal: options?.signal })).data)),
3269
+ jobsPage: verb(true, (ref, listOptions = {}) => list(`${repoPath(ref.repo)}/actions/runs/${encodeURIComponent(ref.id)}/jobs`, listOptions, (raw) => toWorkflowJob(ref, raw), { select: (body, next) => {
3270
+ const { jobs, total_count } = body;
3271
+ return {
3272
+ items: jobs,
3273
+ next,
3274
+ total: total_count
3275
+ };
3276
+ } })),
3277
+ getJob: verb(true, getJob),
3278
+ log: verb(!anonymous, async (ref, options) => (await fetcher.stream(`${repoPath(ref.repo)}/actions/jobs/${encodeURIComponent(ref.id)}/logs`, { signal: options?.signal })).body),
3279
+ rerunFailed: verb(true, async (ref, options) => {
3280
+ await fetcher.raw(`${repoPath(ref.repo)}/actions/runs/${encodeURIComponent(ref.id)}/rerun-failed-jobs`, {
3281
+ method: "POST",
3282
+ signal: options?.signal
3283
+ });
3284
+ })
3285
+ },
3286
+ contents: {
3287
+ getFile: verb(true, readFile),
3288
+ treePage: verb(true, treePage),
3289
+ branchesPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/branches`, listOptions, (raw) => toBranch(raw))),
3290
+ tagsPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/tags`, listOptions, toTag)),
3291
+ resolveRef: verb(true, async (repo, ref, options) => (await fetcher.json(`${repoPath(repo)}/commits/${encodeURIComponent(ref)}`, { signal: options?.signal })).data.sha),
3292
+ commitFiles: verb(true, (repo, input, options) => input.author ? commitTree(repo, input, options) : commitOnBranch(repo, input, options)),
3293
+ compare: verb(true, compare)
3294
+ },
3295
+ commits: {
3296
+ listPage: verb(true, commitsPage),
3297
+ get: verb(true, async ({ repo, sha }, options) => toCommit(repo, (await fetcher.json(`${repoPath(repo)}/commits/${sha}`, { signal: options?.signal })).data)),
3298
+ commentsPage: verb(true, (commit, listOptions = {}) => list(`${repoPath(commit.repo)}/commits/${encodeURIComponent(commit.sha)}/comments`, listOptions, (raw) => toCommitComment(commit, raw))),
3299
+ getComment: verb(anonymous ? "unverified" : true, async (ref, options) => {
3300
+ const { data } = await fetcher.json(commitCommentPath(ref), { signal: options?.signal });
3301
+ return toCommitComment(ref.commit, data);
3302
+ }),
3303
+ createComment: verb(true, async (commit, body, options) => {
3304
+ const { data } = await fetcher.json(`${repoPath(commit.repo)}/commits/${encodeURIComponent(commit.sha)}/comments`, {
3305
+ method: "POST",
3306
+ json: { body },
3307
+ signal: options?.signal
3308
+ });
3309
+ return toCommitComment(commit, data);
3310
+ }),
3311
+ updateComment: verb(true, async (ref, body, options) => {
3312
+ const { data } = await fetcher.json(commitCommentPath(ref), {
3313
+ method: "PATCH",
3314
+ json: { body },
3315
+ signal: options?.signal
3316
+ });
3317
+ return toCommitComment(ref.commit, data);
3318
+ }),
3319
+ deleteComment: verb(true, async (ref, options) => {
3320
+ await fetcher.raw(commitCommentPath(ref), {
3321
+ method: "DELETE",
3322
+ signal: options?.signal
3323
+ });
3324
+ }),
3325
+ commentHiding: verb(true, {
3326
+ hideComment: async (ref, reason, options) => {
3327
+ await graphql("MINIMIZE_COMMENT", {
3328
+ id: await commentNodeId(ref, options),
3329
+ classifier: reason.toUpperCase()
3330
+ }, options);
3331
+ },
3332
+ unhideComment: async (ref, options) => {
3333
+ await graphql("UNMINIMIZE_COMMENT", { id: await commentNodeId(ref, options) }, options);
3334
+ }
3335
+ })
3336
+ },
3337
+ search: {
3338
+ threadsPage: verb(true, searchThreadsPage),
3339
+ reposPage: verb(true, searchReposPage),
3340
+ commitsPage: verb(true, searchCommitsPage),
3341
+ codePage: verb(!anonymous, searchCodePage),
3342
+ queryRaw: true
3343
+ },
3344
+ releases: {
3345
+ listPage: verb(true, releasesPage),
3346
+ get: verb(true, async (ref, options) => toRelease(ref.repo, (await fetcher.json(`${repoPath(ref.repo)}/releases/${encodeURIComponent(ref.id)}`, { signal: options?.signal })).data)),
3347
+ getByTag: verb(true, async (repo, tag, options) => toRelease(repo, (await fetcher.json(`${repoPath(repo)}/releases/tags/${encodeURIComponent(tag)}`, { signal: options?.signal })).data)),
3348
+ downloadAsset: verb(true, async (ref, downloadOptions = {}) => (await fetcher.stream(`${repoPath(ref.repo)}/releases/assets/${encodeURIComponent(ref.id)}`, {
3349
+ headers: { accept: "application/octet-stream" },
3350
+ signal: downloadOptions.signal
3351
+ })).body),
3352
+ latest: verb(true, async (repo, options) => {
3353
+ try {
3354
+ return toRelease(repo, (await fetcher.json(`${repoPath(repo)}/releases/latest`, { signal: options?.signal })).data);
3355
+ } catch (error) {
3356
+ if (error instanceof NotFoundError) return;
3357
+ throw error;
3358
+ }
3359
+ }),
3360
+ create: verb(true, (repo, input, options) => writeRelease(repo, `${repoPath(repo)}/releases`, "POST", input, options)),
3361
+ update: verb(true, (ref, update, options) => writeRelease(ref.repo, `${repoPath(ref.repo)}/releases/${encodeURIComponent(ref.id)}`, "PATCH", update, options))
3362
+ },
3363
+ securityAlerts: {
3364
+ kinds: {
3365
+ dependency: !anonymous && (enterprise ? ({ version }) => versionAtLeast(version, GHES_DEPENDABOT_ALERTS) && "unverified" : true),
3366
+ code_scanning: !anonymous,
3367
+ secret: !anonymous,
3368
+ advisory: !anonymous && !enterprise
3369
+ },
3370
+ listPage: alertsPage
3371
+ },
3372
+ traits: {
3373
+ eventKinds: "native",
3374
+ authKinds: [
3375
+ "token",
3376
+ "app",
3377
+ "anonymous"
3378
+ ],
3379
+ limits: {
3380
+ bodyLength: 65536,
3381
+ commentLength: 65536,
3382
+ labelLength: 50
3383
+ }
3384
+ },
3385
+ probeVersion: enterprise ? async () => (await fetcher.json("/meta")).data.installed_version : void 0,
3386
+ installations: credentials ? verb(true, createInstallationsApi(credentials)) : void 0,
3387
+ web: GITHUB_WEB.links({
3388
+ baseUrl,
3389
+ instance
3390
+ }),
3391
+ webhooks: {
3392
+ listPage: verb(true, (target, listOptions = {}) => list(hooksPath(target), listOptions, (raw) => toWebhook(target, raw), { mapError: scopeIs404 })),
3393
+ create: verb(true, async (target, input, options) => toWebhook(target, (await fetcher.json(hooksPath(target), {
3394
+ method: "POST",
3395
+ json: {
3396
+ name: "web",
3397
+ active: input.active ?? true,
3398
+ events: nativeEventsFor(GITHUB_NATIVE_EVENTS, input.events, input.nativeEvents),
3399
+ config: hookConfig(input)
3400
+ },
3401
+ mapError: scopeIs404,
3402
+ signal: options?.signal
3403
+ })).data)),
3404
+ update: verb(true, async (ref, update, options) => toWebhook(ref.target, (await fetcher.json(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
3405
+ method: "PATCH",
3406
+ json: {
3407
+ ...update.active === void 0 ? {} : { active: update.active },
3408
+ ...update.events || update.nativeEvents ? { events: nativeEventsFor(GITHUB_NATIVE_EVENTS, update.events, update.nativeEvents) } : {},
3409
+ ...update.url || update.secret || update.contentType ? { config: hookConfig(update) } : {}
3410
+ },
3411
+ mapError: scopeIs404,
3412
+ signal: options?.signal
3413
+ })).data)),
3414
+ delete: verb(true, async (ref, options) => {
3415
+ await fetcher.raw(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
3416
+ method: "DELETE",
3417
+ mapError: scopeIs404,
3418
+ signal: options?.signal
3419
+ });
3420
+ }),
3421
+ rotateSecret: verb(true, async (ref, secret, options) => {
3422
+ const current = toWebhook(ref.target, (await fetcher.json(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
3423
+ mapError: scopeIs404,
3424
+ signal: options?.signal
3425
+ })).data);
3426
+ const { data } = await fetcher.json(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
3427
+ method: "PATCH",
3428
+ json: { config: hookConfig({
3429
+ url: current.url,
3430
+ contentType: current.contentType,
3431
+ secret
3432
+ }) },
3433
+ mapError: scopeIs404,
3434
+ signal: options?.signal
3435
+ });
3436
+ return toWebhook(ref.target, data);
3437
+ }),
3438
+ deliveriesPage: verb(true, (ref, listOptions = {}) => list(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}/deliveries`, listOptions, (raw) => toWebhookDelivery(ref, raw), { mapError: scopeIs404 })),
3439
+ redeliver: verb(true, async (ref, options) => {
3440
+ await fetcher.raw(`${hooksPath(ref.hook.target)}/${encodeURIComponent(ref.hook.id)}/deliveries/${encodeURIComponent(ref.id)}/attempts`, {
3441
+ method: "POST",
3442
+ mapError: scopeIs404,
3443
+ signal: options?.signal
3444
+ });
3445
+ })
3446
+ },
3447
+ scopes: githubScopesFor,
3448
+ users: {
3449
+ get: verb(true, async (login, options) => toUser(instance, (await fetcher.json(`/users/${encodeURIComponent(login)}`, { signal: options?.signal })).data)),
3450
+ me: verb(auth.type === "token" && !installation, async (options) => toUser(instance, (await fetcher.json("/user", { signal: options?.signal })).data)),
3451
+ sponsorable: verb(!enterprise && !anonymous, async (login, options) => {
3452
+ const data = await graphql("SPONSORABLE", { login }, options);
3453
+ if (!data.repositoryOwner) throw new NotFoundError(`Account ${login} not found`, 404, "", context);
3454
+ return data.repositoryOwner.hasSponsorsListing;
3455
+ }),
3456
+ eventsPage: verb(true, (login, listOptions) => feedPage(`/users/${encodeURIComponent(login)}/events`, listOptions)),
3457
+ blocking: verb(auth.type === "token" && !installation && (enterprise ? "unverified" : true), {
3458
+ block: async (login, options) => {
3459
+ await fetcher.raw(`/user/blocks/${encodeURIComponent(login)}`, {
3460
+ method: "PUT",
3461
+ signal: options?.signal
3462
+ });
3463
+ },
3464
+ unblock: async (login, options) => {
3465
+ await fetcher.raw(`/user/blocks/${encodeURIComponent(login)}`, {
3466
+ method: "DELETE",
3467
+ signal: options?.signal
3468
+ });
3469
+ }
3470
+ })
3471
+ },
3472
+ repos: {
3473
+ get: verb(true, async (ref, options) => {
3474
+ return toRepo(instance, (await fetcher.json(repoPath(ref), { signal: options?.signal })).data);
3475
+ }),
3476
+ listPage: verb(!anonymous, (listOptions = {}) => installation ? reposPage(fetcher, "/installation/repositories", true, listOptions) : reposPage(fetcher, "/user/repos", false, listOptions)),
3477
+ byOwnerPage: verb(true, ownerReposPage),
3478
+ labelsPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/labels`, listOptions, toLabel)),
3479
+ createLabel: verb(true, async (repo, label, options) => toLabel((await fetcher.json(`${repoPath(repo)}/labels`, {
3480
+ method: "POST",
3481
+ json: {
3482
+ name: label.name,
3483
+ color: label.colour,
3484
+ description: label.description
3485
+ },
3486
+ signal: options?.signal
3487
+ })).data)),
3488
+ milestonesPage: verb(true, milestonesPage),
3489
+ issueTypes: verb(!anonymous && !enterprise, async (repo, options) => {
3490
+ const { data } = await fetcher.json(`${repoPath(repo)}/issue-types`, { signal: options?.signal });
3491
+ return data.map((raw) => toIssueType(raw));
3492
+ }),
3493
+ collaboratorsPage: verb(!anonymous, (repo, listOptions = {}) => list(`${repoPath(repo)}/collaborators`, listOptions, (raw) => toCollaborator(instance, raw))),
3494
+ contributorsPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/contributors`, listOptions, (raw) => toContributor(instance, raw), { query: listOptions.includeUnlinked ? { anon: 1 } : {} })),
3495
+ contributorStats: verb(true, contributorStats),
3496
+ templates: verb(true, templates),
3497
+ permissionFor: verb(!anonymous, async (repo, actor, options) => {
3498
+ const { data } = await fetcher.json(`${repoPath(repo)}/collaborators/${encodeURIComponent(actorLogin(actor))}/permission`, { signal: options?.signal });
3499
+ return toRole({
3500
+ role_name: data.role_name ?? (data.permission === "none" ? void 0 : data.permission),
3501
+ permissions: data.user?.permissions
3502
+ });
3503
+ }),
3504
+ branchRules: verb(enterprise ? "unverified" : true, async (repo, name, options) => {
3505
+ const branchPath = `branches/${name.split("/").map(encodeURIComponent).join("/")}`;
3506
+ const path = `${repoPath(repo)}/${branchPath}`;
3507
+ const [{ data: branch }, rules] = await Promise.all([fetcher.json(path, { signal: options?.signal }), Array.fromAsync(fetcher.items(`${repoPath(repo)}/rules/${branchPath}`, {
3508
+ query: { per_page: 100 },
3509
+ signal: options?.signal
3510
+ }))]);
3511
+ const warnings = [];
3512
+ let protection;
3513
+ if (branch.protection?.enabled) try {
3514
+ if (anonymous) throw new AuthenticationRequiredError("Credentials are required for this request", 401, "", context);
3515
+ protection = (await fetcher.json(`${path}/protection`, { signal: options?.signal })).data;
3516
+ } catch (error) {
3517
+ if (!(error instanceof NotFoundError || error instanceof ForbiddenError || error instanceof InsufficientScopeError || error instanceof AuthenticationRequiredError)) throw error;
3518
+ warnings.push(toWarning("insufficient_scope", error, "protection"));
3519
+ }
3520
+ return toBranchRules(branch, rules, protection, warnings);
3521
+ }),
3522
+ addCollaborator: verb(true, async (repo, actor, role, options) => {
3523
+ return { status: (await fetcher.raw(`${repoPath(repo)}/collaborators/${encodeURIComponent(actorLogin(actor))}`, {
3524
+ method: "PUT",
3525
+ json: { permission: COLLABORATOR_PERMISSIONS[role] ?? role },
3526
+ signal: options?.signal
3527
+ })).status === 201 ? "invited" : "added" };
3528
+ }),
3529
+ assignableUsersPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/assignees`, listOptions, (raw) => toActor(instance, raw))),
3530
+ reviewerCandidatesPage: verb(!anonymous && "emulated", async (thread, listOptions = {}) => {
3531
+ const ref = requireThread(thread, context);
3532
+ const page = await fetcher.page(`${repoPath(ref.repo)}/collaborators`, {
3533
+ query: { per_page: listOptions.perPage },
3534
+ cursor: listOptions.cursor,
3535
+ signal: listOptions.signal
3536
+ });
3537
+ const author = page.notModified ? void 0 : (await get(ref, listOptions)).author?.login;
3538
+ return toPage(page, (raw) => raw.login === author ? void 0 : toActor(instance, raw));
3539
+ }),
3540
+ eventsPage: verb(true, (repo, listOptions) => feedPage(`${repoPath(repo)}/events`, listOptions))
3541
+ },
3542
+ orgs: {
3543
+ teamsPage: verb(!anonymous, (org, listOptions = {}) => list(`/orgs/${encodeURIComponent(org.owner)}/teams`, listOptions, (raw) => toTeam(instance, teamOrg(org), raw))),
3544
+ teamMembersPage: verb(!anonymous, (team, listOptions = {}) => list(`/orgs/${encodeURIComponent(team.org.owner)}/teams/${encodeURIComponent(team.slug)}/members`, listOptions, (raw) => toActor(instance, raw))),
3545
+ blocking: verb(enterprise ? "unverified" : true, {
3546
+ block: async (org, login, options) => {
3547
+ await fetcher.raw(`/orgs/${encodeURIComponent(org.owner)}/blocks/${encodeURIComponent(login)}`, {
3548
+ method: "PUT",
3549
+ signal: options?.signal
3550
+ });
3551
+ },
3552
+ unblock: async (org, login, options) => {
3553
+ await fetcher.raw(`/orgs/${encodeURIComponent(org.owner)}/blocks/${encodeURIComponent(login)}`, {
3554
+ method: "DELETE",
3555
+ signal: options?.signal
3556
+ });
3557
+ }
3558
+ })
3559
+ },
3560
+ notifications: {
3561
+ listPage: verb(notificationsAuth, notificationPage),
3562
+ markRead: verb(notificationsAuth, async (ref, options) => {
3563
+ await fetcher.raw(`/notifications/threads/${encodeURIComponent(ref.id)}`, {
3564
+ method: "PATCH",
3565
+ signal: options?.signal
3566
+ });
3567
+ }),
3568
+ markDone: verb(notificationsAuth && (enterprise ? ({ version }) => versionAtLeast(version, GHES_MARK_DONE) : true), async (ref, options) => {
3569
+ await fetcher.raw(`/notifications/threads/${encodeURIComponent(ref.id)}`, {
3570
+ method: "DELETE",
3571
+ signal: options?.signal
3572
+ });
3573
+ }),
3574
+ unsubscribe: verb(notificationsAuth, async (ref, options) => {
3575
+ await fetcher.raw(`/notifications/threads/${encodeURIComponent(ref.id)}/subscription`, {
3576
+ method: "DELETE",
3577
+ signal: options?.signal
3578
+ });
3579
+ }),
3580
+ markAllRead: verb(notificationsAuth, async (bulk = {}) => {
3581
+ await fetcher.raw(bulk.repo ? `${repoPath(bulk.repo)}/notifications` : "/notifications", {
3582
+ method: "PUT",
3583
+ ...bulk.before ? { json: { last_read_at: bulk.before.toISOString() } } : {},
3584
+ signal: bulk.signal
3585
+ });
3586
+ })
3587
+ },
3588
+ threads: {
3589
+ get: perKind({
3590
+ issue: true,
3591
+ pull_request: true,
3592
+ discussion: !anonymous
3593
+ }, get),
3594
+ getMany: verb(true, getMany),
3595
+ listPage: perKind({
3596
+ ...ISSUE_LIKE,
3597
+ discussion: !anonymous
3598
+ }, listPage),
3599
+ listFilters: [
3600
+ "involves",
3601
+ "mentions",
3602
+ "milestone"
3603
+ ],
3604
+ eventsPage: verb(true, async (thread, listOptions = {}) => {
3605
+ const ref = requireThread(thread, context);
3606
+ if (ref.kind === "discussion") {
3607
+ const [page, { toDiscussionCommentEvent }] = await Promise.all([discussionCommentPage(ref, listOptions), import("./graphql-DG5aJBT3-DceyFYdM.js")]);
3608
+ return {
3609
+ ...page,
3610
+ items: page.items.map(({ comment, isReply }) => toDiscussionCommentEvent(ref, comment, isReply))
3611
+ };
3612
+ }
3613
+ return list(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/timeline`, listOptions, (entry) => toEvent(instance, ref, entry));
3614
+ }),
3615
+ commentsPage: perKind({
3616
+ issue: true,
3617
+ pull_request: true,
3618
+ discussion: !anonymous
3619
+ }, commentsPage),
3620
+ getComment: perKind({
3621
+ issue: anonymous ? "unverified" : true,
3622
+ pull_request: true,
3623
+ discussion: !anonymous
3624
+ }, getComment),
3625
+ reviewsPage: verb(true, reviewsPage),
3626
+ getReview: verb(anonymous ? "unverified" : true, getReview),
3627
+ filesPage: verb(true, (ref, listOptions = {}) => list(`${threadPath(requirePull(ref, "read for changed files"))}/files`, listOptions, toChangedFile)),
3628
+ commitsPage: verb(true, (ref, listOptions = {}) => list(`${threadPath(requirePull(ref, "read for commits"))}/commits`, listOptions, (raw) => toCommit(ref.repo, raw))),
3629
+ createReview: verb(true, createReview),
3630
+ submitReview: verb(true, async (ref, event, body, options) => {
3631
+ const pull = requirePull(ref.thread, "reviewed");
3632
+ const { data } = await fetcher.json(`${threadPath(pull)}/reviews/${encodeURIComponent(ref.id)}/events`, {
3633
+ method: "POST",
3634
+ json: {
3635
+ event: REVIEW_EVENTS[event],
3636
+ body
3637
+ },
3638
+ signal: options?.signal
3639
+ });
3640
+ return toReview(pull, data, []);
3641
+ }),
3642
+ replyToReviewComment: verb(true, async (thread, comment, body, options) => {
3643
+ const pull = requirePull(thread, "reviewed");
3644
+ const id = comment.inReplyTo ?? comment.ref?.id;
3645
+ if (id === void 0) throw new UnsupportedOperationError("GitHub replies to a review comment by its id; pass the comment with its `ref`", context);
3646
+ const { data } = await fetcher.json(`${threadPath(pull)}/comments/${encodeURIComponent(id)}/replies`, {
3647
+ method: "POST",
3648
+ json: { body },
3649
+ signal: options?.signal
3650
+ });
3651
+ return toReviewComment(pull, data, comment.thread);
3652
+ }),
3653
+ reviewThreads: verb(true, {
3654
+ resolveReviewThread: async (_ref, id, options) => {
3655
+ await graphql("RESOLVE_REVIEW_THREAD", { id }, options);
3656
+ },
3657
+ unresolveReviewThread: async (_ref, id, options) => {
3658
+ await graphql("UNRESOLVE_REVIEW_THREAD", { id }, options);
3659
+ }
3660
+ }),
3661
+ checks: perKind({ pull_request: true }, async (thread, options) => {
3662
+ const ref = requireThread(thread, context);
3663
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
3664
+ return data.head?.sha ? headChecks(ref.repo, data.head.sha, options?.signal) : { items: [] };
3665
+ }),
3666
+ createComment: perKind({
3667
+ issue: true,
3668
+ pull_request: true,
3669
+ discussion: true
3670
+ }, async (thread, body, options) => {
3671
+ const ref = requireThread(thread, context);
3672
+ if (ref.kind === "discussion") {
3673
+ const data = await graphql("ADD_DISCUSSION_COMMENT", {
3674
+ id: await discussionId(ref, options),
3675
+ body
3676
+ }, options);
3677
+ return (await import("./graphql-DG5aJBT3-DceyFYdM.js")).toDiscussionComment(ref, data.addDiscussionComment.comment);
3678
+ }
3679
+ const { data } = await fetcher.json(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/comments`, {
3680
+ method: "POST",
3681
+ json: { body },
3682
+ signal: options?.signal
3683
+ });
3684
+ return toComment(ref, data);
3685
+ }),
3686
+ updateComment: perKind({
3687
+ issue: true,
3688
+ pull_request: true,
3689
+ discussion: true
3690
+ }, async (ref, body, options) => {
3691
+ const thread = requireThread(ref.thread, context);
3692
+ if (thread.kind === "discussion") {
3693
+ const data = await graphql("UPDATE_DISCUSSION_COMMENT", {
3694
+ id: ref.id,
3695
+ body
3696
+ }, options);
3697
+ return (await import("./graphql-DG5aJBT3-DceyFYdM.js")).toDiscussionComment(thread, data.updateDiscussionComment.comment);
3698
+ }
3699
+ const { data } = await fetcher.json(commentPath(ref), {
3700
+ method: "PATCH",
3701
+ json: { body },
3702
+ signal: options?.signal
3703
+ });
3704
+ return toComment(thread, data);
3705
+ }),
3706
+ deleteComment: perKind({
3707
+ issue: true,
3708
+ pull_request: true,
3709
+ discussion: true
3710
+ }, async (ref, options) => {
3711
+ if (ref.thread.kind === "discussion") {
3712
+ await graphql("DELETE_DISCUSSION_COMMENT", { id: ref.id }, options);
3713
+ return;
3714
+ }
3715
+ await fetcher.raw(commentPath(ref), {
3716
+ method: "DELETE",
3717
+ signal: options?.signal
3718
+ });
3719
+ }),
3720
+ create: perKind({
3721
+ issue: true,
3722
+ pull_request: true
3723
+ }, async (repo, input, options) => {
3724
+ const assignees = input.assignees?.map(actorLogin);
3725
+ if (input.kind === "issue") {
3726
+ const { data } = await fetcher.json(`${repoPath(repo)}/issues`, {
3727
+ method: "POST",
3728
+ json: {
3729
+ title: input.title,
3730
+ body: input.body,
3731
+ labels: input.labels,
3732
+ assignees
3733
+ },
3734
+ signal: options?.signal
3735
+ });
3736
+ return toThread({
3737
+ forge: FORGE,
3738
+ instance,
3739
+ repo,
3740
+ kind: "issue",
3741
+ number: String(data.number)
3742
+ }, data);
3743
+ }
3744
+ if (input.kind !== "pull_request") throw new UnsupportedOperationError("GitHub discussions cannot be created through this API yet", context);
3745
+ if (!input.head || !input.base) throw new UnsupportedOperationError("Creating a pull request needs head and base branches", context);
3746
+ const { data: pull } = await fetcher.json(`${repoPath(repo)}/pulls`, {
3747
+ method: "POST",
3748
+ json: {
3749
+ title: input.title,
3750
+ body: input.body,
3751
+ head: input.head,
3752
+ base: input.base,
3753
+ draft: input.draft
3754
+ },
3755
+ signal: options?.signal
3756
+ });
3757
+ const ref = {
3758
+ forge: FORGE,
3759
+ instance,
3760
+ repo,
3761
+ kind: "pull_request",
3762
+ number: String(pull.number)
3763
+ };
3764
+ if (!input.labels?.length && !assignees?.length) return toThread(ref, pull);
3765
+ const { data: issue } = await fetcher.json(`${repoPath(repo)}/issues/${encodeURIComponent(pull.number)}`, {
3766
+ method: "PATCH",
3767
+ json: {
3768
+ labels: input.labels,
3769
+ assignees
3770
+ },
3771
+ signal: options?.signal
3772
+ });
3773
+ return toThread(ref, {
3774
+ ...pull,
3775
+ labels: issue.labels,
3776
+ assignees: issue.assignees
3777
+ });
3778
+ }),
3779
+ /** The pulls endpoint takes no labels or assignees, so a pull request with them is edited as an issue. */
3780
+ update: perKind({
3781
+ issue: true,
3782
+ pull_request: true,
3783
+ discussion: true
3784
+ }, async (thread, input, options) => {
3785
+ const ref = requireThread(thread, context);
3786
+ if (ref.kind === "discussion") {
3787
+ if (input.labels || input.assignees) throw new UnsupportedOperationError("Setting labels or assignees on a GitHub discussion is not supported", context);
3788
+ const id = await discussionId(ref, options);
3789
+ const changed = input.state && await setState({
3790
+ ...ref,
3791
+ externalId: id
3792
+ }, input.state, options);
3793
+ if (input.title === void 0 && input.body === void 0) return changed || getDiscussion(ref, options);
3794
+ const data = await graphql("UPDATE_DISCUSSION", {
3795
+ id,
3796
+ title: input.title,
3797
+ body: input.body
3798
+ }, options);
3799
+ return (await import("./graphql-DG5aJBT3-DceyFYdM.js")).toDiscussionThread(ref, data.updateDiscussion.discussion);
3800
+ }
3801
+ const target = requireIssueOrPull(ref, context, "update");
3802
+ const json = {
3803
+ title: input.title,
3804
+ body: input.body,
3805
+ state: input.state,
3806
+ labels: input.labels,
3807
+ assignees: input.assignees?.map(actorLogin)
3808
+ };
3809
+ if (target.kind === "pull_request" && (input.labels || input.assignees)) {
3810
+ await issuePatch(target, json, "update", options?.signal);
3811
+ return toThread(target, (await fetcher.json(threadPath(target), { signal: options?.signal })).data);
3812
+ }
3813
+ const { data } = await fetcher.json(threadPath(target), {
3814
+ method: "PATCH",
3815
+ json,
3816
+ signal: options?.signal
3817
+ });
3818
+ return toThread(target, data);
3819
+ }),
3820
+ addLabels: perKind({
3821
+ issue: true,
3822
+ pull_request: true
3823
+ }, async (thread, labels, options) => {
3824
+ const ref = requireIssueOrPull(thread, context, "label");
3825
+ return toLabels((await fetcher.json(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/labels`, {
3826
+ method: "POST",
3827
+ json: { labels },
3828
+ signal: options?.signal
3829
+ })).data);
3830
+ }),
3831
+ removeLabels: perKind({
3832
+ issue: true,
3833
+ pull_request: true
3834
+ }, async (thread, labels, options) => {
3835
+ const ref = requireIssueOrPull(thread, context, "label");
3836
+ const path = `${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/labels`;
3837
+ let remaining;
3838
+ for (const label of labels) try {
3839
+ remaining = (await fetcher.json(`${path}/${encodeURIComponent(label)}`, {
3840
+ method: "DELETE",
3841
+ signal: options?.signal
3842
+ })).data;
3843
+ } catch (error) {
3844
+ if (!(error instanceof NotFoundError && error.body.includes("Label does not exist"))) throw error;
3845
+ }
3846
+ return toLabels(remaining ?? (await fetcher.json(path, {
3847
+ query: { per_page: 100 },
3848
+ signal: options?.signal
3849
+ })).data);
3850
+ }),
3851
+ setMilestone: perKind({
3852
+ issue: true,
3853
+ pull_request: true
3854
+ }, async (thread, milestone, options) => toMilestone((await issuePatch(thread, { milestone: milestone === void 0 ? null : await milestoneId(milestone, (page) => milestonesPage(requireThread(thread, context).repo, page), context, options) }, "set the milestone of", options?.signal)).milestone)),
3855
+ setIssueType: perKind({ issue: enterprise ? "unverified" : true }, async (thread, issueType, options) => toIssueType((await issuePatch(thread, { type: typeof issueType === "object" ? issueType.name : issueType ?? null }, "set the type of", options?.signal)).type)),
3856
+ reactions: perKind({
3857
+ issue: true,
3858
+ pull_request: true,
3859
+ discussion: true
3860
+ }, {
3861
+ react,
3862
+ unreact
3863
+ }),
3864
+ locking: perKind({
3865
+ issue: true,
3866
+ pull_request: true,
3867
+ discussion: true
3868
+ }, {
3869
+ lock: async (thread, options = {}) => {
3870
+ const ref = requireThread(thread, context);
3871
+ if (ref.kind === "discussion") {
3872
+ await graphql("LOCK_LOCKABLE", { id: await nodeId(ref, options) }, options);
3873
+ return;
3874
+ }
3875
+ await fetcher.raw(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/lock`, {
3876
+ method: "PUT",
3877
+ json: options.reason ? { lock_reason: LOCK_REASONS[options.reason] } : {},
3878
+ signal: options.signal
3879
+ });
3880
+ },
3881
+ unlock: async (thread, options) => {
3882
+ const ref = requireThread(thread, context);
3883
+ if (ref.kind === "discussion") {
3884
+ await graphql("UNLOCK_LOCKABLE", { id: await nodeId(ref, options) }, options);
3885
+ return;
3886
+ }
3887
+ await fetcher.raw(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/lock`, {
3888
+ method: "DELETE",
3889
+ signal: options?.signal
3890
+ });
3891
+ }
3892
+ }),
3893
+ hiding: perKind({
3894
+ issue: true,
3895
+ pull_request: true,
3896
+ discussion: true
3897
+ }, {
3898
+ hideComment: async (ref, reason, options) => {
3899
+ await graphql("MINIMIZE_COMMENT", {
3900
+ id: await commentNodeId(ref, options),
3901
+ classifier: reason.toUpperCase()
3902
+ }, options);
3903
+ },
3904
+ unhideComment: async (ref, options) => {
3905
+ await graphql("UNMINIMIZE_COMMENT", { id: await commentNodeId(ref, options) }, options);
3906
+ }
3907
+ }),
3908
+ reactionsPage: perKind({
3909
+ issue: true,
3910
+ pull_request: true,
3911
+ discussion: !anonymous
3912
+ }, reactionsPage),
3913
+ transfer: verb(true, async (thread, repo, options) => {
3914
+ const ref = requireThread(thread, context);
3915
+ if (ref.kind !== "issue") throw new UnsupportedOperationError("GitHub transfers issues only", context);
3916
+ const target = await graphql("REPOSITORY_ID", {
3917
+ owner: repo.owner,
3918
+ name: repo.name
3919
+ }, options);
3920
+ if (!target.repository) throw new NotFoundError(`Repository ${repo.owner}/${repo.name} not found`, 404, "", context);
3921
+ const data = await graphql("TRANSFER_ISSUE", {
3922
+ issue: await nodeId(ref, options),
3923
+ repo: target.repository.id
3924
+ }, options);
3925
+ return {
3926
+ forge: FORGE,
3927
+ instance,
3928
+ repo,
3929
+ kind: "issue",
3930
+ number: String(data.transferIssue.issue.number),
3931
+ externalId: data.transferIssue.issue.id
3932
+ };
3933
+ }),
3934
+ markDuplicate: verb(true, async (thread, canonical, options) => {
3935
+ await graphql("MARK_DUPLICATE", {
3936
+ canonical: await nodeId(canonical, options),
3937
+ duplicate: await nodeId(thread, options)
3938
+ }, options);
3939
+ }),
3940
+ setLabels: perKind({
3941
+ issue: true,
3942
+ pull_request: true
3943
+ }, async (thread, labels, options) => {
3944
+ const ref = requireIssueOrPull(thread, context, "label");
3945
+ return toLabels((await fetcher.json(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/labels`, {
3946
+ method: "PUT",
3947
+ json: { labels },
3948
+ signal: options?.signal
3949
+ })).data);
3950
+ }),
3951
+ setAssignees: perKind({
3952
+ issue: true,
3953
+ pull_request: true
3954
+ }, async (thread, assignees, options) => {
3955
+ return ((await issuePatch(thread, { assignees: assignees.map(actorLogin) }, "assign", options?.signal)).assignees ?? []).flatMap((user) => toActor(instance, user) ?? []);
3956
+ }),
3957
+ requestReview: perKind({ pull_request: true }, async (thread, reviewers, options) => {
3958
+ const ref = requireThread(thread, context);
3959
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only pull requests have reviewers", context);
3960
+ const teams = reviewers.filter((reviewer) => typeof reviewer !== "string" && reviewer.typeRaw === "Team").map(actorLogin);
3961
+ const users = reviewers.filter((reviewer) => typeof reviewer === "string" || reviewer.typeRaw !== "Team").map(actorLogin);
3962
+ await fetcher.raw(`${threadPath(ref)}/requested_reviewers`, {
3963
+ method: "POST",
3964
+ json: {
3965
+ reviewers: users,
3966
+ ...teams.length ? { team_reviewers: teams } : {}
3967
+ },
3968
+ signal: options?.signal
3969
+ });
3970
+ }),
3971
+ close: perKind(ISSUE_LIKE, (ref, options_) => setState(ref, "closed", options_)),
3972
+ reopen: perKind({
3973
+ issue: true,
3974
+ pull_request: true,
3975
+ discussion: true
3976
+ }, (ref, options) => setState(ref, "open", options)),
3977
+ merge: verb(true, merge),
3978
+ updateBranch: verb(true, updateBranch),
3979
+ closingIssuesPage: verb(!anonymous, async (thread, listOptions = {}) => closingPage(requirePull(thread, "read for the issues they close"), "CLOSING_ISSUES", listOptions)),
3980
+ closingPullRequestsPage: verb(!anonymous, async (thread, listOptions = {}) => {
3981
+ const ref = requireThread(thread, context);
3982
+ if (ref.kind !== "issue") throw new UnsupportedOperationError("Only issues are closed by pull requests", context);
3983
+ return closingPage(ref, "CLOSING_PULL_REQUESTS", listOptions);
3984
+ }),
3985
+ subscriptions: perKind(ISSUE_LIKE, {
3986
+ subscription: async (thread, options) => {
3987
+ const { state } = await subscriptionNode(thread, options);
3988
+ return state === "SUBSCRIBED" ? "subscribed" : state === "IGNORED" ? "ignored" : "none";
3989
+ },
3990
+ subscribe: (thread, options) => setSubscription(thread, "SUBSCRIBED", options),
3991
+ unsubscribe: (thread, options) => setSubscription(thread, "UNSUBSCRIBED", options)
3992
+ })
3993
+ }
3994
+ };
3995
+ return appItself ? supportOnly(spec, ["installations"]) : spec;
3996
+ }
3997
+ /** Creates a GitHub provider for github.com or a GitHub Enterprise Server instance. */
3998
+ const github = /* @__PURE__ */ defineForgeProvider({
3999
+ forge: FORGE,
4000
+ hasWeb: true,
4001
+ baseUrl: "https://api.github.com",
4002
+ anonymous: true,
4003
+ instance: webHost,
4004
+ headers: {
4005
+ "accept": "application/vnd.github+json",
4006
+ "x-github-api-version": "2022-11-28"
4007
+ },
4008
+ prepare: ({ options, baseUrl, headers, state }) => options.auth?.type === "app" ? state ?? createAppCredentials(options.auth, {
4009
+ baseUrl,
4010
+ fetch: options.fetch,
4011
+ timeout: options.timeout,
4012
+ onRetry: options.onRetry,
4013
+ onRateLimit: options.onRateLimit,
4014
+ headers
4015
+ }) : void 0,
4016
+ authHeaders: ({ options, state }) => createAuthHeaders(options.auth, state),
4017
+ webhooks: githubWebhooks,
4018
+ setup: setupGitHub
4019
+ });
4020
+ const PULL_CHECK_READS = /* @__PURE__ */ new Set([
4021
+ "threads.get",
4022
+ "threads.getMany",
4023
+ "threads.list",
4024
+ "threads.closingPullRequests"
4025
+ ]);
4026
+ /**
4027
+ * Token scopes and fine-grained permissions GitHub documents per endpoint
4028
+ * group. Classic scopes are the ones an OAuth consent screen asks for; the
4029
+ * permissions are the fine-grained token and app equivalents.
4030
+ */
4031
+ function githubScopesFor(verb) {
4032
+ const [group = "", name = ""] = verb.split(".");
4033
+ if (group === "webhooks") return name === "verify" || name === "ingest" ? {} : {
4034
+ token: ["admin:repo_hook", "admin:org_hook"],
4035
+ permissions: { webhooks: "admin" }
4036
+ };
4037
+ if (group === "notifications") return {
4038
+ token: ["notifications"],
4039
+ note: "Notifications need a classic personal access token or an OAuth app token; fine-grained tokens and GitHub Apps have no access to them"
4040
+ };
4041
+ if (group === "securityAlerts") return {
4042
+ token: ["security_events", "repo"],
4043
+ permissions: {
4044
+ vulnerability_alerts: "read",
4045
+ secret_scanning_alerts: "read",
4046
+ code_scanning_alerts: "read",
4047
+ repository_advisories: "read"
4048
+ },
4049
+ note: "Drafts and private vulnerability reports need a security manager, an administrator, or a collaborator on the advisory"
4050
+ };
4051
+ if (group === "installations") return { note: "App credentials: an app JWT signed with the app private key" };
4052
+ if (verb === "users.block" || verb === "users.unblock") return {
4053
+ token: ["user"],
4054
+ permissions: { blocking: "write" },
4055
+ note: "Needs a user token: a GitHub App installation cannot block for an account"
4056
+ };
4057
+ if (verb === "orgs.block" || verb === "orgs.unblock") return {
4058
+ token: ["admin:org"],
4059
+ permissions: { organization_user_blocking: "write" }
4060
+ };
4061
+ if (group === "users" || group === "search") return {
4062
+ token: ["read:user"],
4063
+ permissions: {}
4064
+ };
4065
+ if (group === "orgs") return {
4066
+ token: ["read:org"],
4067
+ permissions: { members: "read" }
4068
+ };
4069
+ if (verb === "threads.checks") return {
4070
+ token: ["repo"],
4071
+ permissions: {
4072
+ pull_requests: "read",
4073
+ checks: "read",
4074
+ statuses: "read"
4075
+ }
4076
+ };
4077
+ if (verb === "checks.list") return {
4078
+ token: ["repo"],
4079
+ permissions: {
4080
+ checks: "read",
4081
+ statuses: "read"
4082
+ }
4083
+ };
4084
+ if (verb === "checks.get") return {
4085
+ token: ["repo"],
4086
+ permissions: { checks: "read" }
4087
+ };
4088
+ if (verb === "checks.rerun") return {
4089
+ token: ["repo"],
4090
+ permissions: {
4091
+ checks: "write",
4092
+ actions: "write"
4093
+ },
4094
+ note: "A check run created by GitHub Actions is re-run as its job, which needs `actions: write`"
4095
+ };
4096
+ if (group === "ci") return {
4097
+ token: ["repo"],
4098
+ permissions: { actions: WRITE_VERBS.has(verb) ? "write" : "read" }
4099
+ };
4100
+ if (verb === "checks.report") return {
4101
+ token: ["repo:status"],
4102
+ permissions: {
4103
+ checks: "write",
4104
+ statuses: "write"
4105
+ }
4106
+ };
4107
+ if (verb === "threads.updateBranch") return {
4108
+ token: ["repo", "public_repo"],
4109
+ permissions: {
4110
+ pull_requests: "write",
4111
+ contents: "write"
4112
+ },
4113
+ note: "A GitHub App needs `contents: write` on the head repository"
4114
+ };
4115
+ if (verb === "repos.issueTypes") return {
4116
+ token: ["repo"],
4117
+ permissions: { metadata: "read" }
4118
+ };
4119
+ if (verb === "repos.branchRules") return {
4120
+ token: ["repo", "public_repo"],
4121
+ permissions: {
4122
+ contents: "read",
4123
+ metadata: "read",
4124
+ administration: "read"
4125
+ },
4126
+ note: "Classic branch protection shows its approvals only to an admin of the repository, or with `administration: read`"
4127
+ };
4128
+ if (verb === "threads.setIssueType") return {
4129
+ token: ["repo", "public_repo"],
4130
+ permissions: { issues: "write" },
4131
+ note: "Needs push access: without it, GitHub leaves the type unchanged"
4132
+ };
4133
+ const write = WRITE_VERBS.has(verb);
4134
+ if (PULL_CHECK_READS.has(verb)) return {
4135
+ token: ["repo", "public_repo"],
4136
+ permissions: {
4137
+ issues: "read",
4138
+ pull_requests: "read",
4139
+ checks: "read",
4140
+ statuses: "read"
4141
+ },
4142
+ note: "The `checks` of a pull request are read from its check runs and commit statuses"
4143
+ };
4144
+ if (group === "threads") return {
4145
+ token: ["repo", "public_repo"],
4146
+ permissions: {
4147
+ issues: write ? "write" : "read",
4148
+ pull_requests: write ? "write" : "read"
4149
+ }
4150
+ };
4151
+ if (group === "repos" || group === "contents" || group === "releases") return {
4152
+ token: ["repo", "public_repo"],
4153
+ permissions: {
4154
+ contents: write ? "write" : "read",
4155
+ metadata: "read"
4156
+ }
4157
+ };
4158
+ return {};
4159
+ }
4160
+ //#endregion
4161
+ export { toRepoRef as a, github, toLabels as i, toActor as n, toThreadState as o, toIssueType as r, FORGE as t };