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