@vite-hub/forge 0.0.0 → 0.3.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,2324 @@
1
+ import { $ as toDate, A as hexColour, B as milestoneId, C as createListing, F as latestCommentOf, G as requireIssueOrPull, I as mapConcurrent, K as requireThread, L as memo, M as isFirstPage, O as getManyConcurrently, Q as teamOrg, R as memoBy, U as rateLimitPart, X as summariseChecks, Y as soleMergeMethod, at as versionAtLeast, ct as isNamespaceRef, d as NotFoundError, et as toFileStatus, g as UnsupportedOperationError, it as toWarning, j as hostOf, k as hasEveryLabel, n as BranchMovedError, nt as toPage, o as ForgeError, pt as reactionContent, q as resolveToken, rt as toPullStats, tt as toMergeError, y as actorLogin } from "./utils-DC7MBR65-B7Vr2hFm.js";
2
+ import { C as verb, S as toFileContent, T as githubShapedWeb, _ as reviewState, a as verifyHmacSignature, c as changeBase64, d as eventTime, f as existingFiles, g as perKind, l as defineForgeProvider, m as inDirectories, p as fromBase64, r as nativeEventsFor, s as WRITE_VERBS, t as eventKindsOf } from "./webhooks-Bc6QhmI8-CNgCERCq.js";
3
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/web-khKJ7nW8.mjs
4
+ const RESERVED_PATHS = [
5
+ "-",
6
+ ".well-known",
7
+ "admin",
8
+ "api",
9
+ "assets",
10
+ "attachments",
11
+ "avatars",
12
+ "captcha",
13
+ "explore",
14
+ "issues",
15
+ "login",
16
+ "milestones",
17
+ "notifications",
18
+ "org",
19
+ "pulls",
20
+ "repo",
21
+ "repo-avatars",
22
+ "search",
23
+ "user"
24
+ ];
25
+ function forgejoWeb(forge, baseUrl) {
26
+ return {
27
+ forge,
28
+ baseUrl,
29
+ apiPath: "/api/v1",
30
+ links: ({ baseUrl }) => githubShapedWeb(baseUrl.replace(/\/api\/v1$/, ""), {
31
+ pull: "pulls",
32
+ sections: { stargazers: "stars" },
33
+ commentFragment: "issuecomment-",
34
+ file: (at) => /^[0-9a-f]{40}$/.test(at) ? `/src/commit/${at}` : `/src/${encodeURIComponent(at)}`,
35
+ parseFile: ([route, qualifier, ref, ...rest]) => {
36
+ if (route !== "src" || !qualifier || !ref) return;
37
+ if (qualifier === "branch" || qualifier === "tag" || qualifier === "commit") return rest.length ? {
38
+ at: ref,
39
+ path: rest.join("/")
40
+ } : void 0;
41
+ return {
42
+ at: qualifier,
43
+ path: [ref, ...rest].join("/")
44
+ };
45
+ },
46
+ lineFragment: (line) => `L${line}`,
47
+ reserved: RESERVED_PATHS
48
+ })
49
+ };
50
+ }
51
+ const FORGEJO_WEB = /* @__PURE__ */ forgejoWeb("forgejo", "https://codeberg.org");
52
+ //#endregion
53
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/definition-0wjaAw2i.mjs
54
+ const FORGEJO_HEADERS = {
55
+ signature: ["x-forgejo-signature", "x-gitea-signature"],
56
+ event: [
57
+ "x-forgejo-event",
58
+ "x-gitea-event",
59
+ "x-github-event"
60
+ ],
61
+ delivery: ["x-forgejo-delivery", "x-gitea-delivery"]
62
+ };
63
+ /** Native Forgejo and Gitea event names per normalised kind, for hook subscriptions. */
64
+ const FORGEJO_NATIVE_EVENTS = {
65
+ comment: ["issue_comment", "pull_request_comment"],
66
+ review: [
67
+ "pull_request_review_approved",
68
+ "pull_request_review_rejected",
69
+ "pull_request_review_comment"
70
+ ],
71
+ review_comment: ["pull_request_review_comment"],
72
+ state_change: [
73
+ "issues",
74
+ "pull_request",
75
+ "pull_request_sync"
76
+ ],
77
+ label: ["issue_label", "pull_request_label"],
78
+ assignment: ["issue_assign", "pull_request_assign"],
79
+ push: ["push"],
80
+ ref: ["create", "delete"],
81
+ release: ["release"],
82
+ fork: ["fork"],
83
+ wiki: ["wiki"]
84
+ };
85
+ /** Normalised kinds and actions Forgejo and Gitea deliveries translate into. */
86
+ const FORGEJO_WEBHOOK_EVENTS = [
87
+ {
88
+ kind: "comment",
89
+ action: "created"
90
+ },
91
+ {
92
+ kind: "comment",
93
+ action: "edited"
94
+ },
95
+ {
96
+ kind: "comment",
97
+ action: "deleted"
98
+ },
99
+ {
100
+ kind: "review",
101
+ action: "submitted"
102
+ },
103
+ {
104
+ kind: "review_comment",
105
+ action: "created"
106
+ },
107
+ {
108
+ kind: "state_change",
109
+ action: "opened"
110
+ },
111
+ {
112
+ kind: "state_change",
113
+ action: "closed"
114
+ },
115
+ {
116
+ kind: "state_change",
117
+ action: "reopened"
118
+ },
119
+ {
120
+ kind: "state_change",
121
+ action: "merged"
122
+ },
123
+ {
124
+ kind: "label",
125
+ action: "edited"
126
+ },
127
+ {
128
+ kind: "label",
129
+ action: "unlabelled"
130
+ },
131
+ {
132
+ kind: "assignment",
133
+ action: "assigned"
134
+ },
135
+ {
136
+ kind: "assignment",
137
+ action: "unassigned"
138
+ },
139
+ { kind: "push" },
140
+ {
141
+ kind: "ref",
142
+ action: "created"
143
+ },
144
+ {
145
+ kind: "ref",
146
+ action: "deleted"
147
+ },
148
+ {
149
+ kind: "release",
150
+ action: "published"
151
+ },
152
+ {
153
+ kind: "release",
154
+ action: "edited"
155
+ },
156
+ {
157
+ kind: "release",
158
+ action: "deleted"
159
+ },
160
+ {
161
+ kind: "fork",
162
+ action: "created"
163
+ },
164
+ {
165
+ kind: "wiki",
166
+ action: "created"
167
+ },
168
+ {
169
+ kind: "wiki",
170
+ action: "edited"
171
+ },
172
+ {
173
+ kind: "wiki",
174
+ action: "deleted"
175
+ },
176
+ {
177
+ kind: "wiki",
178
+ action: "renamed"
179
+ }
180
+ ];
181
+ /** The id of the built-in user that Forgejo and Gitea Actions act as. */
182
+ const ACTIONS_USER_ID = -2;
183
+ /** Normalisers take the origin because they serve both Forgejo and Gitea. */
184
+ function toActor(origin, user) {
185
+ if (!user) return;
186
+ return {
187
+ ...origin,
188
+ login: user.login,
189
+ id: String(user.id ?? user.login),
190
+ name: user.full_name || void 0,
191
+ avatarUrl: user.avatar_url,
192
+ url: user.html_url,
193
+ typeRaw: user.is_bot === void 0 ? void 0 : user.is_bot ? "bot" : "user",
194
+ isBotHint: user.is_bot === true || user.id === ACTIONS_USER_ID || user.login.endsWith("[bot]")
195
+ };
196
+ }
197
+ function toRepoRef(origin, repo) {
198
+ const [owner, name] = repo.full_name.split("/");
199
+ return {
200
+ ...origin,
201
+ owner: repo.owner?.login ?? owner ?? "",
202
+ name: repo.name ?? name ?? "",
203
+ externalId: repo.id === void 0 ? void 0 : String(repo.id)
204
+ };
205
+ }
206
+ /** Forgejo and Gitea teams have no slug, so the name stands in for one. */
207
+ function toTeam(origin, org, raw) {
208
+ return {
209
+ ref: {
210
+ ...origin,
211
+ org,
212
+ id: String(raw.id),
213
+ slug: raw.name
214
+ },
215
+ name: raw.name,
216
+ description: raw.description || void 0,
217
+ permission: raw.permission,
218
+ raw
219
+ };
220
+ }
221
+ const MERGE_STYLES = {
222
+ "merge": "merge",
223
+ "rebase": "rebase",
224
+ "rebase-merge": "rebase_merge",
225
+ "squash": "squash",
226
+ "fast-forward-only": "fast_forward_only"
227
+ };
228
+ function toRepo(origin, raw) {
229
+ return {
230
+ ref: toRepoRef(origin, raw),
231
+ description: raw.description || void 0,
232
+ defaultBranch: raw.default_branch,
233
+ visibility: raw.internal ? "internal" : raw.private ? "private" : "public",
234
+ visibilityRaw: raw.internal ? "internal" : raw.private ? "private" : "public",
235
+ isFork: raw.fork ?? false,
236
+ isArchived: raw.archived ?? false,
237
+ parent: raw.parent ? toRepoRef(origin, raw.parent) : void 0,
238
+ topics: raw.topics ?? [],
239
+ url: raw.html_url,
240
+ cloneUrls: raw.clone_url || raw.ssh_url ? {
241
+ https: raw.clone_url,
242
+ ssh: raw.ssh_url
243
+ } : void 0,
244
+ createdAt: toDate(raw.created_at),
245
+ updatedAt: toDate(raw.updated_at),
246
+ openIssueCount: raw.open_issues_count,
247
+ openPullCount: raw.open_pr_counter,
248
+ owner: toActor(origin, raw.owner),
249
+ language: raw.language || void 0,
250
+ homepage: raw.website || void 0,
251
+ licence: raw.licenses?.length === 1 ? raw.licenses[0] : void 0,
252
+ stars: raw.stars_count,
253
+ forks: raw.forks_count,
254
+ watchers: raw.watchers_count,
255
+ mergeMethods: raw.allow_merge_commits === void 0 ? void 0 : [
256
+ ...raw.allow_merge_commits ? ["merge"] : [],
257
+ ...raw.allow_squash_merge ? ["squash"] : [],
258
+ ...raw.allow_rebase ? ["rebase"] : [],
259
+ ...raw.allow_rebase_explicit ? ["rebase_merge"] : [],
260
+ ...raw.allow_fast_forward_only_merge ? ["fast_forward_only"] : []
261
+ ],
262
+ defaultMergeMethod: MERGE_STYLES[raw.default_merge_style ?? ""],
263
+ deleteBranchOnMerge: raw.default_delete_branch_after_merge,
264
+ features: raw.has_issues === void 0 ? void 0 : {
265
+ issues: raw.has_issues,
266
+ pullRequests: raw.has_pull_requests ?? true,
267
+ discussions: false,
268
+ wiki: raw.has_wiki ?? false,
269
+ projects: raw.has_projects ?? false,
270
+ releases: raw.has_releases ?? true
271
+ },
272
+ permissions: raw.permissions ? {
273
+ admin: raw.permissions.admin,
274
+ maintain: raw.permissions.admin,
275
+ push: raw.permissions.push,
276
+ triage: raw.permissions.push,
277
+ pull: raw.permissions.pull
278
+ } : void 0,
279
+ raw
280
+ };
281
+ }
282
+ /** Forgejo and Gitea report `owner`, `admin`, `write`, `read` or `none`; there is no triage or maintain role. */
283
+ function toRole(raw) {
284
+ switch (raw) {
285
+ case "owner":
286
+ case "admin": return "admin";
287
+ case "write": return "write";
288
+ case "read": return "read";
289
+ default: return "none";
290
+ }
291
+ }
292
+ function toLabel(raw) {
293
+ return {
294
+ name: raw.name,
295
+ colour: raw.color || void 0,
296
+ description: raw.description || void 0
297
+ };
298
+ }
299
+ function toMilestone(raw) {
300
+ return raw ? {
301
+ id: String(raw.id),
302
+ title: raw.title,
303
+ state: raw.state === "closed" ? "closed" : "open",
304
+ description: raw.description || void 0,
305
+ dueOn: toDate(raw.due_on),
306
+ raw
307
+ } : void 0;
308
+ }
309
+ function toThreadKind(subjectType) {
310
+ switch (subjectType) {
311
+ case "Pull":
312
+ case "PullRequest": return "pull_request";
313
+ case "Issue": return "issue";
314
+ default: return;
315
+ }
316
+ }
317
+ function toSubjectState(state) {
318
+ switch (state) {
319
+ case "open":
320
+ case "closed":
321
+ case "merged": return state;
322
+ default: return "unknown";
323
+ }
324
+ }
325
+ function numberFromUrl(url) {
326
+ return /\/(?:issues|pulls|commits|git\/commits)\/([^/?#]+)/.exec(url ?? "")?.[1];
327
+ }
328
+ function toSubject(origin, raw) {
329
+ const repo = toRepoRef(origin, raw.repository);
330
+ const kind = toThreadKind(raw.subject.type);
331
+ if (kind) return {
332
+ type: "thread",
333
+ thread: {
334
+ ...origin,
335
+ repo,
336
+ kind,
337
+ typeRaw: raw.subject.type,
338
+ number: numberFromUrl(raw.subject.url)
339
+ }
340
+ };
341
+ const sha = raw.subject.type === "Commit" ? numberFromUrl(raw.subject.url) : void 0;
342
+ if (sha) return {
343
+ type: "commit",
344
+ commit: {
345
+ ...origin,
346
+ repo,
347
+ sha
348
+ }
349
+ };
350
+ if (raw.subject.type === "Repository") return {
351
+ type: "repo",
352
+ repo
353
+ };
354
+ return {
355
+ type: "other",
356
+ typeRaw: raw.subject.type,
357
+ repo,
358
+ url: raw.subject.url ?? void 0
359
+ };
360
+ }
361
+ function toNotification(origin, raw) {
362
+ const subject = toSubject(origin, raw);
363
+ const latestComment = latestCommentOf(subject, raw.subject.latest_comment_url);
364
+ return {
365
+ ref: {
366
+ ...origin,
367
+ id: String(raw.id)
368
+ },
369
+ subject,
370
+ subjectTypeRaw: raw.subject.type,
371
+ reason: "unknown",
372
+ unread: raw.unread,
373
+ title: raw.subject.title,
374
+ subjectState: toSubjectState(raw.subject.state),
375
+ subjectStateRaw: raw.subject.state,
376
+ updatedAt: toDate(raw.updated_at) ?? /* @__PURE__ */ new Date(0),
377
+ url: raw.subject.url ?? raw.url,
378
+ ...latestComment ? { latestComment } : {},
379
+ raw
380
+ };
381
+ }
382
+ function toThread(ref, raw) {
383
+ const origin = {
384
+ forge: ref.forge,
385
+ instance: ref.instance
386
+ };
387
+ const kind = (Boolean(raw.pull_request) || Boolean(raw.head)) && ref.kind === "issue" ? "pull_request" : ref.kind;
388
+ const state = raw.merged || raw.pull_request?.merged ? "merged" : raw.state === "open" || raw.state === "closed" ? raw.state : "unknown";
389
+ return {
390
+ ref: {
391
+ ...ref,
392
+ kind,
393
+ externalId: raw.id === void 0 ? ref.externalId : String(raw.id)
394
+ },
395
+ kind,
396
+ title: raw.title,
397
+ body: raw.body ?? void 0,
398
+ state,
399
+ stateRaw: raw.state,
400
+ isDraft: raw.draft ?? raw.pull_request?.draft ?? false,
401
+ author: toActor(origin, raw.user),
402
+ assignees: (raw.assignees ?? []).flatMap((user) => toActor(origin, user) ?? []),
403
+ reviewers: (raw.requested_reviewers ?? []).flatMap((user) => {
404
+ const actor = toActor(origin, user);
405
+ return actor ? [{
406
+ actor,
407
+ state: "pending",
408
+ stateRaw: "requested"
409
+ }] : [];
410
+ }),
411
+ labels: (raw.labels ?? []).map((label) => ({
412
+ name: label.name,
413
+ colour: label.color,
414
+ description: label.description || void 0
415
+ })),
416
+ url: raw.html_url,
417
+ createdAt: toDate(raw.created_at),
418
+ updatedAt: toDate(raw.updated_at),
419
+ closedAt: toDate(raw.closed_at),
420
+ mergedAt: toDate(raw.merged_at ?? raw.pull_request?.merged_at),
421
+ mergedBy: toActor(origin, raw.merged_by),
422
+ lastActivityAt: toDate(raw.updated_at),
423
+ locked: raw.is_locked,
424
+ commentCount: raw.comments,
425
+ milestone: toMilestone(raw.milestone),
426
+ branches: raw.head && raw.base ? {
427
+ head: {
428
+ ref: raw.head.ref,
429
+ sha: raw.head.sha,
430
+ repo: raw.head.repo ? toRepoRef(origin, raw.head.repo) : void 0
431
+ },
432
+ base: {
433
+ ref: raw.base.ref,
434
+ sha: raw.base.sha
435
+ },
436
+ mergeCommitSha: raw.merge_commit_sha ?? void 0
437
+ } : void 0,
438
+ stats: toPullStats({
439
+ additions: raw.additions,
440
+ deletions: raw.deletions,
441
+ changedFileCount: raw.changed_files
442
+ }),
443
+ raw
444
+ };
445
+ }
446
+ function toComment(thread, raw) {
447
+ return {
448
+ ref: {
449
+ forge: thread.forge,
450
+ instance: thread.instance,
451
+ thread,
452
+ id: String(raw.id)
453
+ },
454
+ body: raw.body ?? "",
455
+ author: toActor({
456
+ forge: thread.forge,
457
+ instance: thread.instance
458
+ }, raw.user),
459
+ createdAt: toDate(raw.created_at),
460
+ updatedAt: toDate(raw.updated_at),
461
+ url: raw.html_url,
462
+ raw
463
+ };
464
+ }
465
+ const EVENT_KINDS = {
466
+ comment: "comment",
467
+ review: "review",
468
+ code_comment: "review_comment",
469
+ commit_ref: "commit",
470
+ issue_ref: "referenced",
471
+ pull_ref: "referenced",
472
+ change_issue_ref: "referenced",
473
+ pull_push: "commit",
474
+ label: "label",
475
+ close: "state_change",
476
+ reopen: "state_change",
477
+ merge_pull: "state_change",
478
+ pull_request_ready_for_review: "state_change",
479
+ assignees: "assignment"
480
+ };
481
+ function toEventKind(type) {
482
+ return EVENT_KINDS[type ?? ""] ?? "other";
483
+ }
484
+ function summarise(entry, kind, actor) {
485
+ const who = actor?.login ?? "someone";
486
+ switch (kind) {
487
+ case "comment": return `${who} commented`;
488
+ case "review": return `${who} reviewed`;
489
+ case "review_comment": return `${who} commented on a line`;
490
+ case "commit": return `${who} referenced ${entry.ref_commit_sha?.slice(0, 7) || "a commit"}`;
491
+ case "referenced": return `${who} referenced this${entry.ref_issue ? ` from #${entry.ref_issue.number}` : ""}`;
492
+ case "label": return `${who} changed label ${entry.label?.name ?? ""}`.trim();
493
+ case "state_change": return `${who} ${entry.type ?? "changed state"}`;
494
+ case "assignment": return `${who} assigned ${entry.assignee?.login ?? ""}`.trim();
495
+ default: return `${who} ${entry.type ?? "acted"}`;
496
+ }
497
+ }
498
+ /** `issue_ref`, `pull_ref` and `change_issue_ref` name the thread that mentioned this one. */
499
+ function crossReference(thread, entry) {
500
+ const source = entry.ref_issue;
501
+ if (!source) return { type: "referenced" };
502
+ const [owner = "", name = ""] = source.repository?.full_name.split("/") ?? [];
503
+ const repo = name ? {
504
+ forge: thread.forge,
505
+ instance: thread.instance,
506
+ owner,
507
+ name,
508
+ externalId: source.repository?.id === void 0 ? void 0 : String(source.repository.id)
509
+ } : thread.repo;
510
+ return {
511
+ type: "referenced",
512
+ from: {
513
+ forge: thread.forge,
514
+ instance: thread.instance,
515
+ repo,
516
+ kind: source.pull_request ? "pull_request" : "issue",
517
+ number: String(source.number)
518
+ },
519
+ fromRepo: repo
520
+ };
521
+ }
522
+ function timelineDetail(thread, entry, kind) {
523
+ const origin = {
524
+ forge: thread.forge,
525
+ instance: thread.instance
526
+ };
527
+ switch (kind) {
528
+ case "comment":
529
+ case "review_comment": return {
530
+ type: kind,
531
+ comment: entry.id === void 0 ? void 0 : {
532
+ ...origin,
533
+ thread,
534
+ id: String(entry.id)
535
+ },
536
+ body: entry.body ?? void 0
537
+ };
538
+ case "review": return {
539
+ type: "review",
540
+ state: "unknown",
541
+ body: entry.body || void 0,
542
+ review: entry.review_id ? {
543
+ ...origin,
544
+ thread,
545
+ id: String(entry.review_id)
546
+ } : void 0
547
+ };
548
+ case "referenced": return crossReference(thread, entry);
549
+ default: return;
550
+ }
551
+ }
552
+ function toEvent(thread, entry, source = "poll") {
553
+ const origin = {
554
+ forge: thread.forge,
555
+ instance: thread.instance
556
+ };
557
+ const kind = toEventKind(entry.type);
558
+ const actor = toActor(origin, entry.user);
559
+ return {
560
+ ...origin,
561
+ id: String(entry.id ?? `${thread.number ?? ""}-${entry.type}-${entry.created_at}`),
562
+ kind,
563
+ kindRaw: entry.type,
564
+ summary: summarise(entry, kind, actor),
565
+ ...eventTime(toDate(entry.created_at), /* @__PURE__ */ new Date(0)),
566
+ actor,
567
+ repo: thread.repo,
568
+ thread,
569
+ detail: timelineDetail(thread, entry, kind),
570
+ source,
571
+ payload: entry
572
+ };
573
+ }
574
+ /** Commit status values. `warning` is informational and neither passes nor fails. */
575
+ function statusState(status) {
576
+ switch (status) {
577
+ case "success": return "success";
578
+ case "failure":
579
+ case "error": return "failure";
580
+ case "pending": return "pending";
581
+ case "warning": return "neutral";
582
+ default: return "unknown";
583
+ }
584
+ }
585
+ function toStatusCheck(repo, raw) {
586
+ const state = statusState(raw.status);
587
+ return {
588
+ ref: {
589
+ forge: repo.forge,
590
+ instance: repo.instance,
591
+ repo,
592
+ id: String(raw.id),
593
+ type: "status"
594
+ },
595
+ name: raw.context,
596
+ state,
597
+ stateRaw: raw.status,
598
+ url: raw.target_url || void 0,
599
+ startedAt: toDate(raw.created_at),
600
+ completedAt: state === "pending" ? void 0 : toDate(raw.updated_at),
601
+ raw
602
+ };
603
+ }
604
+ function toStatusChecks(repo, raw) {
605
+ return (raw.statuses ?? []).map((status) => toStatusCheck(repo, status));
606
+ }
607
+ /** Every Actions run and job status behind each normalised state, as the repeated `status` filter takes them. */
608
+ const ACTION_STATES = {
609
+ pending: [
610
+ "waiting",
611
+ "running",
612
+ "blocked"
613
+ ],
614
+ success: ["success"],
615
+ failure: ["failure", "cancelled"],
616
+ neutral: ["skipped"]
617
+ };
618
+ /** Gitea's statuses and conclusions behind each normalised state, as its repeated `status` filter takes them. */
619
+ const GITEA_ACTION_STATES = {
620
+ pending: [
621
+ "queued",
622
+ "waiting",
623
+ "in_progress"
624
+ ],
625
+ success: ["success"],
626
+ failure: ["failure", "cancelled"],
627
+ neutral: ["skipped"]
628
+ };
629
+ function stateOf(states) {
630
+ return new Map(Object.entries(states).flatMap(([state, raws]) => raws.map((raw) => [raw, state])));
631
+ }
632
+ const ACTION_STATE_OF = /* @__PURE__ */ stateOf(ACTION_STATES);
633
+ const GITEA_ACTION_STATE_OF = /* @__PURE__ */ stateOf(GITEA_ACTION_STATES);
634
+ function actionState(status) {
635
+ return ACTION_STATE_OF.get(status) ?? "unknown";
636
+ }
637
+ function giteaActionState(raw) {
638
+ return GITEA_ACTION_STATE_OF.get(raw.status === "completed" ? raw.conclusion ?? "" : raw.status) ?? "unknown";
639
+ }
640
+ /** Forgejo and Gitea write the zero Unix time for a run or job that never started or stopped. */
641
+ function actionTime(value) {
642
+ const date = toDate(value);
643
+ return date && date.getTime() > 0 ? date : void 0;
644
+ }
645
+ /** `prettyref` is the short ref; pull request runs carry `#<number>` or a bare sha instead of a branch. */
646
+ function actionBranch(raw) {
647
+ const ref = raw.prettyref;
648
+ return ref && !ref.startsWith("#") && ref !== raw.commit_sha ? ref : void 0;
649
+ }
650
+ function toActionRun(repo, raw) {
651
+ const state = actionState(raw.status);
652
+ return {
653
+ ref: {
654
+ forge: repo.forge,
655
+ instance: repo.instance,
656
+ repo,
657
+ id: String(raw.id)
658
+ },
659
+ name: raw.workflow_id || raw.title || String(raw.id),
660
+ state,
661
+ stateRaw: raw.status,
662
+ number: raw.index_in_repo === void 0 ? void 0 : String(raw.index_in_repo),
663
+ eventRaw: raw.trigger_event || raw.event,
664
+ branch: actionBranch(raw),
665
+ sha: raw.commit_sha || void 0,
666
+ url: raw.html_url || void 0,
667
+ actor: toActor({
668
+ forge: repo.forge,
669
+ instance: repo.instance
670
+ }, raw.trigger_user),
671
+ createdAt: toDate(raw.created),
672
+ startedAt: actionTime(raw.started),
673
+ completedAt: state === "pending" ? void 0 : actionTime(raw.stopped),
674
+ raw
675
+ };
676
+ }
677
+ function toActionJob(run, raw) {
678
+ return {
679
+ ref: {
680
+ forge: run.forge,
681
+ instance: run.instance,
682
+ repo: run.repo,
683
+ id: String(raw.id),
684
+ run
685
+ },
686
+ name: raw.name,
687
+ state: actionState(raw.status),
688
+ stateRaw: raw.status,
689
+ url: raw.html_url || void 0,
690
+ raw
691
+ };
692
+ }
693
+ function toGiteaActionRun(repo, raw) {
694
+ const state = giteaActionState(raw);
695
+ return {
696
+ ref: {
697
+ forge: repo.forge,
698
+ instance: repo.instance,
699
+ repo,
700
+ id: String(raw.id)
701
+ },
702
+ name: raw.path?.split("@refs/")[0] || raw.display_title || String(raw.id),
703
+ state,
704
+ stateRaw: raw.status,
705
+ number: raw.run_number === void 0 ? void 0 : String(raw.run_number),
706
+ eventRaw: raw.event,
707
+ branch: raw.head_branch || void 0,
708
+ sha: raw.head_sha || void 0,
709
+ url: raw.html_url || void 0,
710
+ actor: toActor({
711
+ forge: repo.forge,
712
+ instance: repo.instance
713
+ }, raw.actor),
714
+ createdAt: toDate(raw.created_at),
715
+ startedAt: actionTime(raw.started_at),
716
+ completedAt: state === "pending" ? void 0 : actionTime(raw.completed_at),
717
+ raw
718
+ };
719
+ }
720
+ function toGiteaActionJob(run, raw) {
721
+ const state = giteaActionState(raw);
722
+ return {
723
+ ref: {
724
+ forge: run.forge,
725
+ instance: run.instance,
726
+ repo: run.repo,
727
+ id: String(raw.id),
728
+ run
729
+ },
730
+ name: raw.name,
731
+ state,
732
+ stateRaw: raw.status,
733
+ url: raw.html_url || void 0,
734
+ startedAt: actionTime(raw.started_at),
735
+ completedAt: state === "pending" ? void 0 : actionTime(raw.completed_at),
736
+ raw
737
+ };
738
+ }
739
+ function toRelease(repo, raw) {
740
+ const origin = {
741
+ forge: repo.forge,
742
+ instance: repo.instance
743
+ };
744
+ const ref = {
745
+ ...origin,
746
+ repo,
747
+ id: String(raw.id),
748
+ tag: raw.tag_name
749
+ };
750
+ return {
751
+ ref,
752
+ name: raw.name || void 0,
753
+ tag: raw.tag_name,
754
+ body: raw.body || void 0,
755
+ isDraft: raw.draft,
756
+ isPrerelease: raw.prerelease,
757
+ author: raw.author ? toActor(repo, raw.author) : void 0,
758
+ publishedAt: raw.draft ? void 0 : toDate(raw.published_at),
759
+ createdAt: toDate(raw.created_at),
760
+ url: raw.html_url,
761
+ assets: raw.assets?.map((asset) => ({
762
+ ...asset.id === void 0 ? {} : { ref: {
763
+ ...origin,
764
+ repo,
765
+ release: ref,
766
+ id: String(asset.id)
767
+ } },
768
+ name: asset.name,
769
+ url: asset.browser_download_url,
770
+ size: asset.size,
771
+ downloadCount: asset.download_count
772
+ })),
773
+ raw
774
+ };
775
+ }
776
+ function toReviewComment(thread, raw) {
777
+ return {
778
+ ref: {
779
+ forge: thread.forge,
780
+ instance: thread.instance,
781
+ thread,
782
+ id: String(raw.id)
783
+ },
784
+ body: raw.body ?? "",
785
+ author: toActor(thread, raw.user),
786
+ path: raw.path,
787
+ line: raw.position || raw.original_position || void 0,
788
+ side: raw.position ? "right" : raw.original_position ? "left" : void 0,
789
+ createdAt: toDate(raw.created_at),
790
+ url: raw.html_url,
791
+ raw
792
+ };
793
+ }
794
+ /** One conversation per file, side and line, as the web UI groups them; its first comment holds the id and the resolver. */
795
+ function toReviewThreads(thread, raws) {
796
+ const conversations = /* @__PURE__ */ new Map();
797
+ for (const raw of raws.toSorted((left, right) => left.id - right.id)) {
798
+ const key = JSON.stringify([
799
+ raw.path,
800
+ raw.position ? "right" : "left",
801
+ raw.position || raw.original_position
802
+ ]);
803
+ conversations.set(key, [...conversations.get(key) ?? [], raw]);
804
+ }
805
+ return [...conversations.values()].map((comments) => {
806
+ const first = comments[0];
807
+ const id = String(first.id);
808
+ const resolved = Boolean(first.resolver);
809
+ const { path, line, side } = toReviewComment(thread, first);
810
+ return {
811
+ id,
812
+ resolved,
813
+ path,
814
+ line,
815
+ side,
816
+ comments: comments.map((raw) => ({
817
+ ...toReviewComment(thread, raw),
818
+ thread: {
819
+ id,
820
+ resolved
821
+ }
822
+ })),
823
+ raw: comments
824
+ };
825
+ });
826
+ }
827
+ function toReview(thread, raw, comments) {
828
+ return {
829
+ ref: {
830
+ forge: thread.forge,
831
+ instance: thread.instance,
832
+ thread,
833
+ id: String(raw.id)
834
+ },
835
+ author: toActor(thread, raw.user),
836
+ state: reviewState(raw.state?.toLowerCase() === "request_changes" ? "changes_requested" : raw.state),
837
+ stateRaw: raw.state,
838
+ body: raw.body || void 0,
839
+ submittedAt: toDate(raw.submitted_at),
840
+ comments,
841
+ url: raw.html_url,
842
+ raw
843
+ };
844
+ }
845
+ function toChangedFile(raw) {
846
+ return {
847
+ path: raw.filename,
848
+ previousPath: raw.previous_filename,
849
+ status: toFileStatus(raw.status),
850
+ statusRaw: raw.status,
851
+ additions: raw.additions,
852
+ deletions: raw.deletions
853
+ };
854
+ }
855
+ function toFileCommit(repo, raw) {
856
+ return {
857
+ ref: {
858
+ forge: repo.forge,
859
+ instance: repo.instance,
860
+ repo,
861
+ sha: raw.sha
862
+ },
863
+ sha: raw.sha,
864
+ message: raw.message ?? "",
865
+ author: {
866
+ name: raw.author?.name,
867
+ email: raw.author?.email,
868
+ date: toDate(raw.author?.date)
869
+ },
870
+ committer: {
871
+ name: raw.committer?.name,
872
+ email: raw.committer?.email,
873
+ date: toDate(raw.committer?.date)
874
+ },
875
+ parents: raw.parents?.flatMap((parent) => parent.sha ? [parent.sha] : []) ?? [],
876
+ url: raw.html_url,
877
+ raw
878
+ };
879
+ }
880
+ function toCommit(repo, raw) {
881
+ const origin = {
882
+ forge: repo.forge,
883
+ instance: repo.instance
884
+ };
885
+ return {
886
+ ref: {
887
+ ...origin,
888
+ repo,
889
+ sha: raw.sha
890
+ },
891
+ sha: raw.sha,
892
+ message: raw.commit?.message ?? "",
893
+ author: {
894
+ actor: toActor(origin, raw.author),
895
+ name: raw.commit?.author?.name,
896
+ email: raw.commit?.author?.email,
897
+ date: toDate(raw.commit?.author?.date)
898
+ },
899
+ committer: {
900
+ actor: toActor(origin, raw.committer),
901
+ name: raw.commit?.committer?.name,
902
+ email: raw.commit?.committer?.email,
903
+ date: toDate(raw.commit?.committer?.date)
904
+ },
905
+ parents: raw.parents?.flatMap((parent) => parent.sha ? [parent.sha] : []) ?? [],
906
+ url: raw.html_url,
907
+ ...raw.stats ? { stats: {
908
+ additions: raw.stats.additions ?? 0,
909
+ deletions: raw.stats.deletions ?? 0,
910
+ total: raw.stats.total
911
+ } } : {},
912
+ ...raw.files ? { files: raw.files.map(toChangedFile) } : {},
913
+ raw
914
+ };
915
+ }
916
+ function toBranch(raw) {
917
+ return {
918
+ name: raw.name,
919
+ sha: raw.commit?.id ?? "",
920
+ isProtected: raw.protected,
921
+ raw
922
+ };
923
+ }
924
+ /** The branch reports the protection rule that matches it, so one read covers both checks and approvals. */
925
+ function toBranchRules(raw) {
926
+ return {
927
+ branch: raw.name,
928
+ requiredChecks: raw.enable_status_check ? (raw.status_check_contexts ?? []).map((name) => ({ name })) : [],
929
+ requiredApprovals: raw.required_approvals ?? 0,
930
+ raw
931
+ };
932
+ }
933
+ function toTag(raw) {
934
+ return {
935
+ name: raw.name,
936
+ sha: raw.commit?.sha ?? raw.id ?? "",
937
+ raw
938
+ };
939
+ }
940
+ const TREE_TYPES = {
941
+ blob: "file",
942
+ tree: "directory",
943
+ commit: "submodule"
944
+ };
945
+ function toTreeEntry(raw) {
946
+ return {
947
+ path: raw.path,
948
+ type: raw.mode === "120000" ? "symlink" : TREE_TYPES[raw.type ?? ""] ?? "file",
949
+ sha: raw.sha,
950
+ size: raw.size,
951
+ mode: raw.mode
952
+ };
953
+ }
954
+ function toWebhook(target, raw) {
955
+ const nativeEvents = raw.events ?? [];
956
+ return {
957
+ ref: {
958
+ forge: target.forge,
959
+ instance: target.instance,
960
+ target,
961
+ id: String(raw.id)
962
+ },
963
+ url: raw.config?.url ?? "",
964
+ events: eventKindsOf(FORGEJO_NATIVE_EVENTS, nativeEvents),
965
+ nativeEvents,
966
+ active: raw.active ?? true,
967
+ contentType: raw.config?.content_type === "form" ? "form" : "json",
968
+ createdAt: toDate(raw.created_at),
969
+ updatedAt: toDate(raw.updated_at),
970
+ raw
971
+ };
972
+ }
973
+ /** A full page is followed even when `x-total-count` disagrees, because timelines report the page's own length. */
974
+ function countedNextUrl(url, count, totalHeader) {
975
+ const next = new URL(url);
976
+ const page = Number(next.searchParams.get("page")) || 1;
977
+ const limit = Number(next.searchParams.get("limit")) || void 0;
978
+ if (count === 0 || limit !== void 0 && count > limit) return;
979
+ const size = limit ?? count;
980
+ const total = totalHeader === null ? NaN : Number(totalHeader);
981
+ if (!(Number.isFinite(total) && (page - 1) * size + count < total) && count !== limit) return;
982
+ next.searchParams.set("page", String(page + 1));
983
+ next.searchParams.set("limit", String(Math.min(count, size)));
984
+ return next.toString();
985
+ }
986
+ /** `fetcher` with `page` and `items` that also continue listings Forgejo and Gitea page without a `Link` header. */
987
+ function countedPages(fetcher) {
988
+ async function page(path, options = {}) {
989
+ const result = await fetcher.page(path, options);
990
+ if (result.cursor?.nextUrl || result.notModified) return result;
991
+ const nextUrl = countedNextUrl(options.cursor?.nextUrl ? fetcher.resolve(options.cursor.nextUrl) : fetcher.resolve(path, options.query), result.data.length, result.response.headers.get("x-total-count"));
992
+ return nextUrl ? {
993
+ ...result,
994
+ cursor: {
995
+ ...result.cursor,
996
+ nextUrl
997
+ }
998
+ } : result;
999
+ }
1000
+ async function* items(path, options = {}) {
1001
+ let cursor;
1002
+ do {
1003
+ const result = await page(path, {
1004
+ ...options,
1005
+ cursor
1006
+ });
1007
+ yield* result.data;
1008
+ cursor = result.notModified ? void 0 : result.cursor;
1009
+ } while (cursor?.nextUrl);
1010
+ }
1011
+ return {
1012
+ ...fetcher,
1013
+ page,
1014
+ items
1015
+ };
1016
+ }
1017
+ function verifyForgejoSignature(delivery, secret, names = FORGEJO_HEADERS) {
1018
+ return verifyHmacSignature(delivery, secret, { header: names.signature });
1019
+ }
1020
+ /** Handlers for one deployment family; Gitea differs from Forgejo only in its header names. */
1021
+ function forgejoWebhooks(profile) {
1022
+ return ({ options, origin }) => ({
1023
+ events: FORGEJO_WEBHOOK_EVENTS,
1024
+ verify: (delivery) => verifyForgejoSignature(delivery, options.webhookSecret, profile.headers),
1025
+ translate: async (delivery) => (await import("./events-DmSWTdpS-BdJBABfI.js")).translateForgejoWebhook(origin, delivery, profile.headers)
1026
+ });
1027
+ }
1028
+ const YAML_FILE = /\.ya?ml$/i;
1029
+ /** The folders each web UI checks for a pull request template, in its order. Gitea skips `.forgejo` and `docs`. */
1030
+ const PULL_TEMPLATE_DIRECTORIES = {
1031
+ forgejo: [
1032
+ "",
1033
+ ".forgejo",
1034
+ ".gitea",
1035
+ ".github",
1036
+ "docs"
1037
+ ],
1038
+ gitea: [
1039
+ "",
1040
+ ".gitea",
1041
+ ".github"
1042
+ ]
1043
+ };
1044
+ const PULL_TEMPLATE_FILES = ["PULL_REQUEST_TEMPLATE", "pull_request_template"].flatMap((name) => [
1045
+ `${name}.md`,
1046
+ `${name}.yaml`,
1047
+ `${name}.yml`
1048
+ ]);
1049
+ const FORGEJO_PROFILE = {
1050
+ forge: "forgejo",
1051
+ web: FORGEJO_WEB,
1052
+ headers: FORGEJO_HEADERS
1053
+ };
1054
+ const ISSUE_AND_PULL = {
1055
+ issue: true,
1056
+ pull_request: true
1057
+ };
1058
+ /** Forgejo versions with the Actions runs API, and with run jobs and job logs. */
1059
+ const FORGEJO_ACTION_RUNS = "12.0";
1060
+ const FORGEJO_ACTION_JOBS = "16.0";
1061
+ /** Gitea versions with runs and their jobs, and with job logs. */
1062
+ const GITEA_ACTION_RUNS = "1.25";
1063
+ const GITEA_ACTION_LOGS = "1.24";
1064
+ /** Gitea version with re-running the failed jobs of a run. */
1065
+ const GITEA_RERUN_FAILED = "1.26";
1066
+ /** Gitea version with replies to review comments. */
1067
+ const GITEA_REVIEW_REPLIES = "1.27";
1068
+ /** The Forgejo and Gitea version with activity feeds. */
1069
+ const ACTIVITY_FEEDS = "1.20";
1070
+ /** Forgejo and Gitea versions with blocking an account. */
1071
+ const FORGEJO_BLOCKS = "1.20";
1072
+ const GITEA_BLOCKS = "1.22";
1073
+ /** Gitea version with locking an issue or pull request. */
1074
+ const GITEA_LOCKS = "1.24";
1075
+ const GITEA_LOCK_REASONS = {
1076
+ off_topic: "Off-topic",
1077
+ too_heated: "Too heated",
1078
+ resolved: "Resolved",
1079
+ spam: "Spam"
1080
+ };
1081
+ /** Timelines send no usable count, so only a full page of an explicit size shows that another follows. */
1082
+ const TIMELINE_PAGE_SIZE = 50;
1083
+ /** Whether `user` has `login`, in any case; `true` when no login is wanted. Forgejo's issue search ignores `created_by` and `assigned_by`. */
1084
+ function sameLogin(user, login) {
1085
+ return !login || user?.login.toLowerCase() === login.toLowerCase();
1086
+ }
1087
+ /** The Forgejo implementation for one deployment family. Shared by `forgejo()` and `gitea()`. */
1088
+ function forgejoDefinition(profile) {
1089
+ return {
1090
+ forge: profile.forge,
1091
+ hasWeb: true,
1092
+ baseUrl: profile.web.baseUrl,
1093
+ anonymous: true,
1094
+ apiPath: profile.web.apiPath,
1095
+ headers: { accept: "application/json" },
1096
+ authHeaders: ({ options: { auth } }) => auth?.type === "token" ? async () => ({ authorization: `token ${await resolveToken(auth)}` }) : void 0,
1097
+ webhooks: forgejoWebhooks(profile),
1098
+ setup: (ctx) => setupForgejo(ctx, profile)
1099
+ };
1100
+ }
1101
+ function setupForgejo({ options, origin, fetcher: baseFetcher, baseUrl }, profile) {
1102
+ const context = origin;
1103
+ /** Collaborators, assignees, reviewers and permissions are served only to signed-in users. */
1104
+ const anonymous = options.auth?.type === "anonymous";
1105
+ const fetcher = countedPages(baseFetcher);
1106
+ const list = createListing(fetcher, "limit");
1107
+ /** Organisations are accounts too, so `/users/{owner}/repos` serves both. */
1108
+ function ownerReposPage(owner, query = {}) {
1109
+ return list(`/users/${encodeURIComponent(owner.owner)}/repos`, query, (raw) => toRepo(origin, raw), { warnings: isFirstPage(query.cursor) && ((query.sort ?? "created") !== "created" || query.direction === "desc") ? [{
1110
+ code: "sort_unsupported",
1111
+ message: `${profile.forge} lists the repositories of an owner oldest first only`
1112
+ }] : void 0 });
1113
+ }
1114
+ async function readUser(path, signal) {
1115
+ const { data } = await fetcher.json(path, { signal });
1116
+ return {
1117
+ ...toActor(origin, data),
1118
+ bio: data.description || void 0,
1119
+ location: data.location || void 0,
1120
+ websiteUrl: data.website || void 0,
1121
+ createdAt: toDate(data.created),
1122
+ followers: data.followers_count,
1123
+ following: data.following_count,
1124
+ raw: data
1125
+ };
1126
+ }
1127
+ function repoPath(repo) {
1128
+ return `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
1129
+ }
1130
+ function threadPath(ref) {
1131
+ switch (ref.kind) {
1132
+ case "pull_request": return `${repoPath(ref.repo)}/pulls/${encodeURIComponent(ref.number)}`;
1133
+ case "discussion": throw new UnsupportedOperationError(`${profile.forge} has no discussions`, context);
1134
+ default: return `${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}`;
1135
+ }
1136
+ }
1137
+ const currentUser = memo(() => fetcher.json("/user").then((result) => result.data));
1138
+ /**
1139
+ * An update or a deletion names the blob it replaces, so each directory the change touches is listed first,
1140
+ * at the commit the change builds on. A branch from `createFrom` is created before the commit.
1141
+ */
1142
+ async function commitFiles(repo, input, options) {
1143
+ const signal = options?.signal;
1144
+ const branchPath = `${repoPath(repo)}/branches/${input.branch.split("/").map(encodeURIComponent).join("/")}`;
1145
+ let head = input.expectedHead;
1146
+ if (input.createFrom !== void 0) {
1147
+ const { data } = await fetcher.json(`${repoPath(repo)}/branches`, {
1148
+ method: "POST",
1149
+ json: {
1150
+ new_branch_name: input.branch,
1151
+ old_ref_name: input.createFrom
1152
+ },
1153
+ signal
1154
+ });
1155
+ head = data.commit?.id;
1156
+ } else if (head !== void 0) {
1157
+ const { data } = await fetcher.json(branchPath, { signal });
1158
+ if (data.commit?.id !== head.toLowerCase()) throw new BranchMovedError(`${input.branch} is at ${data.commit?.id}, not ${head}`, 409, "", context);
1159
+ }
1160
+ try {
1161
+ const ref = head ?? input.branch;
1162
+ const existing = await existingFiles(input.changes, inDirectories(async (directory) => {
1163
+ try {
1164
+ const entries = await listDirectory(repo, directory, {
1165
+ ref,
1166
+ signal
1167
+ });
1168
+ return entries && new Map(entries.filter((entry) => entry.type === "file" || entry.type === "symlink").map((entry) => [entry.path, entry.sha]));
1169
+ } catch (error) {
1170
+ if (error instanceof NotFoundError) return;
1171
+ throw error;
1172
+ }
1173
+ }), context);
1174
+ const { data } = await fetcher.json(`${repoPath(repo)}/contents`, {
1175
+ method: "POST",
1176
+ json: {
1177
+ branch: input.branch,
1178
+ message: input.message,
1179
+ ...input.author && { author: input.author },
1180
+ files: input.changes.map(({ path, content }) => content === null ? {
1181
+ operation: "delete",
1182
+ path,
1183
+ sha: existing.get(path)
1184
+ } : {
1185
+ operation: existing.has(path) ? "update" : "create",
1186
+ path,
1187
+ content: changeBase64(content),
1188
+ ...existing.has(path) && { sha: existing.get(path) }
1189
+ })
1190
+ },
1191
+ signal
1192
+ });
1193
+ return toFileCommit(repo, data.commit);
1194
+ } catch (error) {
1195
+ if (input.createFrom !== void 0) {
1196
+ if ((await fetcher.json(branchPath).catch(() => void 0))?.data.commit?.id === head) await fetcher.raw(branchPath, { method: "DELETE" }).catch(() => {});
1197
+ }
1198
+ throw error;
1199
+ }
1200
+ }
1201
+ /** Labels are addressed by id in writes, so names are resolved once per repo. */
1202
+ /** Forgejo and Gitea address reactions on issues and on comments with the same body. */
1203
+ function reactionPath(target) {
1204
+ return "thread" in target ? `${repoPath(target.thread.repo)}/issues/comments/${encodeURIComponent(target.id)}/reactions` : `${issuePath(requireIssueOrPull(target, context, "react to"))}/reactions`;
1205
+ }
1206
+ async function setReaction(target, reaction, method, options) {
1207
+ await fetcher.raw(reactionPath(target), {
1208
+ method,
1209
+ json: { content: reaction },
1210
+ signal: options?.signal
1211
+ });
1212
+ }
1213
+ const labelIdsOf = memoBy(async (path) => {
1214
+ const map = /* @__PURE__ */ new Map();
1215
+ for await (const label of fetcher.items(path, { query: { limit: 50 } })) map.set(label.name, label.id);
1216
+ return map;
1217
+ });
1218
+ /** Labels an organisation shares with its repositories; none for a user, whose `/orgs` route is a 404. */
1219
+ const orgLabelIdsOf = memoBy(async (owner) => {
1220
+ try {
1221
+ return await labelIdsOf(`/orgs/${encodeURIComponent(owner)}/labels`);
1222
+ } catch (error) {
1223
+ if (error instanceof NotFoundError) return /* @__PURE__ */ new Map();
1224
+ throw error;
1225
+ }
1226
+ });
1227
+ async function resolveLabels(repo, names) {
1228
+ const map = await labelIdsOf(`${repoPath(repo)}/labels`);
1229
+ const shared = names.some((name) => !map.has(name)) ? await orgLabelIdsOf(repo.owner) : void 0;
1230
+ return names.map((name) => {
1231
+ const id = map.get(name) ?? shared?.get(name);
1232
+ if (id === void 0) throw new UnsupportedOperationError(`No label named ${name} in ${repo.owner}/${repo.name}`, context);
1233
+ return id;
1234
+ });
1235
+ }
1236
+ async function notificationPage(listOptions = {}) {
1237
+ const result = await fetcher.json(listOptions.cursor?.nextUrl ?? "/notifications", {
1238
+ query: listOptions.cursor?.nextUrl ? void 0 : {
1239
+ all: listOptions.all ?? false,
1240
+ since: listOptions.since?.toISOString(),
1241
+ limit: listOptions.perPage
1242
+ },
1243
+ signal: listOptions.signal
1244
+ });
1245
+ return {
1246
+ items: (result.data ?? []).map((raw) => toNotification(origin, raw)),
1247
+ cursor: result.cursor,
1248
+ notModified: result.notModified,
1249
+ ...rateLimitPart(result.response)
1250
+ };
1251
+ }
1252
+ async function setStatus(ref, status, options) {
1253
+ await fetcher.raw(`/notifications/threads/${encodeURIComponent(ref.id)}`, {
1254
+ method: "PATCH",
1255
+ query: { "to-status": status },
1256
+ signal: options?.signal
1257
+ });
1258
+ }
1259
+ async function issueTarget(ref, { thread, signal }) {
1260
+ if (thread) {
1261
+ const resolved = requireThread(thread, context);
1262
+ if (resolved.kind !== "issue" && resolved.kind !== "pull_request") throw new UnsupportedOperationError("Only issue and pull request threads can be unsubscribed from", context);
1263
+ return {
1264
+ owner: resolved.repo.owner,
1265
+ name: resolved.repo.name,
1266
+ number: resolved.number
1267
+ };
1268
+ }
1269
+ const { data } = await fetcher.json(`/notifications/threads/${encodeURIComponent(ref.id)}`, { signal });
1270
+ const number = numberFromUrl(data.subject.url);
1271
+ if (!number || !toThreadKind(data.subject.type)) throw new UnsupportedOperationError("Only issue and pull request threads can be unsubscribed from", context);
1272
+ const [owner = "", name = ""] = data.repository.full_name.split("/");
1273
+ return {
1274
+ owner,
1275
+ name,
1276
+ number
1277
+ };
1278
+ }
1279
+ async function subscriptionPath(target) {
1280
+ const user = await currentUser();
1281
+ return `${repoPath(target)}/issues/${encodeURIComponent(target.number)}/subscriptions/${encodeURIComponent(user.login)}`;
1282
+ }
1283
+ async function unsubscribe(ref, writeOptions = {}) {
1284
+ await fetcher.raw(await subscriptionPath(await issueTarget(ref, writeOptions)), {
1285
+ method: "DELETE",
1286
+ signal: writeOptions.signal
1287
+ });
1288
+ }
1289
+ function issuePath(ref) {
1290
+ return `${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}`;
1291
+ }
1292
+ /** A pull request is edited through the pulls endpoint, whose response carries its branches and reviewers. */
1293
+ async function setState(thread, state, options) {
1294
+ const ref = requireIssueOrPull(thread, context, state === "open" ? "reopen" : "close");
1295
+ const { data } = await fetcher.json(ref.kind === "pull_request" ? threadPath(ref) : issuePath(ref), {
1296
+ method: "PATCH",
1297
+ json: { state },
1298
+ signal: options?.signal
1299
+ });
1300
+ return toThread(ref, data);
1301
+ }
1302
+ /** The merge response has no body, and a merge scheduled until checks pass responds with `201`. */
1303
+ async function merge(thread, mergeOptions = {}) {
1304
+ const ref = requireThread(thread, context);
1305
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only pull requests can be merged", context);
1306
+ const pull = `${repoPath(ref.repo)}/pulls/${encodeURIComponent(ref.number)}`;
1307
+ let method = mergeOptions.method;
1308
+ if (!method) {
1309
+ const { data: repo } = await fetcher.json(repoPath(ref.repo), { signal: mergeOptions.signal });
1310
+ method = soleMergeMethod({
1311
+ merge: repo.allow_merge_commits,
1312
+ rebase: repo.allow_rebase,
1313
+ rebase_merge: repo.allow_rebase_explicit,
1314
+ squash: repo.allow_squash_merge,
1315
+ fast_forward_only: repo.allow_fast_forward_only_merge
1316
+ }, context);
1317
+ }
1318
+ const response = await fetcher.raw(`${pull}/merge`, {
1319
+ method: "POST",
1320
+ json: {
1321
+ Do: method.replaceAll("_", "-"),
1322
+ MergeTitleField: mergeOptions.title,
1323
+ MergeMessageField: mergeOptions.message,
1324
+ head_commit_id: mergeOptions.sha,
1325
+ merge_when_checks_succeed: mergeOptions.whenChecksPass
1326
+ },
1327
+ mapError: toMergeError,
1328
+ signal: mergeOptions.signal
1329
+ });
1330
+ return { status: mergeOptions.whenChecksPass && response.status === 201 ? "queued" : "merged" };
1331
+ }
1332
+ /** The update takes no expected head, so `sha` is compared against a read of the pull request first. */
1333
+ async function updateBranch(thread, updateOptions = {}) {
1334
+ const ref = requirePull(thread, "updated");
1335
+ const { sha, signal } = updateOptions;
1336
+ if (sha !== void 0) {
1337
+ const { data } = await fetcher.json(pullPath(ref), { signal });
1338
+ if (data.head?.sha !== sha) throw new BranchMovedError(`Head branch of pull request ${ref.number} is at ${data.head?.sha}, not ${sha}`, 409, "", context);
1339
+ }
1340
+ await fetcher.raw(`${pullPath(ref)}/update`, {
1341
+ method: "POST",
1342
+ query: { style: updateOptions.method ?? "merge" },
1343
+ mapError: toMergeError,
1344
+ signal
1345
+ });
1346
+ return { status: "updated" };
1347
+ }
1348
+ const REVIEW_EVENTS = {
1349
+ approve: "APPROVED",
1350
+ request_changes: "REQUEST_CHANGES",
1351
+ comment: "COMMENT"
1352
+ };
1353
+ function requirePull(thread, action) {
1354
+ const ref = requireThread(thread, context);
1355
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError(`Only pull requests can be ${action}`, context);
1356
+ return ref;
1357
+ }
1358
+ function pullPath(ref) {
1359
+ return `${repoPath(ref.repo)}/pulls/${encodeURIComponent(ref.number)}`;
1360
+ }
1361
+ function reviewCommentInput(comments) {
1362
+ return comments?.map((comment) => ({
1363
+ path: comment.path,
1364
+ body: comment.body,
1365
+ ...comment.side === "left" ? { old_position: comment.line } : { new_position: comment.line }
1366
+ }));
1367
+ }
1368
+ async function createReview(thread, input, options) {
1369
+ const ref = requirePull(thread, "reviewed");
1370
+ const { data } = await fetcher.json(`${pullPath(ref)}/reviews`, {
1371
+ method: "POST",
1372
+ json: {
1373
+ event: input.event ? REVIEW_EVENTS[input.event] : void 0,
1374
+ body: input.body ?? "",
1375
+ comments: reviewCommentInput(input.comments)
1376
+ },
1377
+ signal: options?.signal
1378
+ });
1379
+ return toReview(ref, data, []);
1380
+ }
1381
+ async function get(thread, options) {
1382
+ const ref = requireThread(thread, context);
1383
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
1384
+ const result = toThread(ref, data);
1385
+ if (ref.kind === "pull_request" && data.head?.sha) try {
1386
+ const checks = await statusChecks(ref.repo, data.head.sha, options?.signal);
1387
+ result.checks = summariseChecks(checks.map((check) => check.state));
1388
+ } catch (error) {
1389
+ if (!(error instanceof ForgeError)) throw error;
1390
+ result.warnings = [...result.warnings ?? [], toWarning("checks_unreadable", error, ref.number)];
1391
+ }
1392
+ return result;
1393
+ }
1394
+ const STATUS_STATES = {
1395
+ pending: "pending",
1396
+ success: "success",
1397
+ failure: "failure",
1398
+ neutral: "success",
1399
+ unknown: "pending"
1400
+ };
1401
+ async function statusChecks(repo, sha, signal) {
1402
+ const { data } = await fetcher.json(`${repoPath(repo)}/commits/${sha}/status`, { signal });
1403
+ return toStatusChecks(repo, data);
1404
+ }
1405
+ function milestonesPage(repo, listOptions = {}) {
1406
+ return list(`${repoPath(repo)}/milestones`, listOptions, (raw) => toMilestone(raw), { query: { state: listOptions.state ?? "open" } });
1407
+ }
1408
+ async function releasesPage(repo, listOptions = {}) {
1409
+ return list(`${repoPath(repo)}/releases`, listOptions, (raw) => toRelease(repo, raw));
1410
+ }
1411
+ async function writeRelease(repo, path, method, input, options) {
1412
+ const { data } = await fetcher.json(path, {
1413
+ method,
1414
+ json: {
1415
+ tag_name: input.tag,
1416
+ target_commitish: input.target,
1417
+ name: input.name,
1418
+ body: input.body,
1419
+ draft: input.draft,
1420
+ prerelease: input.prerelease
1421
+ },
1422
+ signal: options?.signal
1423
+ });
1424
+ return toRelease(repo, method === "POST" ? {
1425
+ ...data,
1426
+ assets: []
1427
+ } : data);
1428
+ }
1429
+ async function listPage(repo, query = {}) {
1430
+ const warnings = [];
1431
+ if (query.kind === "discussion") return {
1432
+ items: [],
1433
+ warnings: [{
1434
+ code: "kind_unsupported",
1435
+ message: `${profile.forge} has no discussions`
1436
+ }]
1437
+ };
1438
+ const sort = query.sort ?? "created";
1439
+ const direction = query.direction ?? "desc";
1440
+ if (isFirstPage(query.cursor) && (sort !== "created" || direction !== "desc")) warnings.push({
1441
+ code: "sort_unsupported",
1442
+ message: `${profile.forge} lists repository issues newest first only`
1443
+ });
1444
+ const createdAfter = query.createdAfter?.getTime();
1445
+ const result = await fetcher.page(`${repoPath(repo)}/issues`, {
1446
+ query: {
1447
+ state: query.state === "merged" ? "closed" : query.state ?? "open",
1448
+ type: query.kind === "pull_request" ? "pulls" : query.kind === "issue" ? "issues" : void 0,
1449
+ labels: query.labels?.join(","),
1450
+ created_by: query.author,
1451
+ assigned_by: query.assignee,
1452
+ since: query.since?.toISOString(),
1453
+ limit: query.perPage
1454
+ },
1455
+ cursor: query.cursor,
1456
+ signal: query.signal
1457
+ });
1458
+ const older = (raw) => createdAfter !== void 0 && (Date.parse(raw.created_at ?? "") || 0) < createdAfter;
1459
+ const unmerged = (raw) => query.state === "merged" && !raw.pull_request?.merged;
1460
+ const page = toPage(result, (raw) => older(raw) || unmerged(raw) || !hasEveryLabel(raw.labels, query.labels) ? void 0 : toThread({
1461
+ ...origin,
1462
+ repo,
1463
+ kind: raw.pull_request ? "pull_request" : "issue",
1464
+ number: String(raw.number)
1465
+ }, raw), warnings);
1466
+ return (result.data ?? []).some(older) ? {
1467
+ ...page,
1468
+ cursor: void 0
1469
+ } : page;
1470
+ }
1471
+ /** Repository hooks, or organisation hooks for a namespace ref. */
1472
+ function hooksPath(target) {
1473
+ return isNamespaceRef(target) ? `/orgs/${encodeURIComponent(target.owner)}/hooks` : `${repoPath(target)}/hooks`;
1474
+ }
1475
+ async function searchThreadsPage(query) {
1476
+ const warnings = [];
1477
+ if (isFirstPage(query.cursor) && query.involves) warnings.push({
1478
+ code: "filter_unsupported",
1479
+ message: `${profile.forge} has no involves filter; it was ignored`
1480
+ });
1481
+ if (isFirstPage(query.cursor) && query.sort && query.sort !== "relevance") warnings.push({
1482
+ code: "sort_unsupported",
1483
+ message: `${profile.forge} searches issues newest first only`
1484
+ });
1485
+ const result = await fetcher.page("/repos/issues/search", {
1486
+ query: {
1487
+ q: query.text,
1488
+ type: query.kind === "pull_request" ? "pulls" : query.kind === "issue" ? "issues" : void 0,
1489
+ state: query.state ?? "all",
1490
+ labels: query.labels?.join(","),
1491
+ created_by: query.author,
1492
+ assigned_by: query.assignee,
1493
+ since: query.since?.toISOString(),
1494
+ owner: query.repo?.owner ?? query.owner,
1495
+ limit: query.perPage
1496
+ },
1497
+ cursor: query.cursor,
1498
+ signal: query.signal
1499
+ });
1500
+ return toPage(result, (raw) => {
1501
+ const [owner = "", name = ""] = raw.repository?.full_name.split("/") ?? [];
1502
+ const repo = query.repo ?? (name ? {
1503
+ ...origin,
1504
+ owner,
1505
+ name,
1506
+ externalId: raw.repository?.id === void 0 ? void 0 : String(raw.repository.id)
1507
+ } : void 0);
1508
+ if (!repo || !hasEveryLabel(raw.labels, query.labels) || !sameLogin(raw.user, query.author) || query.assignee && !raw.assignees?.some((user) => sameLogin(user, query.assignee)) || query.repo && raw.repository && raw.repository.full_name !== `${query.repo.owner}/${query.repo.name}`) return;
1509
+ return toThread({
1510
+ ...origin,
1511
+ repo,
1512
+ kind: raw.pull_request ? "pull_request" : "issue",
1513
+ number: String(raw.number)
1514
+ }, raw);
1515
+ }, warnings);
1516
+ }
1517
+ const isGitea = profile.forge === "gitea";
1518
+ /** Codeberg and gitea.com run a current release, so only a self-hosted instance waits for its version. */
1519
+ function released(minimum) {
1520
+ return hostOf(baseUrl) === hostOf(profile.web.baseUrl) ? true : ({ version }) => versionAtLeast(version, minimum);
1521
+ }
1522
+ function actions(forgejoMinimum, giteaMinimum) {
1523
+ return released(isGitea ? giteaMinimum : forgejoMinimum);
1524
+ }
1525
+ async function feedPage(path, listOptions, query) {
1526
+ const { toFeedEvent } = await import("./feed-BwdcTgZq-Bm_c8br8.js");
1527
+ return list(path, listOptions, (raw) => toFeedEvent(origin, raw), { query });
1528
+ }
1529
+ async function setBlocked(scope, login, blocked, options) {
1530
+ const path = isGitea ? `${scope}/blocks/${encodeURIComponent(login)}` : `${scope}/${blocked ? "block" : "unblock"}/${encodeURIComponent(login)}`;
1531
+ await fetcher.raw(path, {
1532
+ method: isGitea && !blocked ? "DELETE" : "PUT",
1533
+ signal: options?.signal
1534
+ });
1535
+ }
1536
+ async function setLocked(thread, locked, options = {}) {
1537
+ const ref = requireThread(thread, context);
1538
+ await fetcher.raw(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/lock`, {
1539
+ method: locked ? "PUT" : "DELETE",
1540
+ ...locked ? { json: options.reason ? { lock_reason: GITEA_LOCK_REASONS[options.reason] } : {} } : {},
1541
+ signal: options.signal
1542
+ });
1543
+ }
1544
+ /** Gitea lists runs and serves job logs only with a token. */
1545
+ const giteaAnonymous = isGitea && anonymous;
1546
+ /** Team ids of an organisation by lowercased name, which Forgejo and Gitea keep unique. */
1547
+ const teamIdsOf = memoBy(async (org) => {
1548
+ const map = /* @__PURE__ */ new Map();
1549
+ for await (const team of fetcher.items(`/orgs/${encodeURIComponent(org)}/teams`)) map.set(team.name.toLowerCase(), team.id);
1550
+ return map;
1551
+ });
1552
+ /** One page of an Actions listing, read from `key` and continued from `total_count` when no `Link` header is sent. */
1553
+ async function actionsPage(path, key, query, pageOptions) {
1554
+ const url = pageOptions.cursor?.nextUrl ? fetcher.resolve(pageOptions.cursor.nextUrl) : fetcher.resolve(path, query);
1555
+ return fetcher.page(path, {
1556
+ query,
1557
+ cursor: pageOptions.cursor,
1558
+ signal: pageOptions.signal,
1559
+ select: (body, next) => {
1560
+ const listing = body;
1561
+ const items = listing[key] ?? [];
1562
+ return {
1563
+ items,
1564
+ next: next ?? countedNextUrl(url, items.length, listing.total_count === void 0 ? null : String(listing.total_count)),
1565
+ ...listing.total_count !== void 0 ? { total: listing.total_count } : {}
1566
+ };
1567
+ }
1568
+ });
1569
+ }
1570
+ async function runsPage(repo, query = {}) {
1571
+ const states = isGitea ? GITEA_ACTION_STATES : ACTION_STATES;
1572
+ const statuses = query.state ? `?${states[query.state].map((status) => `status=${status}`).join("&")}` : "";
1573
+ const path = `${repoPath(repo)}/actions/runs${statuses}`;
1574
+ if (isGitea) return toPage(await actionsPage(path, "workflow_runs", {
1575
+ branch: query.branch,
1576
+ page: 1,
1577
+ limit: query.perPage ?? 50
1578
+ }, query), (raw) => toGiteaActionRun(repo, raw));
1579
+ const result = await actionsPage(path, "workflow_runs", {
1580
+ ref: query.branch ? `refs/heads/${query.branch}` : void 0,
1581
+ page: 1,
1582
+ limit: query.perPage ?? 50
1583
+ }, query);
1584
+ return toPage(result, (raw) => query.branch && actionBranch(raw) !== query.branch ? void 0 : toActionRun(repo, raw));
1585
+ }
1586
+ async function jobsPage(ref, listOptions = {}) {
1587
+ const path = `${repoPath(ref.repo)}/actions/runs/${encodeURIComponent(ref.id)}/jobs`;
1588
+ if (isGitea) return toPage(await actionsPage(path, "jobs", {
1589
+ page: 1,
1590
+ limit: listOptions.perPage ?? 50
1591
+ }, listOptions), (raw) => toGiteaActionJob(ref, raw));
1592
+ const { data, response } = await fetcher.json(path, { signal: listOptions.signal });
1593
+ return {
1594
+ items: (data ?? []).map((raw) => toActionJob(ref, raw)),
1595
+ ...rateLimitPart(response)
1596
+ };
1597
+ }
1598
+ async function searchReposPage(query) {
1599
+ const result = await fetcher.page("/repos/search", {
1600
+ query: {
1601
+ q: query.text,
1602
+ owner: query.owner,
1603
+ sort: query.sort === "stars" ? "stars" : query.sort === "created" ? "created" : query.sort === "updated" ? "updated" : void 0,
1604
+ order: query.direction,
1605
+ limit: query.perPage
1606
+ },
1607
+ cursor: query.cursor,
1608
+ signal: query.signal,
1609
+ select: (body, next) => ({
1610
+ items: body.data,
1611
+ next
1612
+ })
1613
+ });
1614
+ return toPage(result, (raw) => toRepo(origin, raw));
1615
+ }
1616
+ async function templates(repo, options = {}) {
1617
+ const [issues, pulls] = await Promise.all([options.kind === "pull_request" ? [] : issueTemplates(repo, options.signal), options.kind === "issue" ? [] : pullTemplate(repo, options.signal)]);
1618
+ return [...issues, ...pulls];
1619
+ }
1620
+ /** The API parses each template but drops its front matter and a form's YAML, so the file gets read too. */
1621
+ async function issueTemplates(repo, signal) {
1622
+ const { data } = await fetcher.json(`${repoPath(repo)}/issue_templates`, { signal });
1623
+ return mapConcurrent(data ?? [], 4, async (raw) => ({
1624
+ kind: "issue",
1625
+ name: raw.name,
1626
+ path: raw.file_name,
1627
+ format: YAML_FILE.test(raw.file_name) ? "form" : "markdown",
1628
+ body: await readText(repo, raw.file_name, signal),
1629
+ title: raw.title || void 0,
1630
+ about: raw.about || void 0,
1631
+ labels: raw.labels?.length ? raw.labels : void 0,
1632
+ fields: raw.body?.map((field) => ({
1633
+ type: field.type,
1634
+ id: field.id || void 0,
1635
+ attributes: field.attributes ?? {},
1636
+ validations: field.validations ?? void 0
1637
+ })),
1638
+ raw
1639
+ }));
1640
+ }
1641
+ /** No API for pull request templates, so this finds the one file the web UI would pick. */
1642
+ async function pullTemplate(repo, signal) {
1643
+ const directories = PULL_TEMPLATE_DIRECTORIES[isGitea ? "gitea" : "forgejo"];
1644
+ const root = await listDirectory(repo, "", { signal }) ?? [];
1645
+ const pick = (entries) => PULL_TEMPLATE_FILES.map((name) => entries.find((entry) => entry.type === "file" && entry.name === name)).find(Boolean);
1646
+ const inRoot = pick(root);
1647
+ const nested = inRoot ? [] : await Promise.all(directories.filter((directory) => directory && root.some((entry) => entry.type === "dir" && entry.name === directory)).map(async (directory) => await listDirectory(repo, directory, { signal }) ?? []));
1648
+ const entry = inRoot ?? nested.map(pick).find(Boolean);
1649
+ if (!entry) return [];
1650
+ return [{
1651
+ kind: "pull_request",
1652
+ name: entry.name,
1653
+ path: entry.path,
1654
+ format: YAML_FILE.test(entry.name) ? "form" : "markdown",
1655
+ body: await readText(repo, entry.path, signal),
1656
+ raw: entry
1657
+ }];
1658
+ }
1659
+ async function readText(repo, path, signal) {
1660
+ return (await readFile(repo, path, {
1661
+ as: "text",
1662
+ signal
1663
+ })).content;
1664
+ }
1665
+ /** The entries of a directory, `''` for the root, or `undefined` when the path names a file. */
1666
+ async function listDirectory(repo, directory, options = {}) {
1667
+ const { data } = await fetcher.json(`${repoPath(repo)}/contents${directory ? `/${directory.split("/").map(encodeURIComponent).join("/")}` : ""}`, {
1668
+ query: { ref: options.ref },
1669
+ signal: options.signal
1670
+ });
1671
+ return Array.isArray(data) ? data : void 0;
1672
+ }
1673
+ /** Large files come back with a null `content`, so they come from the raw endpoint, which has no size limit. */
1674
+ async function readFile(repo, path, fileOptions = {}) {
1675
+ const encoded = path.split("/").map(encodeURIComponent).join("/");
1676
+ if (fileOptions.metadata === false) {
1677
+ const response = await fetcher.raw(`${repoPath(repo)}/raw/${encoded}`, {
1678
+ query: { ref: fileOptions.ref },
1679
+ signal: fileOptions.signal
1680
+ });
1681
+ const bytes = new Uint8Array(await response.arrayBuffer());
1682
+ return toFileContent(bytes, {
1683
+ path,
1684
+ size: bytes.byteLength
1685
+ }, fileOptions, context);
1686
+ }
1687
+ const { data } = await fetcher.json(`${repoPath(repo)}/contents/${encoded}`, {
1688
+ query: { ref: fileOptions.ref },
1689
+ signal: fileOptions.signal
1690
+ });
1691
+ const file = {
1692
+ path: data.path,
1693
+ sha: data.sha,
1694
+ size: data.size,
1695
+ url: data.html_url ?? void 0
1696
+ };
1697
+ if (data.encoding === "base64" && data.content) return toFileContent(fromBase64(data.content), file, fileOptions, context);
1698
+ const response = await fetcher.raw(`${repoPath(repo)}/raw/${encoded}`, {
1699
+ query: { ref: fileOptions.ref },
1700
+ signal: fileOptions.signal
1701
+ });
1702
+ return toFileContent(new Uint8Array(await response.arrayBuffer()), file, fileOptions, context);
1703
+ }
1704
+ return {
1705
+ traits: {
1706
+ eventKinds: "native",
1707
+ authKinds: ["token", "anonymous"]
1708
+ },
1709
+ notApplicable: [
1710
+ ...isGitea ? [] : ["threads.lock"],
1711
+ "threads.hideComment",
1712
+ "threads.resolveReviewThread",
1713
+ "repos.issueTypes",
1714
+ "threads.setIssueType",
1715
+ "checks.rerun",
1716
+ "webhooks.deliveries",
1717
+ "webhooks.redeliver"
1718
+ ],
1719
+ search: {
1720
+ threadsPage: verb(true, searchThreadsPage),
1721
+ reposPage: verb(true, searchReposPage)
1722
+ },
1723
+ probeVersion: async () => (await fetcher.json("/version")).data.version,
1724
+ users: {
1725
+ get: verb(true, (login, options) => readUser(`/users/${encodeURIComponent(login)}`, options?.signal)),
1726
+ me: verb(true, (options) => readUser("/user", options?.signal)),
1727
+ eventsPage: verb(released(ACTIVITY_FEEDS), (login, listOptions = {}) => feedPage(`/users/${encodeURIComponent(login)}/activities/feeds`, listOptions, { "only-performed-by": true })),
1728
+ blocking: verb(released(isGitea ? GITEA_BLOCKS : FORGEJO_BLOCKS), {
1729
+ block: (login, options) => setBlocked("/user", login, true, options),
1730
+ unblock: (login, options) => setBlocked("/user", login, false, options)
1731
+ })
1732
+ },
1733
+ repos: {
1734
+ get: verb(true, async (ref, options) => toRepo(origin, (await fetcher.json(repoPath(ref), { signal: options?.signal })).data)),
1735
+ listPage: verb(true, (listOptions = {}) => list("/user/repos", listOptions, (raw) => toRepo(origin, raw))),
1736
+ byOwnerPage: verb(true, ownerReposPage),
1737
+ labelsPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/labels`, listOptions, toLabel)),
1738
+ createLabel: verb(true, async (repo, label, options) => toLabel((await fetcher.json(`${repoPath(repo)}/labels`, {
1739
+ method: "POST",
1740
+ json: {
1741
+ name: label.name,
1742
+ color: hexColour(label.colour, "#"),
1743
+ description: label.description
1744
+ },
1745
+ signal: options?.signal
1746
+ })).data)),
1747
+ milestonesPage: verb(true, milestonesPage),
1748
+ collaboratorsPage: verb(!anonymous, (repo, listOptions = {}) => list(`${repoPath(repo)}/collaborators`, listOptions, (raw) => ({
1749
+ actor: toActor(origin, raw),
1750
+ role: "read",
1751
+ raw
1752
+ }))),
1753
+ permissionFor: verb(!anonymous, async (repo, actor, options) => {
1754
+ const { data } = await fetcher.json(`${repoPath(repo)}/collaborators/${encodeURIComponent(actorLogin(actor))}/permission`, { signal: options?.signal });
1755
+ return toRole(data.role_name ?? data.permission);
1756
+ }),
1757
+ branchRules: verb(true, async (repo, name, options) => toBranchRules((await fetcher.json(`${repoPath(repo)}/branches/${name.split("/").map(encodeURIComponent).join("/")}`, { signal: options?.signal })).data)),
1758
+ addCollaborator: verb(true, async (repo, actor, role, options) => {
1759
+ await fetcher.raw(`${repoPath(repo)}/collaborators/${encodeURIComponent(actorLogin(actor))}`, {
1760
+ method: "PUT",
1761
+ json: { permission: role === "admin" ? "admin" : role === "read" || role === "triage" ? "read" : "write" },
1762
+ signal: options?.signal
1763
+ });
1764
+ return { status: "added" };
1765
+ }),
1766
+ assignableUsersPage: verb(!anonymous, (repo, listOptions = {}) => list(`${repoPath(repo)}/assignees`, listOptions, (raw) => toActor(origin, raw))),
1767
+ reviewerCandidatesPage: verb(!anonymous, (thread, listOptions = {}) => list(`${repoPath(requireThread(thread, context).repo)}/reviewers`, listOptions, (raw) => toActor(origin, raw))),
1768
+ templates: verb(true, templates),
1769
+ eventsPage: verb(released(ACTIVITY_FEEDS), (repo, listOptions = {}) => feedPage(`${repoPath(repo)}/activities/feeds`, listOptions))
1770
+ },
1771
+ orgs: {
1772
+ teamsPage: verb(!anonymous, (org, listOptions = {}) => list(`/orgs/${encodeURIComponent(org.owner)}/teams`, listOptions, (raw) => toTeam(origin, teamOrg(org), raw))),
1773
+ teamMembersPage: verb(!anonymous, async (team, listOptions = {}) => {
1774
+ const id = team.id ?? (await teamIdsOf(team.org.owner)).get(team.slug.toLowerCase());
1775
+ if (id === void 0) throw new NotFoundError(`${team.org.owner} has no team named ${team.slug}`, 404, "", context);
1776
+ return list(`/teams/${encodeURIComponent(id)}/members`, listOptions, (raw) => toActor(origin, raw));
1777
+ }),
1778
+ blocking: verb(released(isGitea ? GITEA_BLOCKS : FORGEJO_BLOCKS), {
1779
+ block: (org, login, options) => setBlocked(`/orgs/${encodeURIComponent(org.owner)}`, login, true, options),
1780
+ unblock: (org, login, options) => setBlocked(`/orgs/${encodeURIComponent(org.owner)}`, login, false, options)
1781
+ })
1782
+ },
1783
+ notifications: {
1784
+ listPage: verb(true, notificationPage),
1785
+ markRead: verb(true, (ref, options) => setStatus(ref, "read", options)),
1786
+ markDone: verb("emulated", (ref, writeOptions) => setStatus(ref, "read", writeOptions)),
1787
+ unsubscribe: verb(true, unsubscribe),
1788
+ markAllRead: verb(true, async (bulk = {}) => {
1789
+ await fetcher.raw(bulk.repo ? `${repoPath(bulk.repo)}/notifications` : "/notifications", {
1790
+ method: "PUT",
1791
+ query: {
1792
+ "last_read_at": bulk.before?.toISOString(),
1793
+ "to-status": "read"
1794
+ },
1795
+ signal: bulk.signal
1796
+ });
1797
+ }),
1798
+ unreadCount: verb(true, async (options) => (await fetcher.json("/notifications/new", { signal: options?.signal })).data.new)
1799
+ },
1800
+ checks: {
1801
+ list: verb(true, async (repo, sha, options) => ({ items: await statusChecks(repo, sha, options?.signal) })),
1802
+ report: verb(true, async (repo, sha, input, options) => toStatusCheck(repo, (await fetcher.json(`${repoPath(repo)}/statuses/${sha}`, {
1803
+ method: "POST",
1804
+ json: {
1805
+ state: STATUS_STATES[input.state],
1806
+ context: input.name,
1807
+ description: input.description,
1808
+ target_url: input.url
1809
+ },
1810
+ signal: options?.signal
1811
+ })).data))
1812
+ },
1813
+ ci: {
1814
+ runsPage: verb(giteaAnonymous ? false : actions(FORGEJO_ACTION_RUNS, GITEA_ACTION_RUNS), runsPage),
1815
+ getRun: verb(actions(FORGEJO_ACTION_RUNS, GITEA_ACTION_RUNS), async (ref, options) => {
1816
+ const path = `${repoPath(ref.repo)}/actions/runs/${encodeURIComponent(ref.id)}`;
1817
+ return isGitea ? toGiteaActionRun(ref.repo, (await fetcher.json(path, { signal: options?.signal })).data) : toActionRun(ref.repo, (await fetcher.json(path, { signal: options?.signal })).data);
1818
+ }),
1819
+ jobsPage: verb(actions(FORGEJO_ACTION_JOBS, GITEA_ACTION_RUNS), jobsPage),
1820
+ getJob: verb(isGitea && (anonymous ? "unverified" : actions(FORGEJO_ACTION_JOBS, GITEA_ACTION_RUNS)), async (ref, options) => {
1821
+ const { data } = await fetcher.json(`${repoPath(ref.repo)}/actions/jobs/${encodeURIComponent(ref.id)}`, { signal: options?.signal });
1822
+ const run = ref.run ?? (data.run_id === void 0 ? void 0 : {
1823
+ ...origin,
1824
+ repo: ref.repo,
1825
+ id: String(data.run_id)
1826
+ });
1827
+ if (!run) throw new UnsupportedOperationError(`Gitea returned job ${ref.id} without its run, and the ref names no run`, context);
1828
+ return toGiteaActionJob(run, data);
1829
+ }),
1830
+ log: verb(giteaAnonymous ? false : actions(FORGEJO_ACTION_JOBS, GITEA_ACTION_LOGS), async (ref, options) => (await fetcher.stream(`${repoPath(ref.repo)}/actions/jobs/${encodeURIComponent(ref.id)}/logs`, { signal: options?.signal })).body),
1831
+ rerunFailed: verb(isGitea && released(GITEA_RERUN_FAILED), async (ref, options) => {
1832
+ await fetcher.raw(`${repoPath(ref.repo)}/actions/runs/${encodeURIComponent(ref.id)}/rerun-failed-jobs`, {
1833
+ method: "POST",
1834
+ signal: options?.signal
1835
+ });
1836
+ })
1837
+ },
1838
+ contents: {
1839
+ getFile: verb(true, readFile),
1840
+ treePage: verb(true, async (repo, treeOptions = {}) => {
1841
+ const ref = treeOptions.ref ?? "HEAD";
1842
+ const { data, response } = await fetcher.json(`${repoPath(repo)}/git/trees/${encodeURIComponent(ref)}`, {
1843
+ query: {
1844
+ recursive: treeOptions.recursive ? "true" : void 0,
1845
+ per_page: treeOptions.perPage
1846
+ },
1847
+ signal: treeOptions.signal
1848
+ });
1849
+ const prefix = treeOptions.path?.replace(/^\/|\/$/g, "");
1850
+ const entries = (data.tree ?? []).filter((entry) => !prefix || entry.path.startsWith(`${prefix}/`));
1851
+ const warnings = data.truncated ? [{
1852
+ code: "tree_truncated",
1853
+ message: `${profile.forge} truncated the tree; read it directory by directory instead`,
1854
+ subject: ref
1855
+ }] : [];
1856
+ return toPage({
1857
+ data: entries,
1858
+ response,
1859
+ notModified: false
1860
+ }, toTreeEntry, warnings);
1861
+ }),
1862
+ branchesPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/branches`, listOptions, toBranch)),
1863
+ tagsPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/tags`, listOptions, toTag)),
1864
+ resolveRef: verb(true, async (repo, ref, options) => {
1865
+ const { data } = await fetcher.json(`${repoPath(repo)}/commits`, {
1866
+ query: {
1867
+ sha: ref,
1868
+ limit: 1,
1869
+ stat: "false"
1870
+ },
1871
+ signal: options?.signal
1872
+ });
1873
+ const sha = data[0]?.sha;
1874
+ if (!sha) throw new NotFoundError(`${profile.forge} has no commit for ${ref}`, 404, "", context);
1875
+ return sha;
1876
+ }),
1877
+ compare: verb(true, async (repo, base, head, options) => {
1878
+ const { data } = await fetcher.json(`${repoPath(repo)}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`, {
1879
+ query: { files: options?.files === false ? false : void 0 },
1880
+ signal: options?.signal
1881
+ });
1882
+ return {
1883
+ base,
1884
+ head,
1885
+ aheadBy: data.total_commits ?? data.commits?.length,
1886
+ commits: (data.commits ?? []).map((raw) => toCommit(repo, raw)),
1887
+ files: (data.files ?? []).map(toChangedFile),
1888
+ raw: data
1889
+ };
1890
+ }),
1891
+ commitFiles: verb(true, commitFiles)
1892
+ },
1893
+ commits: {
1894
+ listPage: verb(true, (repo, query = {}) => list(`${repoPath(repo)}/commits`, query, (raw) => toCommit(repo, raw), { query: {
1895
+ sha: query.ref,
1896
+ path: query.path,
1897
+ since: query.since?.toISOString(),
1898
+ until: query.until?.toISOString()
1899
+ } })),
1900
+ get: verb(true, async ({ repo, sha }, options) => toCommit(repo, (await fetcher.json(`${repoPath(repo)}/git/commits/${sha}`, {
1901
+ query: {
1902
+ stat: "true",
1903
+ files: "true"
1904
+ },
1905
+ signal: options?.signal
1906
+ })).data))
1907
+ },
1908
+ releases: {
1909
+ listPage: verb(true, releasesPage),
1910
+ get: verb(true, async (ref, options) => toRelease(ref.repo, (await fetcher.json(`${repoPath(ref.repo)}/releases/${encodeURIComponent(ref.id)}`, { signal: options?.signal })).data)),
1911
+ getByTag: verb(true, async (repo, tag, options) => toRelease(repo, (await fetcher.json(`${repoPath(repo)}/releases/tags/${encodeURIComponent(tag)}`, { signal: options?.signal })).data)),
1912
+ downloadAsset: verb(true, async (ref, downloadOptions = {}) => {
1913
+ const { data } = await fetcher.json(`${repoPath(ref.repo)}/releases/${encodeURIComponent(ref.release.id)}/assets/${encodeURIComponent(ref.id)}`, { signal: downloadOptions.signal });
1914
+ return (await fetcher.stream(data.browser_download_url, { signal: downloadOptions.signal })).body;
1915
+ }),
1916
+ latest: verb(true, async (repo, options) => {
1917
+ try {
1918
+ return toRelease(repo, (await fetcher.json(`${repoPath(repo)}/releases/latest`, { signal: options?.signal })).data);
1919
+ } catch (error) {
1920
+ if (error instanceof NotFoundError) return;
1921
+ throw error;
1922
+ }
1923
+ }),
1924
+ create: verb(true, (repo, input, options) => writeRelease(repo, `${repoPath(repo)}/releases`, "POST", input, options)),
1925
+ update: verb(true, (ref, update, options) => writeRelease(ref.repo, `${repoPath(ref.repo)}/releases/${encodeURIComponent(ref.id)}`, "PATCH", update, options))
1926
+ },
1927
+ threads: {
1928
+ checks: perKind({ pull_request: true }, async (thread, options) => {
1929
+ const ref = requireThread(thread, context);
1930
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
1931
+ return { items: data.head?.sha ? await statusChecks(ref.repo, data.head.sha, options?.signal) : [] };
1932
+ }),
1933
+ reviewsPage: verb(true, async (thread, listOptions = {}) => {
1934
+ const ref = requirePull(thread, "reviewed");
1935
+ const result = await fetcher.page(`${pullPath(ref)}/reviews`, {
1936
+ query: { limit: listOptions.perPage },
1937
+ cursor: listOptions.cursor,
1938
+ signal: listOptions.signal,
1939
+ conditional: false
1940
+ });
1941
+ return {
1942
+ items: await Promise.all((result.data ?? []).map(async (raw) => {
1943
+ const comments = raw.comments_count === 0 ? [] : (await fetcher.json(`${pullPath(ref)}/reviews/${encodeURIComponent(raw.id)}/comments`, { signal: listOptions.signal })).data ?? [];
1944
+ return toReview(ref, raw, comments.map((comment) => toReviewComment(ref, comment)));
1945
+ })),
1946
+ cursor: result.cursor,
1947
+ ...rateLimitPart(result.response)
1948
+ };
1949
+ }),
1950
+ /** A conversation takes replies from several reviews, so every review is read and the conversations come in one page. */
1951
+ reviewThreadsPage: verb("emulated", async (thread, listOptions = {}) => {
1952
+ const ref = requirePull(thread, "read for review threads");
1953
+ const reviews = await Array.fromAsync(fetcher.items(`${pullPath(ref)}/reviews`, {
1954
+ query: { limit: 50 },
1955
+ signal: listOptions.signal
1956
+ }));
1957
+ return { items: toReviewThreads(ref, (await mapConcurrent(reviews.filter((review) => review.comments_count !== 0), 4, async (review) => (await fetcher.json(`${pullPath(ref)}/reviews/${encodeURIComponent(review.id)}/comments`, { signal: listOptions.signal })).data ?? [])).flat()) };
1958
+ }),
1959
+ getReview: verb(true, async (ref, options) => {
1960
+ const pull = requirePull(ref.thread, "reviewed");
1961
+ const { data } = await fetcher.json(`${pullPath(pull)}/reviews/${encodeURIComponent(ref.id)}`, { signal: options?.signal });
1962
+ return toReview(pull, data, (data.comments_count === 0 ? [] : (await fetcher.json(`${pullPath(pull)}/reviews/${encodeURIComponent(ref.id)}/comments`, { signal: options?.signal })).data ?? []).map((comment) => toReviewComment(pull, comment)));
1963
+ }),
1964
+ filesPage: verb(true, (ref, listOptions = {}) => list(`${pullPath(requirePull(ref, "read for changed files"))}/files`, listOptions, toChangedFile)),
1965
+ commitsPage: verb(true, (ref, listOptions = {}) => list(`${pullPath(requirePull(ref, "read for commits"))}/commits`, listOptions, (raw) => toCommit(ref.repo, raw))),
1966
+ createReview: verb(true, createReview),
1967
+ submitReview: verb(true, async (ref, event, body, options) => {
1968
+ const pull = requirePull(ref.thread, "reviewed");
1969
+ const { data } = await fetcher.json(`${pullPath(pull)}/reviews/${encodeURIComponent(ref.id)}`, {
1970
+ method: "POST",
1971
+ json: {
1972
+ event: REVIEW_EVENTS[event],
1973
+ body: body ?? ""
1974
+ },
1975
+ signal: options?.signal
1976
+ });
1977
+ return toReview(pull, data, []);
1978
+ }),
1979
+ replyToReviewComment: verb(isGitea ? released(GITEA_REVIEW_REPLIES) : "not_applicable", async (thread, comment, body, options) => {
1980
+ const pull = requirePull(thread, "reviewed");
1981
+ if (comment.ref === void 0) throw new UnsupportedOperationError(`${profile.forge} replies to a review comment by its id; pass the comment with its \`ref\``, context);
1982
+ const { data } = await fetcher.json(`${pullPath(pull)}/comments/${encodeURIComponent(comment.ref.id)}/replies`, {
1983
+ method: "POST",
1984
+ json: { body },
1985
+ signal: options?.signal
1986
+ });
1987
+ return toReviewComment(pull, data);
1988
+ }),
1989
+ get: perKind(ISSUE_AND_PULL, get),
1990
+ getMany: verb(true, (refs, options) => getManyConcurrently(refs, get, options)),
1991
+ listPage: perKind(ISSUE_AND_PULL, listPage),
1992
+ eventsPage: verb(true, async (thread, listOptions = {}) => {
1993
+ const ref = requireThread(thread, context);
1994
+ return list(`${issuePath(ref)}/timeline`, {
1995
+ perPage: TIMELINE_PAGE_SIZE,
1996
+ ...listOptions
1997
+ }, (entry) => toEvent(ref, entry));
1998
+ }),
1999
+ commentsPage: perKind(ISSUE_AND_PULL, async (thread, listOptions = {}) => {
2000
+ const ref = requireIssueOrPull(thread, context, "list comments on");
2001
+ return list(`${issuePath(ref)}/comments`, listOptions, (raw) => toComment(ref, raw), { query: { since: listOptions.since?.toISOString() } });
2002
+ }),
2003
+ getComment: perKind(ISSUE_AND_PULL, async (ref, options) => {
2004
+ const thread = requireThread(ref.thread, context);
2005
+ const { data } = await fetcher.json(`${repoPath(thread.repo)}/issues/comments/${encodeURIComponent(ref.id)}`, { signal: options?.signal });
2006
+ if (!data) throw new NotFoundError(`Comment ${ref.id} not found`, 404, "", context);
2007
+ return toComment(thread, data);
2008
+ }),
2009
+ createComment: perKind({
2010
+ issue: true,
2011
+ pull_request: true
2012
+ }, async (thread, body, options) => {
2013
+ const ref = requireIssueOrPull(thread, context, "comment on");
2014
+ const { data } = await fetcher.json(`${issuePath(ref)}/comments`, {
2015
+ method: "POST",
2016
+ json: { body },
2017
+ signal: options?.signal
2018
+ });
2019
+ return toComment(ref, data);
2020
+ }),
2021
+ updateComment: perKind({
2022
+ issue: true,
2023
+ pull_request: true
2024
+ }, async (ref, body, options) => {
2025
+ const thread = requireThread(ref.thread, context);
2026
+ const { data } = await fetcher.json(`${repoPath(thread.repo)}/issues/comments/${encodeURIComponent(ref.id)}`, {
2027
+ method: "PATCH",
2028
+ json: { body },
2029
+ signal: options?.signal
2030
+ });
2031
+ return toComment(thread, data);
2032
+ }),
2033
+ deleteComment: perKind({
2034
+ issue: true,
2035
+ pull_request: true
2036
+ }, async (ref, options) => {
2037
+ await fetcher.raw(`${repoPath(ref.thread.repo)}/issues/comments/${encodeURIComponent(ref.id)}`, {
2038
+ method: "DELETE",
2039
+ signal: options?.signal
2040
+ });
2041
+ }),
2042
+ create: perKind({
2043
+ issue: true,
2044
+ pull_request: true
2045
+ }, async (repo, input, options) => {
2046
+ const labels = input.labels?.length ? await resolveLabels(repo, input.labels) : void 0;
2047
+ const assignees = input.assignees?.map(actorLogin);
2048
+ if (input.kind === "issue") {
2049
+ const { data } = await fetcher.json(`${repoPath(repo)}/issues`, {
2050
+ method: "POST",
2051
+ json: {
2052
+ title: input.title,
2053
+ body: input.body,
2054
+ labels,
2055
+ assignees
2056
+ },
2057
+ signal: options?.signal
2058
+ });
2059
+ return toThread({
2060
+ ...origin,
2061
+ repo,
2062
+ kind: "issue",
2063
+ number: String(data.number)
2064
+ }, data);
2065
+ }
2066
+ if (!input.head || !input.base) throw new UnsupportedOperationError("Creating a pull request needs head and base branches", context);
2067
+ const { data } = await fetcher.json(`${repoPath(repo)}/pulls`, {
2068
+ method: "POST",
2069
+ json: {
2070
+ title: input.draft ? `WIP: ${input.title}` : input.title,
2071
+ body: input.body,
2072
+ head: input.head,
2073
+ base: input.base,
2074
+ labels,
2075
+ assignees
2076
+ },
2077
+ signal: options?.signal
2078
+ });
2079
+ return toThread({
2080
+ ...origin,
2081
+ repo,
2082
+ kind: "pull_request",
2083
+ number: String(data.number)
2084
+ }, data);
2085
+ }),
2086
+ /** An issue edit takes no labels, so an issue's labels are set first and the edit response includes them. */
2087
+ update: perKind({
2088
+ issue: true,
2089
+ pull_request: true
2090
+ }, async (thread, input, options) => {
2091
+ const ref = requireIssueOrPull(thread, context, "update");
2092
+ const labels = input.labels && await resolveLabels(ref.repo, input.labels);
2093
+ const pull = ref.kind === "pull_request";
2094
+ if (labels && !pull) await fetcher.raw(`${issuePath(ref)}/labels`, {
2095
+ method: "PUT",
2096
+ json: { labels },
2097
+ signal: options?.signal
2098
+ });
2099
+ const json = {
2100
+ title: input.title,
2101
+ body: input.body,
2102
+ state: input.state,
2103
+ assignees: input.assignees?.map(actorLogin),
2104
+ labels: pull ? labels : void 0
2105
+ };
2106
+ const { data } = await fetcher.json(pull ? threadPath(ref) : issuePath(ref), {
2107
+ method: "PATCH",
2108
+ json,
2109
+ signal: options?.signal
2110
+ });
2111
+ return toThread(ref, data);
2112
+ }),
2113
+ addLabels: perKind({
2114
+ issue: true,
2115
+ pull_request: true
2116
+ }, async (thread, labels, options) => {
2117
+ const ref = requireIssueOrPull(thread, context, "label");
2118
+ return (await fetcher.json(`${issuePath(ref)}/labels`, {
2119
+ method: "POST",
2120
+ json: { labels: await resolveLabels(ref.repo, labels) },
2121
+ signal: options?.signal
2122
+ })).data.map(toLabel);
2123
+ }),
2124
+ /** The delete response has no body, so the labels are read afterwards. */
2125
+ removeLabels: perKind({
2126
+ issue: true,
2127
+ pull_request: true
2128
+ }, async (thread, labels, options) => {
2129
+ const ref = requireIssueOrPull(thread, context, "label");
2130
+ for (const id of await resolveLabels(ref.repo, labels)) await fetcher.raw(`${issuePath(ref)}/labels/${id}`, {
2131
+ method: "DELETE",
2132
+ signal: options?.signal
2133
+ });
2134
+ return (await fetcher.json(`${issuePath(ref)}/labels`, { signal: options?.signal })).data.map(toLabel);
2135
+ }),
2136
+ setMilestone: perKind({
2137
+ issue: true,
2138
+ pull_request: true
2139
+ }, async (thread, milestone, options) => {
2140
+ const ref = requireIssueOrPull(thread, context, "set the milestone of");
2141
+ const { data } = await fetcher.json(issuePath(ref), {
2142
+ method: "PATCH",
2143
+ json: { milestone: milestone === void 0 ? 0 : await milestoneId(milestone, (page) => milestonesPage(ref.repo, page), context, options) },
2144
+ signal: options?.signal
2145
+ });
2146
+ return toMilestone(data.milestone);
2147
+ }),
2148
+ reactionsPage: perKind(ISSUE_AND_PULL, async (target, listOptions = {}) => {
2149
+ const result = await fetcher.page(reactionPath(target), {
2150
+ query: { limit: listOptions.perPage },
2151
+ cursor: listOptions.cursor,
2152
+ signal: listOptions.signal
2153
+ });
2154
+ return toPage(result, (raw) => {
2155
+ const reactor = toActor(context, raw.user);
2156
+ return reactor && {
2157
+ content: reactionContent(raw.content),
2158
+ contentRaw: raw.content,
2159
+ actor: reactor,
2160
+ createdAt: toDate(raw.created_at),
2161
+ raw
2162
+ };
2163
+ });
2164
+ }),
2165
+ reactions: perKind({
2166
+ issue: true,
2167
+ pull_request: true
2168
+ }, {
2169
+ react: (target, reaction, options) => setReaction(target, reaction, "POST", options),
2170
+ unreact: (target, reaction, options) => setReaction(target, reaction, "DELETE", options)
2171
+ }),
2172
+ setLabels: perKind({
2173
+ issue: true,
2174
+ pull_request: true
2175
+ }, async (thread, labels, options) => {
2176
+ const ref = requireIssueOrPull(thread, context, "label");
2177
+ return (await fetcher.json(`${issuePath(ref)}/labels`, {
2178
+ method: "PUT",
2179
+ json: { labels: await resolveLabels(ref.repo, labels) },
2180
+ signal: options?.signal
2181
+ })).data.map(toLabel);
2182
+ }),
2183
+ setAssignees: perKind({
2184
+ issue: true,
2185
+ pull_request: true
2186
+ }, async (thread, assignees, options) => {
2187
+ const ref = requireIssueOrPull(thread, context, "assign");
2188
+ const { data } = await fetcher.json(issuePath(ref), {
2189
+ method: "PATCH",
2190
+ json: { assignees: assignees.map(actorLogin) },
2191
+ signal: options?.signal
2192
+ });
2193
+ return (data.assignees ?? []).flatMap((user) => toActor(context, user) ?? []);
2194
+ }),
2195
+ requestReview: perKind({ pull_request: true }, async (thread, reviewers, options) => {
2196
+ await fetcher.raw(`${threadPath(requireThread(thread, context))}/requested_reviewers`, {
2197
+ method: "POST",
2198
+ json: { reviewers: reviewers.map(actorLogin) },
2199
+ signal: options?.signal
2200
+ });
2201
+ }),
2202
+ close: perKind({
2203
+ issue: true,
2204
+ pull_request: true
2205
+ }, (ref, options) => setState(ref, "closed", options)),
2206
+ reopen: perKind({
2207
+ issue: true,
2208
+ pull_request: true
2209
+ }, (ref, options) => setState(ref, "open", options)),
2210
+ ...isGitea ? { locking: perKind({
2211
+ issue: released(GITEA_LOCKS),
2212
+ pull_request: released(GITEA_LOCKS)
2213
+ }, {
2214
+ lock: (thread, options) => setLocked(thread, true, options),
2215
+ unlock: (thread, options) => setLocked(thread, false, options)
2216
+ }) } : {},
2217
+ merge: verb(true, merge),
2218
+ updateBranch: verb(true, updateBranch),
2219
+ subscriptions: perKind(ISSUE_AND_PULL, {
2220
+ async subscription(thread, options) {
2221
+ const ref = requireIssueOrPull(thread, context, "read the subscription of");
2222
+ const { data } = await fetcher.json(`${issuePath(ref)}/subscriptions/check`, { signal: options?.signal });
2223
+ return data.ignored ? "ignored" : data.subscribed ? "subscribed" : "none";
2224
+ },
2225
+ async subscribe(thread, options) {
2226
+ const ref = requireIssueOrPull(thread, context, "subscribe to");
2227
+ await fetcher.raw(await subscriptionPath({
2228
+ owner: ref.repo.owner,
2229
+ name: ref.repo.name,
2230
+ number: ref.number
2231
+ }), {
2232
+ method: "PUT",
2233
+ signal: options?.signal
2234
+ });
2235
+ },
2236
+ async unsubscribe(thread, options) {
2237
+ const ref = requireIssueOrPull(thread, context, "unsubscribe from");
2238
+ await fetcher.raw(await subscriptionPath({
2239
+ owner: ref.repo.owner,
2240
+ name: ref.repo.name,
2241
+ number: ref.number
2242
+ }), {
2243
+ method: "DELETE",
2244
+ signal: options?.signal
2245
+ });
2246
+ }
2247
+ })
2248
+ },
2249
+ web: profile.web.links({
2250
+ baseUrl,
2251
+ instance: origin.instance
2252
+ }),
2253
+ webhooks: {
2254
+ listPage: verb(true, (target, listOptions = {}) => list(hooksPath(target), listOptions, (raw) => toWebhook(target, raw))),
2255
+ create: verb(true, async (target, input, options) => toWebhook(target, (await fetcher.json(hooksPath(target), {
2256
+ method: "POST",
2257
+ json: {
2258
+ type: "gitea",
2259
+ active: input.active ?? true,
2260
+ events: nativeEventsFor(FORGEJO_NATIVE_EVENTS, input.events, input.nativeEvents),
2261
+ config: {
2262
+ url: input.url,
2263
+ content_type: input.contentType ?? "json",
2264
+ ...input.secret ? { secret: input.secret } : {}
2265
+ }
2266
+ },
2267
+ signal: options?.signal
2268
+ })).data)),
2269
+ update: verb(true, async (ref, update, options) => toWebhook(ref.target, (await fetcher.json(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
2270
+ method: "PATCH",
2271
+ json: {
2272
+ ...update.active === void 0 ? {} : { active: update.active },
2273
+ ...update.events || update.nativeEvents ? { events: nativeEventsFor(FORGEJO_NATIVE_EVENTS, update.events, update.nativeEvents) } : {},
2274
+ ...update.url || update.secret || update.contentType ? { config: {
2275
+ ...update.url ? { url: update.url } : {},
2276
+ content_type: update.contentType ?? "json",
2277
+ ...update.secret ? { secret: update.secret } : {}
2278
+ } } : {}
2279
+ },
2280
+ signal: options?.signal
2281
+ })).data)),
2282
+ delete: verb(true, async (ref, options) => {
2283
+ await fetcher.raw(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
2284
+ method: "DELETE",
2285
+ signal: options?.signal
2286
+ });
2287
+ }),
2288
+ rotateSecret: verb(true, async (ref, secret, options) => {
2289
+ const current = toWebhook(ref.target, (await fetcher.json(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, { signal: options?.signal })).data);
2290
+ const { data } = await fetcher.json(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
2291
+ method: "PATCH",
2292
+ json: { config: {
2293
+ url: current.url,
2294
+ content_type: current.contentType ?? "json",
2295
+ secret
2296
+ } },
2297
+ signal: options?.signal
2298
+ });
2299
+ return toWebhook(ref.target, data);
2300
+ })
2301
+ },
2302
+ scopes: forgejoScopesFor
2303
+ };
2304
+ }
2305
+ /**
2306
+ * Forgejo and Gitea token scopes, which are per resource group with a
2307
+ * `read:` or `write:` prefix.
2308
+ */
2309
+ function forgejoScopesFor(verb) {
2310
+ const [group = "", name = ""] = verb.split(".");
2311
+ const write = WRITE_VERBS.has(verb);
2312
+ if (group === "webhooks") return name === "verify" || name === "ingest" ? {} : { token: ["write:repository", "write:organization"] };
2313
+ if (group === "notifications") return { token: [name === "list" || name === "page" || name === "unreadCount" ? "read:notification" : "write:notification"] };
2314
+ if (group === "users" || group === "search") return { token: [write ? "write:user" : "read:user"] };
2315
+ if (group === "orgs") return { token: [write ? "write:organization" : "read:organization"] };
2316
+ if (group === "threads" || group === "repos" || group === "contents" || group === "releases" || group === "checks" || group === "ci") return { token: [write ? "write:issue" : "read:issue", write ? "write:repository" : "read:repository"] };
2317
+ return {};
2318
+ }
2319
+ //#endregion
2320
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/forgejo/index.mjs
2321
+ /** Creates a Forgejo provider for Codeberg or any self-hosted Forgejo instance. */
2322
+ const forgejo = /* @__PURE__ */ defineForgeProvider(/* @__PURE__ */ forgejoDefinition(FORGEJO_PROFILE));
2323
+ //#endregion
2324
+ export { forgejo, toThread as i, toActor as n, toRepoRef as r, FORGEJO_HEADERS as t };