@vite-hub/forge 0.0.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1890 @@
1
+ import { D as forgeIterable, L as memo, M as isFirstPage, P as iteratePages, S as createFetcher, _ as WebhookVerificationError, d as NotFoundError, dt as namespaceRef, ft as normaliseRepoName, g as UnsupportedOperationError, lt as isResolvedThread, p as ReadOnlyError, r as ContentNotTextError, ut as isUnsupported, w as createRequest } from "./utils-DC7MBR65-B7Vr2hFm.js";
2
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/crypto-DydCoK4e.mjs
3
+ const encoder = new TextEncoder();
4
+ function toBytes(value) {
5
+ return typeof value === "string" ? encoder.encode(value) : value;
6
+ }
7
+ function toHex(buffer) {
8
+ return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
9
+ }
10
+ /** Base64 for arbitrary bytes, a byte at a time so a large buffer cannot overflow the call stack. */
11
+ function toBase64(bytes) {
12
+ let binary = "";
13
+ for (const byte of bytes) binary += String.fromCharCode(byte);
14
+ return btoa(binary);
15
+ }
16
+ function toBase64Url(input) {
17
+ return (typeof input === "string" ? btoa(input) : toBase64(input)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
18
+ }
19
+ async function hmacSha256(secret, body) {
20
+ const key = await crypto.subtle.importKey("raw", toBytes(secret), {
21
+ name: "HMAC",
22
+ hash: "SHA-256"
23
+ }, false, ["sign"]);
24
+ return crypto.subtle.sign("HMAC", key, toBytes(body));
25
+ }
26
+ /** Lowercase hex HMAC-SHA256 of `body` under `secret`. */
27
+ async function hmacSha256Hex(secret, body) {
28
+ return toHex(await hmacSha256(secret, body));
29
+ }
30
+ /**
31
+ * Constant-time comparison of two strings. The time taken depends only on the
32
+ * length of `a`, so pass the untrusted value as `a`.
33
+ */
34
+ function timingSafeEqual(a, b) {
35
+ let mismatch = a.length ^ b.length;
36
+ for (let index = 0; index < a.length; index++) mismatch |= a.charCodeAt(index) ^ b.charCodeAt(index % b.length);
37
+ return mismatch === 0;
38
+ }
39
+ function decodePem(pem) {
40
+ const pkcs1 = pem.includes("BEGIN RSA PRIVATE KEY");
41
+ const body = pem.replace(/-----(?:BEGIN|END)[^-]+-----/g, "").replace(/\s+/g, "");
42
+ const binary = atob(body);
43
+ const der = new Uint8Array(binary.length);
44
+ for (let index = 0; index < binary.length; index++) der[index] = binary.charCodeAt(index);
45
+ return {
46
+ der,
47
+ pkcs1
48
+ };
49
+ }
50
+ function derLength(length) {
51
+ if (length < 128) return [length];
52
+ const bytes = [];
53
+ let remaining = length;
54
+ while (remaining > 0) {
55
+ bytes.unshift(remaining & 255);
56
+ remaining >>= 8;
57
+ }
58
+ return [128 | bytes.length, ...bytes];
59
+ }
60
+ /**
61
+ * Wraps a PKCS#1 RSA key in a PKCS#8 `PrivateKeyInfo`. GitHub App keys are
62
+ * distributed as PKCS#1, which Web Crypto cannot import directly.
63
+ */
64
+ function pkcs1ToPkcs8(der) {
65
+ const algorithm = [
66
+ 48,
67
+ 13,
68
+ 6,
69
+ 9,
70
+ 42,
71
+ 134,
72
+ 72,
73
+ 134,
74
+ 247,
75
+ 13,
76
+ 1,
77
+ 1,
78
+ 1,
79
+ 5,
80
+ 0
81
+ ];
82
+ const octetString = [
83
+ 4,
84
+ ...derLength(der.length),
85
+ ...der
86
+ ];
87
+ const contents = [
88
+ 2,
89
+ 1,
90
+ 0,
91
+ ...algorithm,
92
+ ...octetString
93
+ ];
94
+ return new Uint8Array([
95
+ 48,
96
+ ...derLength(contents.length),
97
+ ...contents
98
+ ]);
99
+ }
100
+ /** Signs an RS256 JWT with a PEM-encoded RSA private key. */
101
+ async function signRs256Jwt(privateKeyPem, claims) {
102
+ const { der, pkcs1 } = decodePem(privateKeyPem);
103
+ const key = await crypto.subtle.importKey("pkcs8", pkcs1 ? pkcs1ToPkcs8(der) : der, {
104
+ name: "RSASSA-PKCS1-v1_5",
105
+ hash: "SHA-256"
106
+ }, false, ["sign"]);
107
+ const payload = `${toBase64Url(JSON.stringify({
108
+ alg: "RS256",
109
+ typ: "JWT"
110
+ }))}.${toBase64Url(JSON.stringify(claims))}`;
111
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, encoder.encode(payload));
112
+ return `${payload}.${toBase64Url(new Uint8Array(signature))}`;
113
+ }
114
+ /** The value of a header, whatever the casing of `name`, from a `Headers` object or a plain record. */
115
+ function headerValue(headers, name) {
116
+ if (headers instanceof Headers) return headers.get(name) ?? void 0;
117
+ const lower = name.toLowerCase();
118
+ for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === lower) return value;
119
+ }
120
+ /** A request body as text. */
121
+ function bodyText(body) {
122
+ return typeof body === "string" ? body : new TextDecoder().decode(body);
123
+ }
124
+ //#endregion
125
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/web-De5LwgO3.mjs
126
+ function sameRepo(a, b) {
127
+ if (!b || a.forge !== b.forge || a.instance !== b.instance) return false;
128
+ const [left, right] = [normaliseRepoName(a), normaliseRepoName(b)];
129
+ return left.owner === right.owner && left.name === right.name;
130
+ }
131
+ function lineOf(value) {
132
+ const line = Number.parseInt(value ?? "", 10);
133
+ return line > 0 ? { line } : {};
134
+ }
135
+ /** Reads `base...head` or `base..head`. Git forbids `..` in a ref name, so the first `..` separates the two. */
136
+ function rangeOf(value) {
137
+ const at = value.indexOf("..");
138
+ const base = value.slice(0, at);
139
+ const head = value.slice(value[at + 2] === "." ? at + 3 : at + 2);
140
+ return at > 0 && head ? { compare: {
141
+ base,
142
+ head
143
+ } } : {};
144
+ }
145
+ function encodePath(path) {
146
+ return path.split("/").map(encodeURIComponent).join("/");
147
+ }
148
+ function webUrlFor(web, target) {
149
+ if (("file" in target ? target.file : "raw" in target ? target.raw : "commit" in target ? target.commit : "compare" in target ? target.compare : void 0)?.repo.kind === "namespace") return;
150
+ let path;
151
+ if ("repo" in target) path = "section" in target && target.section ? web.section?.(target.repo, target.section) : web.repo(target.repo);
152
+ else if ("thread" in target) path = isResolvedThread(target.thread) || target.thread.displayNumber ? web.thread(target.thread) : void 0;
153
+ else if ("comment" in target) {
154
+ const { comment } = target;
155
+ path = isResolvedThread(comment.thread) ? web.comment?.(comment) : void 0;
156
+ } else if ("release" in target) path = web.release?.(target.release);
157
+ else if ("file" in target) path = web.file?.(target.file.repo, target.file.path, target.file.at ?? "HEAD", target.file.line);
158
+ else if ("raw" in target) path = web.raw?.(target.raw.repo, target.raw.path, target.raw.at ?? "HEAD");
159
+ else if ("commit" in target) path = target.commit.sha ? web.commit?.(target.commit.repo, target.commit.sha) : void 0;
160
+ else path = web.compare?.(target.compare.repo, target.compare.base, target.compare.head);
161
+ return path === void 0 ? void 0 : path.startsWith("/") ? `${web.baseUrl}${path}` : path;
162
+ }
163
+ /** `ssh://user@host:port/path` or `git://host:port/path` with the host in group 1, or `user@host:path` with it in group 2; the path is group 3. */
164
+ const CLONE_URL_RE = /^(?:(?:ssh|git):\/\/(?:[^@/]+@)?([^:/]+)(?::\d+)?\/|(?:[^@/\s]+@)?([^:/\s]+):(?!\/))(.+)$/i;
165
+ /** The `git+` that npm's `repository` field writes before a transport scheme. */
166
+ const GIT_PLUS_RE = /^git\+(?=[a-z]+:\/\/)/i;
167
+ /** The npm `repository` shorthand, https://docs.npmjs.com/cli/configuring-npm/package-json#repository */
168
+ const SHORTHAND_RE = /^(github|gitlab|bitbucket):(?!\/)/i;
169
+ const SHORTHAND_HOSTS = {
170
+ github: "github.com",
171
+ gitlab: "gitlab.com",
172
+ bitbucket: "bitbucket.org"
173
+ };
174
+ function parseWebUrl(web, input, origin) {
175
+ const base = new URL(web.baseUrl);
176
+ const prefix = base.pathname.replace(/\/$/, "");
177
+ const source = String(input).replace(GIT_PLUS_RE, "").replace(SHORTHAND_RE, (_, forge) => `https://${SHORTHAND_HOSTS[forge.toLowerCase()]}/`);
178
+ const clone = CLONE_URL_RE.exec(source);
179
+ let url;
180
+ try {
181
+ url = new URL(clone && (clone[1] ?? clone[2]).toLowerCase() === base.hostname ? `${base.origin}${prefix}/${clone[3]}` : source);
182
+ } catch {
183
+ return;
184
+ }
185
+ if (url.protocol !== "http:" && url.protocol !== "https:" || url.host !== base.host && !web.hosts?.includes(url.host) || url.username || url.password) return;
186
+ if (prefix && !url.pathname.startsWith(`${prefix}/`)) return;
187
+ let segments;
188
+ try {
189
+ segments = url.pathname.slice(prefix.length).split("/").filter(Boolean).map(decodeURIComponent);
190
+ } catch {
191
+ return;
192
+ }
193
+ return web.parse(segments, url, origin);
194
+ }
195
+ function referenceFor(web, ref, options = {}) {
196
+ if (!web || !("sha" in ref || isResolvedThread(ref) || ref.displayNumber)) return;
197
+ return web.reference?.(ref, sameRepo(ref.repo, options.from), options.expand ?? false) ?? webUrlFor(web, "sha" in ref ? { commit: ref } : { thread: ref });
198
+ }
199
+ /** `owner/name`, for forges that nest no deeper. */
200
+ const OWNER_NAME = String.raw`[\w.-]+\/[\w.-]+`;
201
+ /** What cannot come right before a reference, so that a path, an email address or a word does not read as one. */
202
+ const BEFORE = String.raw`(?<![\w/.@#~&!+-])`;
203
+ /** What cannot come right after a reference: a word character, or a dot, slash or `@` that continues a word. */
204
+ const AFTER = String.raw`(?![\w-]|[./@]\w)`;
205
+ const SHA = "[0-9a-f]{7,40}";
206
+ const SCHEME_CHAR = /[\w+.-]/;
207
+ const LETTER = /[a-z]/i;
208
+ const SPACE = /\s/;
209
+ const rules = /* @__PURE__ */ new WeakMap();
210
+ function repoIn(slug, origin) {
211
+ const at = slug.lastIndexOf("/");
212
+ return {
213
+ ...origin,
214
+ owner: slug.slice(0, at),
215
+ name: slug.slice(at + 1)
216
+ };
217
+ }
218
+ /** The spans of URLs in `text`, each from its scheme to the next whitespace. */
219
+ function urlSpans(text) {
220
+ const spans = [];
221
+ for (let at = text.indexOf("://"); at !== -1; at = text.indexOf("://", at + 1)) {
222
+ let start = at;
223
+ while (start > 0 && SCHEME_CHAR.test(text[start - 1])) start--;
224
+ while (start < at && !LETTER.test(text[start])) start++;
225
+ if (start === at || at + 3 >= text.length || SPACE.test(text[at + 3])) continue;
226
+ let end = at + 4;
227
+ while (end < text.length && !SPACE.test(text[end])) end++;
228
+ spans.push([start, end]);
229
+ at = end;
230
+ }
231
+ return spans;
232
+ }
233
+ /** A bare sha needs a letter and a digit, so that neither a number nor a word reads as one. */
234
+ function isBareSha(value) {
235
+ return /[a-f]/.test(value) && /\d/.test(value);
236
+ }
237
+ function rulesFor(syntax) {
238
+ const cached = rules.get(syntax);
239
+ if (cached) return cached;
240
+ const compiled = [];
241
+ const rule = (source, read) => compiled.push({
242
+ pattern: new RegExp(`${BEFORE}${source}${AFTER}`, "g"),
243
+ read
244
+ });
245
+ const suffix = syntax.suffix ? `(?:${syntax.suffix})?` : "";
246
+ for (const { prefix, kind, number = String.raw`[1-9]\d*`, displayNumber, sameRepo: local, namespace } of syntax.threads) {
247
+ const thread = `${prefix.replace(/[$()*+.?[\\\]^{|}]/g, "\\$&")}(?<id>${number})${suffix}`;
248
+ rule(thread, ({ id }, from, origin) => ({
249
+ ...origin,
250
+ repo: namespace ? namespaceRef(origin, from.owner) : from,
251
+ kind,
252
+ ...displayNumber ? { displayNumber: id } : { number: id }
253
+ }));
254
+ if (syntax.repo && !local) rule(`(?<slug>${syntax.repo})${thread}`, ({ slug, id }, _, origin) => ({
255
+ ...origin,
256
+ repo: repoIn(slug, origin),
257
+ kind,
258
+ ...displayNumber ? { displayNumber: id } : { number: id }
259
+ }));
260
+ }
261
+ if (syntax.commits) {
262
+ rule(`(?<sha>${SHA})`, ({ sha }, from, origin) => isBareSha(sha) ? {
263
+ ...origin,
264
+ repo: from,
265
+ sha
266
+ } : void 0);
267
+ if (syntax.repo) rule(`(?<slug>${syntax.repo})@(?<sha>${SHA})`, ({ slug, sha }, _, origin) => ({
268
+ ...origin,
269
+ repo: repoIn(slug, origin),
270
+ sha
271
+ }));
272
+ }
273
+ rules.set(syntax, compiled);
274
+ return compiled;
275
+ }
276
+ function parseReferences(web, text, from, origin) {
277
+ if (!web?.references || from.forge !== origin.forge || from.instance !== origin.instance) return [];
278
+ const urls = urlSpans(text);
279
+ const found = [];
280
+ for (const { pattern, read } of rulesFor(web.references)) for (const match of text.matchAll(pattern)) {
281
+ const ref = urls.some(([start, end]) => match.index >= start && match.index < end) ? void 0 : read(match.groups, from, origin);
282
+ if (ref) found.push({
283
+ start: match.index,
284
+ end: match.index + match[0].length,
285
+ ref
286
+ });
287
+ }
288
+ found.sort((a, b) => a.start - b.start || b.end - a.end);
289
+ let end = 0;
290
+ return found.filter((match) => {
291
+ if (match.start < end) return false;
292
+ end = match.end;
293
+ return true;
294
+ });
295
+ }
296
+ /** Reads GitHub's file route, `blob/{at}/{path}`. */
297
+ function parseGitHubFile([route, at, ...path]) {
298
+ return route === "blob" && at && path.length ? {
299
+ at,
300
+ path: path.join("/")
301
+ } : void 0;
302
+ }
303
+ /** Web links for forges laid out like GitHub: `/{owner}/{name}/issues/{n}` and friends. */
304
+ function githubShapedWeb(baseUrl, shape) {
305
+ const repoPath = (repo) => `/${encodePath(repo.owner)}/${encodeURIComponent(repo.name)}`;
306
+ const kindPath = {
307
+ issue: "issues",
308
+ pull_request: shape.pull,
309
+ ...shape.discussions ? { discussion: "discussions" } : {}
310
+ };
311
+ const commitPath = shape.commit ?? "commit";
312
+ const kindOf = new Map(Object.entries(kindPath).map(([kind, path]) => [path, kind]));
313
+ const reserved = new Set(shape.reserved?.map((segment) => segment.toLowerCase()));
314
+ const parseFile = shape.parseFile ?? parseGitHubFile;
315
+ return {
316
+ baseUrl,
317
+ repo: repoPath,
318
+ section: (repo, section) => {
319
+ if (repo.kind === "namespace") return;
320
+ const path = shape.sections?.[section];
321
+ if (path === null) return;
322
+ return `${repoPath(repo)}/${path ?? (section === "pullRequests" ? "pulls" : section)}`;
323
+ },
324
+ thread: (ref) => kindPath[ref.kind] && ref.number ? `${repoPath(ref.repo)}/${kindPath[ref.kind]}/${encodeURIComponent(ref.number)}` : void 0,
325
+ comment: (ref) => kindPath[ref.thread.kind] && `${repoPath(ref.thread.repo)}/${kindPath[ref.thread.kind]}/${encodeURIComponent(ref.thread.number)}#${shape.commentFragment}${ref.id}`,
326
+ commit: (repo, sha) => `${repoPath(repo)}/${commitPath}/${encodeURIComponent(sha)}`,
327
+ release: (ref) => ref.tag ? `${repoPath(ref.repo)}/releases/tag/${encodeURIComponent(ref.tag)}` : void 0,
328
+ file: (repo, path, at, line) => `${repoPath(repo)}${shape.file(at)}/${encodePath(path)}${line ? `#${shape.lineFragment(line)}` : ""}`,
329
+ raw: (repo, path, at) => shape.raw === false ? void 0 : shape.rawOrigin ? `${shape.rawOrigin}${repoPath(repo)}/${encodeURIComponent(at)}/${encodePath(path)}` : `${repoPath(repo)}/raw/${encodeURIComponent(at)}/${encodePath(path)}`,
330
+ compare: (repo, base, head) => `${repoPath(repo)}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`,
331
+ parse: (segments, url, from) => {
332
+ const [owner, name, section, id] = segments;
333
+ if (!owner || !name || reserved.has(owner.toLowerCase())) return;
334
+ const repo = {
335
+ ...from,
336
+ owner,
337
+ name: name.replace(/\.git$/, "")
338
+ };
339
+ const file = parseFile(segments.slice(2));
340
+ if (file) return {
341
+ repo,
342
+ file: {
343
+ ...file,
344
+ ...lineOf(url.hash.replace(/^#L/, ""))
345
+ }
346
+ };
347
+ const kind = section ? kindOf.get(section) : void 0;
348
+ if (section === "releases" && id === "tag" && segments[4]) return {
349
+ repo,
350
+ release: {
351
+ ...from,
352
+ repo,
353
+ id: segments[4],
354
+ tag: segments[4]
355
+ }
356
+ };
357
+ if (section === commitPath && id) return {
358
+ repo,
359
+ commit: {
360
+ ...from,
361
+ repo,
362
+ sha: id
363
+ }
364
+ };
365
+ if (section === "compare" && id) return {
366
+ repo,
367
+ ...rangeOf(segments.slice(3).join("/"))
368
+ };
369
+ if (!kind || !id) return { repo };
370
+ const thread = {
371
+ ...from,
372
+ repo,
373
+ kind,
374
+ number: id
375
+ };
376
+ if (kind === "pull_request" && segments[4] === "commits" && segments[5]) return {
377
+ repo,
378
+ thread,
379
+ commit: {
380
+ ...from,
381
+ repo,
382
+ sha: segments[5]
383
+ }
384
+ };
385
+ const comment = url.hash.startsWith(`#${shape.commentFragment}`) ? url.hash.slice(shape.commentFragment.length + 1) : void 0;
386
+ return {
387
+ repo,
388
+ thread,
389
+ ...comment ? { comment: {
390
+ ...from,
391
+ thread,
392
+ id: comment
393
+ } } : {}
394
+ };
395
+ },
396
+ reference: (ref, same) => {
397
+ if ("sha" in ref) return same ? ref.sha.slice(0, 7) : `${ref.repo.owner}/${ref.repo.name}@${ref.sha.slice(0, 7)}`;
398
+ if (!ref.number) return;
399
+ const prefix = ref.kind === "pull_request" && shape.pullPrefix ? shape.pullPrefix : "#";
400
+ return `${same ? "" : `${ref.repo.owner}/${ref.repo.name}`}${prefix}${ref.number}`;
401
+ },
402
+ references: shape.references ?? {
403
+ threads: [{
404
+ prefix: "#",
405
+ kind: "issue"
406
+ }, ...shape.pullPrefix ? [{
407
+ prefix: shape.pullPrefix,
408
+ kind: "pull_request"
409
+ }] : []],
410
+ repo: OWNER_NAME,
411
+ commits: true
412
+ }
413
+ };
414
+ }
415
+ /** The API base URL and the instance that `options` select. */
416
+ function resolveInstance(definition, options) {
417
+ const root = (options.baseUrl ?? definition.baseUrl).replace(/\/$/, "");
418
+ const baseUrl = definition.apiPath && !root.endsWith(definition.apiPath) ? `${root}${definition.apiPath}` : root;
419
+ let host;
420
+ try {
421
+ host = new URL(baseUrl).host;
422
+ } catch (cause) {
423
+ throw new TypeError(`Invalid baseUrl for ${definition.forge}: ${JSON.stringify(baseUrl)}`, { cause });
424
+ }
425
+ return {
426
+ baseUrl,
427
+ instance: options.instance ?? definition.instance?.(host) ?? host
428
+ };
429
+ }
430
+ //#endregion
431
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/define-BRQZP-ft.mjs
432
+ /** Decodes base64, tolerating the newlines GitHub and Gitea wrap it in. */
433
+ function fromBase64(value) {
434
+ const binary = atob(value.replaceAll(/\s/g, ""));
435
+ const bytes = new Uint8Array(binary.length);
436
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
437
+ return bytes;
438
+ }
439
+ /**
440
+ * Shapes bytes as the caller asked: UTF-8 text for `as: 'text'`, bytes
441
+ * otherwise. Rejects with {@link ContentNotTextError} when text was asked for
442
+ * and the bytes are not valid UTF-8.
443
+ */
444
+ function toFileContent(bytes, file, options, context) {
445
+ return options?.as === "text" ? {
446
+ ...file,
447
+ content: decodeText(bytes, file.path, context),
448
+ encoding: "utf-8"
449
+ } : {
450
+ ...file,
451
+ content: bytes,
452
+ encoding: "binary"
453
+ };
454
+ }
455
+ /** Decodes UTF-8, rejecting with {@link ContentNotTextError} that names `what` when the bytes are not text. */
456
+ function decodeText(bytes, what, context) {
457
+ try {
458
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
459
+ } catch (cause) {
460
+ throw new ContentNotTextError(`${what} is not valid UTF-8 text`, context, { cause });
461
+ }
462
+ }
463
+ /** The bytes of a file to write, with a string encoded as UTF-8. */
464
+ function changeBytes(content) {
465
+ return typeof content === "string" ? new TextEncoder().encode(content) : content;
466
+ }
467
+ /** Base64 of a file to write, with a string encoded as UTF-8. */
468
+ function changeBase64(content) {
469
+ return toBase64(changeBytes(content));
470
+ }
471
+ /** The directory that holds `path`, or `''` at the root. */
472
+ function directoryOf(path) {
473
+ const index = path.lastIndexOf("/");
474
+ return index < 0 ? "" : path.slice(0, index);
475
+ }
476
+ /**
477
+ * Looks up the files that `changes` touch with `find`, which resolves to `undefined` for a missing file,
478
+ * and rejects with {@link NotFoundError} when a file to delete does not exist.
479
+ */
480
+ async function existingFiles(changes, find, context) {
481
+ const found = await Promise.all(changes.map(async (change) => [change.path, await find(change.path)]));
482
+ const missing = changes.find((change, index) => change.content === null && found[index][1] === void 0);
483
+ if (missing) throw new NotFoundError(`${missing.path} does not exist, so it cannot be deleted`, 404, "", context);
484
+ return new Map(found.flatMap(([path, file]) => file === void 0 ? [] : [[path, file]]));
485
+ }
486
+ /**
487
+ * Finds files by listing their directories, once per directory.
488
+ * @param list Reads the entries of a directory by their full path, or `undefined` when it does not exist.
489
+ */
490
+ function inDirectories(list) {
491
+ const listings = /* @__PURE__ */ new Map();
492
+ return async (path) => {
493
+ const directory = directoryOf(path);
494
+ if (!listings.has(directory)) listings.set(directory, list(directory));
495
+ return (await listings.get(directory))?.get(path);
496
+ };
497
+ }
498
+ /** The first line of a commit message and the rest, as forges that take them apart expect. */
499
+ function splitMessage(message) {
500
+ const [headline = "", ...rest] = message.split("\n");
501
+ const body = rest.join("\n").replace(/^\n+/, "");
502
+ return body ? {
503
+ headline,
504
+ body
505
+ } : { headline };
506
+ }
507
+ /** True for a full SHA-1 or SHA-256 commit id, which needs no lookup to resolve. */
508
+ function isSha(ref) {
509
+ return /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(ref);
510
+ }
511
+ /**
512
+ * Every capability with the verbs it covers and the flags that gate it, in the order the capability matrix lists them.
513
+ */
514
+ const CAPABILITY_TABLE = [
515
+ {
516
+ capability: "experimental",
517
+ derived: "experimental",
518
+ verbs: []
519
+ },
520
+ { capability: "sources.stream" },
521
+ { capability: "repos.get" },
522
+ { capability: "users.get" },
523
+ {
524
+ capability: "users.me",
525
+ account: true
526
+ },
527
+ {
528
+ capability: "users.sponsorable",
529
+ account: true
530
+ },
531
+ {
532
+ capability: "users.events",
533
+ listing: true
534
+ },
535
+ {
536
+ capability: "users.block",
537
+ write: true,
538
+ account: true,
539
+ spec: "users.blocking",
540
+ verbs: ["users.block", "users.unblock"]
541
+ },
542
+ {
543
+ capability: "repos.list",
544
+ account: true,
545
+ listing: true
546
+ },
547
+ {
548
+ capability: "repos.byOwner",
549
+ listing: true
550
+ },
551
+ {
552
+ capability: "repos.labels",
553
+ listing: true
554
+ },
555
+ {
556
+ capability: "repos.createLabel",
557
+ write: true
558
+ },
559
+ {
560
+ capability: "repos.milestones",
561
+ listing: true
562
+ },
563
+ { capability: "repos.issueTypes" },
564
+ {
565
+ capability: "repos.collaborators",
566
+ listing: true
567
+ },
568
+ {
569
+ capability: "repos.contributors",
570
+ listing: true
571
+ },
572
+ { capability: "repos.contributorStats" },
573
+ { capability: "repos.templates" },
574
+ { capability: "repos.permissionFor" },
575
+ { capability: "repos.branchRules" },
576
+ {
577
+ capability: "repos.addCollaborator",
578
+ write: true
579
+ },
580
+ {
581
+ capability: "repos.assignableUsers",
582
+ listing: true
583
+ },
584
+ {
585
+ capability: "repos.reviewerCandidates",
586
+ listing: true
587
+ },
588
+ {
589
+ capability: "repos.events",
590
+ listing: true
591
+ },
592
+ {
593
+ capability: "orgs.teams",
594
+ listing: true
595
+ },
596
+ {
597
+ capability: "orgs.teamMembers",
598
+ listing: true,
599
+ account: true
600
+ },
601
+ {
602
+ capability: "orgs.block",
603
+ write: true,
604
+ spec: "orgs.blocking",
605
+ verbs: ["orgs.block", "orgs.unblock"]
606
+ },
607
+ {
608
+ capability: "threads.get",
609
+ perKind: true
610
+ },
611
+ {
612
+ capability: "threads.list",
613
+ listing: true,
614
+ perKind: true
615
+ },
616
+ { capability: "threads.getMany" },
617
+ {
618
+ capability: "threads.closingIssues",
619
+ listing: true
620
+ },
621
+ {
622
+ capability: "threads.closingPullRequests",
623
+ listing: true
624
+ },
625
+ {
626
+ capability: "threads.events",
627
+ listing: true,
628
+ spec: "threads.eventsPage",
629
+ derived: "threadEvents"
630
+ },
631
+ {
632
+ capability: "threads.comments",
633
+ listing: true,
634
+ perKind: true
635
+ },
636
+ {
637
+ capability: "threads.getComment",
638
+ spec: "threads.getComment",
639
+ derived: "getComment",
640
+ perKind: true
641
+ },
642
+ {
643
+ capability: "threads.createComment",
644
+ write: true,
645
+ perKind: true
646
+ },
647
+ {
648
+ capability: "threads.updateComment",
649
+ write: true,
650
+ perKind: true
651
+ },
652
+ {
653
+ capability: "threads.deleteComment",
654
+ write: true,
655
+ perKind: true
656
+ },
657
+ {
658
+ capability: "threads.hideComment",
659
+ write: true,
660
+ spec: "threads.hiding",
661
+ perKind: true,
662
+ verbs: ["threads.hideComment", "threads.unhideComment"]
663
+ },
664
+ {
665
+ capability: "threads.reactions",
666
+ listing: true,
667
+ perKind: true
668
+ },
669
+ {
670
+ capability: "threads.react",
671
+ write: true,
672
+ spec: "threads.reactions",
673
+ perKind: true,
674
+ verbs: ["threads.react", "threads.unreact"]
675
+ },
676
+ {
677
+ capability: "threads.create",
678
+ write: true,
679
+ perKind: true
680
+ },
681
+ {
682
+ capability: "threads.update",
683
+ write: true,
684
+ perKind: true
685
+ },
686
+ {
687
+ capability: "threads.close",
688
+ write: true,
689
+ perKind: true
690
+ },
691
+ {
692
+ capability: "threads.reopen",
693
+ write: true,
694
+ perKind: true
695
+ },
696
+ {
697
+ capability: "threads.lock",
698
+ write: true,
699
+ spec: "threads.locking",
700
+ perKind: true,
701
+ verbs: ["threads.lock", "threads.unlock"]
702
+ },
703
+ {
704
+ capability: "threads.setLabels",
705
+ write: true,
706
+ perKind: true
707
+ },
708
+ {
709
+ capability: "threads.addLabels",
710
+ write: true,
711
+ perKind: true
712
+ },
713
+ {
714
+ capability: "threads.removeLabels",
715
+ write: true,
716
+ perKind: true
717
+ },
718
+ {
719
+ capability: "threads.setMilestone",
720
+ write: true,
721
+ perKind: true
722
+ },
723
+ {
724
+ capability: "threads.setIssueType",
725
+ write: true,
726
+ perKind: true
727
+ },
728
+ {
729
+ capability: "threads.setAssignees",
730
+ write: true,
731
+ perKind: true
732
+ },
733
+ {
734
+ capability: "threads.requestReview",
735
+ write: true,
736
+ perKind: true
737
+ },
738
+ {
739
+ capability: "threads.merge",
740
+ write: true
741
+ },
742
+ {
743
+ capability: "threads.updateBranch",
744
+ write: true
745
+ },
746
+ {
747
+ capability: "threads.transfer",
748
+ write: true
749
+ },
750
+ {
751
+ capability: "threads.markDuplicate",
752
+ write: true
753
+ },
754
+ {
755
+ capability: "threads.subscription",
756
+ account: true,
757
+ spec: "threads.subscriptions",
758
+ perKind: true
759
+ },
760
+ {
761
+ capability: "threads.subscribe",
762
+ write: true,
763
+ derived: "subscriptionSet",
764
+ verbs: ["threads.subscribe", "threads.unsubscribe"]
765
+ },
766
+ {
767
+ capability: "threads.checks",
768
+ perKind: true
769
+ },
770
+ {
771
+ capability: "threads.files",
772
+ listing: true
773
+ },
774
+ {
775
+ capability: "threads.commits",
776
+ listing: true
777
+ },
778
+ {
779
+ capability: "threads.reviews",
780
+ listing: true
781
+ },
782
+ {
783
+ capability: "threads.getReview",
784
+ spec: "threads.getReview",
785
+ derived: "getReview"
786
+ },
787
+ {
788
+ capability: "threads.createReview",
789
+ write: true
790
+ },
791
+ {
792
+ capability: "threads.submitReview",
793
+ write: true
794
+ },
795
+ {
796
+ capability: "threads.approve",
797
+ write: true,
798
+ spec: "threads.approve",
799
+ derived: "approve"
800
+ },
801
+ {
802
+ capability: "threads.replyToReviewComment",
803
+ write: true
804
+ },
805
+ {
806
+ capability: "threads.reviewThreads",
807
+ listing: true
808
+ },
809
+ {
810
+ capability: "threads.resolveReviewThread",
811
+ write: true,
812
+ spec: "threads.reviewThreads",
813
+ verbs: ["threads.resolveReviewThread", "threads.unresolveReviewThread"]
814
+ },
815
+ {
816
+ capability: "notifications.list",
817
+ account: true,
818
+ listing: true
819
+ },
820
+ {
821
+ capability: "notifications.markRead",
822
+ account: true,
823
+ write: true
824
+ },
825
+ {
826
+ capability: "notifications.markDone",
827
+ account: true,
828
+ write: true
829
+ },
830
+ {
831
+ capability: "notifications.unsubscribe",
832
+ account: true,
833
+ write: true
834
+ },
835
+ {
836
+ capability: "notifications.markAllRead",
837
+ account: true,
838
+ write: true
839
+ },
840
+ {
841
+ capability: "notifications.markAllDone",
842
+ account: true,
843
+ write: true
844
+ },
845
+ {
846
+ capability: "notifications.unreadCount",
847
+ account: true
848
+ },
849
+ {
850
+ capability: "installations.list",
851
+ account: true,
852
+ spec: "installations",
853
+ verbs: [
854
+ "installations.list",
855
+ "installations.get",
856
+ "installations.token",
857
+ "installations.repos",
858
+ "installations.provider",
859
+ "installations.providers"
860
+ ],
861
+ listings: ["installations.list", "installations.repos"]
862
+ },
863
+ { capability: "checks.list" },
864
+ { capability: "checks.get" },
865
+ {
866
+ capability: "checks.report",
867
+ write: true
868
+ },
869
+ {
870
+ capability: "checks.rerun",
871
+ write: true
872
+ },
873
+ {
874
+ capability: "ci.runs",
875
+ listing: true
876
+ },
877
+ { capability: "ci.getRun" },
878
+ {
879
+ capability: "ci.jobs",
880
+ listing: true
881
+ },
882
+ {
883
+ capability: "ci.getJob",
884
+ spec: "ci.getJob",
885
+ derived: "ciJob"
886
+ },
887
+ { capability: "ci.log" },
888
+ {
889
+ capability: "ci.rerunFailed",
890
+ write: true
891
+ },
892
+ { capability: "contents.getFile" },
893
+ {
894
+ capability: "contents.tree",
895
+ listing: true
896
+ },
897
+ {
898
+ capability: "contents.branches",
899
+ listing: true
900
+ },
901
+ {
902
+ capability: "contents.tags",
903
+ listing: true
904
+ },
905
+ { capability: "contents.resolveRef" },
906
+ { capability: "contents.compare" },
907
+ {
908
+ capability: "contents.commitFiles",
909
+ write: true
910
+ },
911
+ {
912
+ capability: "commits.list",
913
+ listing: true
914
+ },
915
+ { capability: "commits.get" },
916
+ {
917
+ capability: "commits.comments",
918
+ listing: true
919
+ },
920
+ {
921
+ capability: "commits.getComment",
922
+ spec: "commits.getComment",
923
+ derived: "commitComment"
924
+ },
925
+ {
926
+ capability: "commits.createComment",
927
+ write: true
928
+ },
929
+ {
930
+ capability: "commits.updateComment",
931
+ write: true
932
+ },
933
+ {
934
+ capability: "commits.deleteComment",
935
+ write: true
936
+ },
937
+ {
938
+ capability: "commits.hideComment",
939
+ write: true,
940
+ spec: "commits.commentHiding",
941
+ verbs: ["commits.hideComment", "commits.unhideComment"]
942
+ },
943
+ {
944
+ capability: "releases.list",
945
+ listing: true
946
+ },
947
+ { capability: "releases.get" },
948
+ { capability: "releases.latest" },
949
+ { capability: "releases.getByTag" },
950
+ { capability: "releases.downloadAsset" },
951
+ {
952
+ capability: "releases.create",
953
+ write: true
954
+ },
955
+ {
956
+ capability: "releases.update",
957
+ write: true
958
+ },
959
+ {
960
+ capability: "webhooks.ingest",
961
+ derived: "webhook",
962
+ verbs: ["webhooks.verify", "webhooks.ingest"]
963
+ },
964
+ {
965
+ capability: "webhooks.list",
966
+ account: true,
967
+ listing: true
968
+ },
969
+ {
970
+ capability: "webhooks.create",
971
+ write: true
972
+ },
973
+ {
974
+ capability: "webhooks.update",
975
+ write: true
976
+ },
977
+ {
978
+ capability: "webhooks.delete",
979
+ write: true
980
+ },
981
+ {
982
+ capability: "webhooks.rotateSecret",
983
+ write: true
984
+ },
985
+ {
986
+ capability: "webhooks.deliveries",
987
+ account: true,
988
+ listing: true
989
+ },
990
+ {
991
+ capability: "webhooks.redeliver",
992
+ write: true
993
+ },
994
+ {
995
+ capability: "search.threads",
996
+ listing: true
997
+ },
998
+ {
999
+ capability: "search.repos",
1000
+ listing: true
1001
+ },
1002
+ {
1003
+ capability: "search.commits",
1004
+ listing: true
1005
+ },
1006
+ {
1007
+ capability: "search.code",
1008
+ listing: true
1009
+ },
1010
+ {
1011
+ capability: "securityAlerts.list",
1012
+ listing: true,
1013
+ derived: "alertKinds"
1014
+ },
1015
+ {
1016
+ capability: "eventKinds",
1017
+ derived: "eventKinds",
1018
+ verbs: []
1019
+ },
1020
+ {
1021
+ capability: "authKinds",
1022
+ derived: "authKinds",
1023
+ verbs: []
1024
+ },
1025
+ {
1026
+ capability: "limits",
1027
+ derived: "limits",
1028
+ verbs: []
1029
+ }
1030
+ ].map(({ listing, ...row }) => {
1031
+ const path = listing ? `${row.capability}Page` : row.capability;
1032
+ const spec = row.spec ?? (row.derived ? void 0 : path);
1033
+ return {
1034
+ ...row,
1035
+ ...spec ? { spec } : {},
1036
+ verbs: row.verbs ?? [row.capability],
1037
+ ...listing ? { listings: [row.capability] } : {}
1038
+ };
1039
+ });
1040
+ const ALERT_KINDS = [
1041
+ "dependency",
1042
+ "code_scanning",
1043
+ "secret",
1044
+ "advisory"
1045
+ ];
1046
+ const KINDS = [
1047
+ "issue",
1048
+ "pull_request",
1049
+ "discussion"
1050
+ ];
1051
+ const NOT_APPLICABLE_KINDS = {
1052
+ issue: "not_applicable",
1053
+ pull_request: "not_applicable",
1054
+ discussion: "not_applicable"
1055
+ };
1056
+ const NOT_APPLICABLE_ALERTS = {
1057
+ dependency: "not_applicable",
1058
+ code_scanning: "not_applicable",
1059
+ secret: "not_applicable",
1060
+ advisory: "not_applicable"
1061
+ };
1062
+ /**
1063
+ * The level `support` declares. Unless `declared` is set, `'experimental'` and
1064
+ * `'unverified'` resolve to `true`, as `capabilities` reports them.
1065
+ */
1066
+ function resolve(support, env, declared = false) {
1067
+ const level = typeof support === "function" ? support(env) : support ?? false;
1068
+ return declared || level !== "experimental" && level !== "unverified" ? level : true;
1069
+ }
1070
+ function resolveKinds(kinds, env, declared = false) {
1071
+ return Object.fromEntries(KINDS.map((kind) => [kind, resolve(kinds?.[kind], env, declared)]));
1072
+ }
1073
+ /** A capability composed of `parts` is `'not_applicable'` when any part is, else `false`, else `'unverified'`. */
1074
+ function composed(parts, level) {
1075
+ return parts.includes("not_applicable") ? "not_applicable" : parts.includes(false) ? false : parts.includes("unverified") ? "unverified" : level;
1076
+ }
1077
+ /** A thread's events are read for each kind the provider reads threads of, at the weaker of the two levels. */
1078
+ function threadEventKinds(spec, env, declared = false) {
1079
+ const events = resolve(spec.threads.eventsPage.support, env, declared);
1080
+ const threads = resolveKinds(spec.threads.get.kinds, env, declared);
1081
+ return Object.fromEntries(KINDS.map((kind) => [kind, composed([events, threads[kind]], events === true ? threads[kind] : events)]));
1082
+ }
1083
+ /** A single-item read the spec does not declare is emulated by walking its listing. */
1084
+ function readOrEmulated(read, listing, emulated, env, declared) {
1085
+ if (read !== false) return read;
1086
+ const level = emulated === void 0 ? "emulated" : resolve(emulated, env, declared);
1087
+ return composed([listing], level === true ? "emulated" : level);
1088
+ }
1089
+ /** `threads.getComment`, per kind: declared, or emulated from `threads.comments`. */
1090
+ function getCommentKinds(spec, env, declared = false) {
1091
+ const read = resolveKinds(spec.threads.getComment?.kinds, env, declared);
1092
+ const listing = resolveKinds(spec.threads.commentsPage.kinds, env, declared);
1093
+ return Object.fromEntries(KINDS.map((kind) => [kind, readOrEmulated(read[kind], listing[kind], spec.emulated?.getComment?.[kind], env, declared)]));
1094
+ }
1095
+ /** `threads.getReview`: declared, or emulated from `threads.reviews`. */
1096
+ function getReviewSupport(spec, env, declared = false) {
1097
+ return readOrEmulated(resolve(spec.threads.getReview?.support, env, declared), resolve(spec.threads.reviewsPage?.support, env, declared), spec.emulated?.getReview, env, declared);
1098
+ }
1099
+ /** `ci.getJob`: declared, or emulated from `ci.jobs` for a job ref that names its run. */
1100
+ function ciJobSupport(spec, env, declared = false) {
1101
+ return readOrEmulated(resolve(spec.ci?.getJob?.support, env, declared), resolve(spec.ci?.jobsPage?.support, env, declared), spec.emulated?.getJob, env, declared);
1102
+ }
1103
+ /** `commits.getComment`: declared, or emulated from `commits.commentsPage`. */
1104
+ function commitCommentSupport(spec, env, declared = false) {
1105
+ return readOrEmulated(resolve(spec.commits?.getComment?.support, env, declared), resolve(spec.commits?.commentsPage?.support, env, declared), spec.emulated?.getCommitComment, env, declared);
1106
+ }
1107
+ function read(source, path) {
1108
+ return path.split(".").reduce((value, key) => value?.[key], source);
1109
+ }
1110
+ function write(target, path, value) {
1111
+ const keys = path.split(".");
1112
+ const leaf = keys.pop();
1113
+ const parent = keys.reduce((node, key) => node[key] ??= {}, target);
1114
+ parent[leaf] = value;
1115
+ }
1116
+ function unsupported(declared) {
1117
+ return declared && {
1118
+ ...declared,
1119
+ support: declared.support === "not_applicable" ? "not_applicable" : false
1120
+ };
1121
+ }
1122
+ /** Keeps the kinds that are `'not_applicable'`, which no credential or mode changes. */
1123
+ function unsupportedKinds(declared) {
1124
+ return declared && {
1125
+ ...declared,
1126
+ kinds: Object.fromEntries(Object.entries(declared.kinds ?? {}).filter(([, value]) => value === "not_applicable"))
1127
+ };
1128
+ }
1129
+ /** What `entry` contributes to the capability object; `undefined` leaves the field to core. */
1130
+ function valueFor(entry, spec, env, flags, declared) {
1131
+ switch (entry.derived) {
1132
+ case "experimental": return;
1133
+ case "webhook": return flags.webhook || (spec.notApplicable?.includes("webhooks.ingest") ? "not_applicable" : false);
1134
+ case "threadEvents": return threadEventKinds(spec, env, declared);
1135
+ case "getComment": return getCommentKinds(spec, env, declared);
1136
+ case "getReview": return getReviewSupport(spec, env, declared);
1137
+ case "ciJob": return ciJobSupport(spec, env, declared);
1138
+ case "commitComment": return commitCommentSupport(spec, env, declared);
1139
+ case "subscriptionSet": return resolveKinds((flags.readOnly ? unsupportedKinds(spec.threads.subscriptions) : spec.threads.subscriptions)?.kinds, env, declared);
1140
+ case "approve": return resolve((spec.threads.approve ?? spec.threads.createReview)?.support, env, declared);
1141
+ case "alertKinds": return Object.fromEntries(ALERT_KINDS.map((kind) => [kind, resolve(spec.securityAlerts?.kinds[kind], env, declared)]));
1142
+ case "eventKinds": return spec.traits.eventKinds;
1143
+ case "authKinds": return spec.traits.authKinds;
1144
+ case "limits": return spec.traits.limits;
1145
+ }
1146
+ const verb = read(spec, entry.spec);
1147
+ return entry.perKind ? resolveKinds(verb?.kinds, env, declared) : resolve(verb?.support, env, declared);
1148
+ }
1149
+ /**
1150
+ * The capability object a spec declares, derived from {@link CAPABILITY_TABLE} with every support resolved against `env`.
1151
+ * With `declared`, it keeps the `'experimental'` and `'unverified'` levels that `capabilities` reports as `true`.
1152
+ */
1153
+ function capabilitiesOf(spec, env, flags, declared = false) {
1154
+ const resolved = applyNotApplicable(spec);
1155
+ const capabilities = {
1156
+ version: env.version,
1157
+ ...flags.experimental ? { experimental: true } : {}
1158
+ };
1159
+ for (const entry of CAPABILITY_TABLE) {
1160
+ const value = valueFor(entry, resolved, env, flags, declared);
1161
+ if (value === void 0) continue;
1162
+ for (const key of entry.verbs?.length ? entry.verbs : [entry.capability]) write(capabilities, key, value);
1163
+ }
1164
+ return capabilities;
1165
+ }
1166
+ const DECLARED = Symbol.for("forges.declaredCapabilities");
1167
+ /** Records how to read the declared levels of `provider`, for {@link declaredCapabilities}. */
1168
+ function trackDeclared(provider, read) {
1169
+ return Object.defineProperty(provider, DECLARED, { value: read });
1170
+ }
1171
+ /** Verbs `readOnly` blocks, by their {@link ForgeVerb} name. */
1172
+ const WRITE_VERBS = new Set(CAPABILITY_TABLE.flatMap((entry) => entry.write ? entry.verbs ?? [] : []));
1173
+ function update(target, path, change, create = false) {
1174
+ const [key, ...rest] = path.split(".");
1175
+ const node = target;
1176
+ if (!key) return change(target);
1177
+ if (!create && node?.[key] === void 0) return target;
1178
+ return {
1179
+ ...node,
1180
+ [key]: update(node?.[key], rest.join("."), change, create)
1181
+ };
1182
+ }
1183
+ const notApplicable = (declared) => ({
1184
+ ...declared,
1185
+ support: "not_applicable"
1186
+ });
1187
+ const notApplicableKinds = (declared) => ({
1188
+ ...declared,
1189
+ kinds: NOT_APPLICABLE_KINDS
1190
+ });
1191
+ /** Fills `spec` with `'not_applicable'` entries before anything resolves it, so derived capabilities inherit the level from their parts. */
1192
+ function applyNotApplicable(spec) {
1193
+ if (!spec.notApplicable?.length) return spec;
1194
+ const absent = new Set(spec.notApplicable);
1195
+ let updated = spec;
1196
+ for (const entry of CAPABILITY_TABLE) if (entry.spec && absent.has(entry.capability)) updated = update(updated, entry.spec, entry.perKind ? notApplicableKinds : notApplicable, true);
1197
+ if (absent.has("securityAlerts.list")) updated = update(updated, "securityAlerts", (declared) => ({
1198
+ ...declared,
1199
+ kinds: NOT_APPLICABLE_ALERTS
1200
+ }), true);
1201
+ return updated;
1202
+ }
1203
+ /**
1204
+ * Marks writes unsupported, with `anonymous` everything that needs an account,
1205
+ * and with `webhooksOnly` every declared verb, leaving only webhook ingestion.
1206
+ */
1207
+ function restrict(spec, anonymous, webhooksOnly = false) {
1208
+ let restricted = applyNotApplicable(spec);
1209
+ for (const entry of CAPABILITY_TABLE) if (entry.spec && (entry.write || anonymous && (entry.account || webhooksOnly))) restricted = update(restricted, entry.spec, entry.perKind ? unsupportedKinds : unsupported);
1210
+ const result = restricted;
1211
+ return anonymous && webhooksOnly ? update(result, "securityAlerts", unsupportedKinds) : result;
1212
+ }
1213
+ /**
1214
+ * Marks every declared verb unsupported except the capabilities in `keep` and
1215
+ * anything under them, for a credential that reaches only part of the API.
1216
+ * @param spec The spec that `setup()` declares.
1217
+ * @param keep Capability paths, such as `installations`, that stay as declared.
1218
+ * @example
1219
+ * ```ts
1220
+ * return appItself ? supportOnly(spec, ['installations']) : spec
1221
+ * ```
1222
+ */
1223
+ function supportOnly(spec, keep) {
1224
+ const kept = (capability) => keep.some((path) => capability === path || capability.startsWith(`${path}.`));
1225
+ let restricted = applyNotApplicable(spec);
1226
+ for (const entry of CAPABILITY_TABLE) if (entry.spec && !kept(entry.capability)) restricted = update(restricted, entry.spec, entry.perKind ? unsupportedKinds : unsupported);
1227
+ return kept("securityAlerts") ? restricted : update(restricted, "securityAlerts", unsupportedKinds);
1228
+ }
1229
+ const ACTIONS = {
1230
+ open: "opened",
1231
+ opened: "opened",
1232
+ close: "closed",
1233
+ closed: "closed",
1234
+ reopen: "reopened",
1235
+ reopened: "reopened",
1236
+ merge: "merged",
1237
+ merged: "merged",
1238
+ edit: "edited",
1239
+ edited: "edited",
1240
+ update: "edited",
1241
+ updated: "edited",
1242
+ create: "created",
1243
+ created: "created",
1244
+ delete: "deleted",
1245
+ deleted: "deleted",
1246
+ submitted: "submitted",
1247
+ labeled: "labelled",
1248
+ labelled: "labelled",
1249
+ label_added: "labelled",
1250
+ unlabeled: "unlabelled",
1251
+ unlabelled: "unlabelled",
1252
+ label_removed: "unlabelled",
1253
+ label_updated: "edited",
1254
+ label_cleared: "unlabelled",
1255
+ assigned: "assigned",
1256
+ unassigned: "unassigned",
1257
+ review_requested: "review_requested",
1258
+ synchronize: "synchronised",
1259
+ synchronized: "synchronised",
1260
+ synchronised: "synchronised",
1261
+ ready_for_review: "ready_for_review",
1262
+ converted_to_draft: "converted_to_draft",
1263
+ convert_to_draft: "converted_to_draft",
1264
+ publish: "published",
1265
+ published: "published",
1266
+ renamed: "renamed",
1267
+ transferred: "transferred",
1268
+ archived: "archived",
1269
+ unarchived: "unarchived",
1270
+ added: "added",
1271
+ removed: "removed",
1272
+ typed: "typed",
1273
+ untyped: "untyped"
1274
+ };
1275
+ /** What a comment or review event means when the forge names no verb. */
1276
+ const KIND_DEFAULTS = {
1277
+ comment: "created",
1278
+ review_comment: "created",
1279
+ review: "submitted"
1280
+ };
1281
+ /** Normalises a forge-native verb (`closed`, `close`, `synchronize`, ...) into an {@link EventAction}. */
1282
+ function eventAction(raw) {
1283
+ return raw ? ACTIONS[raw.toLowerCase()] : void 0;
1284
+ }
1285
+ /**
1286
+ * Fills `action` from `actionRaw`, or from the last `.`/`:` segment of
1287
+ * `kindRaw`, falling back to the kind's default verb, then `other`.
1288
+ */
1289
+ function completeEvent(event) {
1290
+ if (event.action) return event;
1291
+ const raw = event.actionRaw ?? event.kindRaw?.split(/[.:]/).pop();
1292
+ return {
1293
+ ...event,
1294
+ action: eventAction(raw) ?? KIND_DEFAULTS[event.kind] ?? "other"
1295
+ };
1296
+ }
1297
+ const REVIEW_STATES = {
1298
+ approved: "approved",
1299
+ approve: "approved",
1300
+ changes_requested: "changes_requested",
1301
+ request_changes: "changes_requested",
1302
+ commented: "commented",
1303
+ comment: "commented",
1304
+ pending: "pending",
1305
+ dismissed: "dismissed"
1306
+ };
1307
+ /** Sets `occurredAt` to `time`, or to `fallback` with `undated` when the forge reported no time. */
1308
+ function eventTime(time, fallback = /* @__PURE__ */ new Date()) {
1309
+ return time ? { occurredAt: time } : {
1310
+ occurredAt: fallback,
1311
+ undated: true
1312
+ };
1313
+ }
1314
+ /** Normalises a forge-native review verdict (`APPROVED`, `changes_requested`, ...) into a {@link ReviewState}. */
1315
+ function reviewState(raw) {
1316
+ return raw && REVIEW_STATES[raw.toLowerCase()] || "unknown";
1317
+ }
1318
+ /** A {@link ThreadSnapshot} of the fields that are known, or `undefined` when none is. An `unknown` state is dropped. */
1319
+ function threadSnapshot(fields) {
1320
+ const known = Object.entries(fields).filter(([key, value]) => value !== void 0 && !(key === "state" && value === "unknown"));
1321
+ return known.length ? Object.fromEntries(known) : void 0;
1322
+ }
1323
+ /** The {@link ThreadSnapshot} of a thread normalised from the issue or pull request an event embeds. */
1324
+ function snapshotOfThread({ title, body, state, stateRaw, stateReason, isDraft, author, labels, issueType, url, branches, stats, mergedBy }) {
1325
+ return threadSnapshot({
1326
+ title,
1327
+ body,
1328
+ state,
1329
+ stateRaw,
1330
+ stateReason,
1331
+ isDraft,
1332
+ author,
1333
+ labels,
1334
+ issueType,
1335
+ url,
1336
+ branches,
1337
+ stats,
1338
+ mergedBy
1339
+ });
1340
+ }
1341
+ const VERBS = new Set(CAPABILITY_TABLE.flatMap((entry) => entry.verbs ?? []));
1342
+ /**
1343
+ * Whether `verb` is supported according to `capabilities`, for `kind` where
1344
+ * support differs by thread kind (or by alert kind for `securityAlerts`).
1345
+ * Without `kind`, a per-kind verb counts as supported when any kind is.
1346
+ * @param capabilities The capabilities of a provider, such as `provider.capabilities`.
1347
+ * @param verb The operation, named by its path on the provider, such as `threads.createComment`.
1348
+ * @param kind The thread or alert kind, for an operation whose support differs by kind.
1349
+ * @example
1350
+ * ```ts
1351
+ * if (can(provider.capabilities, 'threads.merge')) {
1352
+ * await provider.threads.merge(ref)
1353
+ * }
1354
+ * ```
1355
+ */
1356
+ function can(capabilities, verb, kind) {
1357
+ return !isUnsupported(support(capabilities, verb, kind));
1358
+ }
1359
+ /** Levels from strongest to weakest, as the capability matrix ranks them. */
1360
+ const LEVELS = [true, "emulated"];
1361
+ /**
1362
+ * How well `verb` is supported according to `capabilities`: `true`,
1363
+ * `'emulated'`, `'not_applicable'` or `false`, for `kind` where support differs
1364
+ * by thread kind (or by alert kind for `securityAlerts`). Without `kind`, a
1365
+ * per-kind verb reports its strongest available level, or `'not_applicable'`
1366
+ * when no kind is available and any kind is, else `false`.
1367
+ * @param capabilities The capabilities of a provider, such as `provider.capabilities`.
1368
+ * @param verb The operation, named by its path on the provider, such as `threads.createComment`.
1369
+ * @param kind The thread or alert kind, for an operation whose support differs by kind.
1370
+ */
1371
+ function support(capabilities, verb, kind) {
1372
+ const declared = capabilityOf(capabilities, verb);
1373
+ if (typeof declared !== "object") return declared;
1374
+ if (kind) return declared[kind] ?? false;
1375
+ const levels = Object.values(declared);
1376
+ return LEVELS.find((level) => levels.includes(level)) ?? (levels.includes("not_applicable") ? "not_applicable" : false);
1377
+ }
1378
+ /** The capability entry behind `verb`: one support level, or one per kind. */
1379
+ function capabilityOf(capabilities, verb) {
1380
+ if (!VERBS.has(verb)) throw new TypeError(`Unknown verb ${JSON.stringify(verb)}; verbs are named by their path on the provider, such as 'threads.createComment'`);
1381
+ return verb.split(".").reduce((value, key) => value[key], capabilities);
1382
+ }
1383
+ const THREAD_FILTERS = [
1384
+ "involves",
1385
+ "mentions",
1386
+ "milestone"
1387
+ ];
1388
+ /**
1389
+ * Declares a verb whose support does not depend on the thread kind.
1390
+ * @param support How well the verb is supported.
1391
+ * @param run The function that implements the verb.
1392
+ */
1393
+ function verb(support, run) {
1394
+ return {
1395
+ support,
1396
+ run
1397
+ };
1398
+ }
1399
+ /**
1400
+ * Declares a verb whose support depends on the thread kind.
1401
+ * @param kinds How well each thread kind is supported. Kinds that are left out are unsupported.
1402
+ * @param run The function that implements the verb.
1403
+ * @example
1404
+ * ```ts
1405
+ * const threads = {
1406
+ * get: perKind({ issue: true, pull_request: true }, getThread),
1407
+ * }
1408
+ * ```
1409
+ */
1410
+ function perKind(kinds, run) {
1411
+ return {
1412
+ kinds,
1413
+ run
1414
+ };
1415
+ }
1416
+ /** Iterables whose page takes only options, with no target before them. */
1417
+ const UNTARGETED = /* @__PURE__ */ new Set([
1418
+ "repos.list",
1419
+ "notifications.list",
1420
+ "installations.list",
1421
+ "search.threads",
1422
+ "search.repos",
1423
+ "search.commits",
1424
+ "search.code"
1425
+ ]);
1426
+ /** The thread kind a per-kind verb is called for, read from its arguments. */
1427
+ function kindOf(name, args) {
1428
+ const first = args[0];
1429
+ if (name === "create" || name === "list") return args[1]?.kind;
1430
+ return first?.thread?.kind ?? first?.kind;
1431
+ }
1432
+ async function* completeItems(items) {
1433
+ for await (const item of items) yield {
1434
+ ...item,
1435
+ event: completeEvent(item.event)
1436
+ };
1437
+ }
1438
+ function readPath(source, path) {
1439
+ return path.split(".").reduce((value, key) => value?.[key], source);
1440
+ }
1441
+ /** Most reads spent looking for a first item when a provider's filtering empties a page. */
1442
+ const MAX_EMPTY_READS = 10;
1443
+ /**
1444
+ * Providers that cannot filter on the forge's side drop items from each page
1445
+ * they read, so a page can come back empty with a `cursor`. Reads on until the
1446
+ * page has an item, the listing ends or `MAX_EMPTY_READS` reads are spent.
1447
+ */
1448
+ async function nonEmptyPage(read, start) {
1449
+ let page = await read(start);
1450
+ const warnings = page.warnings;
1451
+ for (let reads = 1; !page.items.length && page.cursor && !page.notModified && reads < MAX_EMPTY_READS; reads++) page = await read(page.cursor);
1452
+ if (!warnings?.length || page.warnings === warnings) return page;
1453
+ const later = (page.warnings ?? []).filter((warning) => !warnings.some((seen) => seen.code === warning.code && seen.message === warning.message));
1454
+ return {
1455
+ ...page,
1456
+ warnings: [...warnings, ...later]
1457
+ };
1458
+ }
1459
+ /** Resets this close together belong to one window, as a reset in seconds from now drifts between responses. */
1460
+ const RESET_TOLERANCE_MS = 1e3;
1461
+ /** Whether `next` was counted before `kept` though it arrived after it: from an older window, or with more requests left in the same one. */
1462
+ function countedBefore(next, kept) {
1463
+ if (!next.resetAt || !kept.resetAt) return false;
1464
+ const gap = next.resetAt.getTime() - kept.resetAt.getTime();
1465
+ if (Math.abs(gap) > RESET_TOLERANCE_MS) return gap < 0;
1466
+ return next.remaining !== void 0 && kept.remaining !== void 0 && next.remaining > kept.remaining;
1467
+ }
1468
+ function createProvider(definition, givenOptions, givenState) {
1469
+ const givenAuth = givenOptions.auth;
1470
+ const anonymous = Boolean(definition.anonymous) && (!givenAuth || givenAuth.type === "anonymous");
1471
+ const options = anonymous && !givenAuth ? {
1472
+ ...givenOptions,
1473
+ auth: { type: "anonymous" }
1474
+ } : givenOptions;
1475
+ const { baseUrl, instance } = resolveInstance(definition, options);
1476
+ const origin = {
1477
+ forge: definition.forge,
1478
+ instance
1479
+ };
1480
+ const browser = "document" in globalThis || "WorkerGlobalScope" in globalThis;
1481
+ const userAgent = options.userAgent ?? (browser ? void 0 : "forges");
1482
+ const headers = {
1483
+ ...definition.headers,
1484
+ ...userAgent ? { "user-agent": userAgent } : {}
1485
+ };
1486
+ const prepared = {
1487
+ options,
1488
+ forge: definition.forge,
1489
+ instance,
1490
+ baseUrl,
1491
+ headers,
1492
+ origin,
1493
+ state: givenState
1494
+ };
1495
+ const state = definition.prepare ? definition.prepare(prepared) : givenState;
1496
+ const base = {
1497
+ ...prepared,
1498
+ state
1499
+ };
1500
+ const budgets = /* @__PURE__ */ new Map();
1501
+ const tracked = (event) => {
1502
+ const kept = budgets.get(event.rateLimit.resource);
1503
+ if (!kept || !countedBefore(event.rateLimit, kept)) budgets.set(event.rateLimit.resource, event.rateLimit);
1504
+ options.onRateLimit?.(event);
1505
+ };
1506
+ const authHeaders = anonymous ? void 0 : definition.authHeaders?.(base);
1507
+ const makeFetcher = (overrides) => createFetcher({
1508
+ fetch: options.fetch,
1509
+ timeout: options.timeout,
1510
+ onRetry: options.onRetry,
1511
+ onRateLimit: "authHeaders" in overrides || authHeaders ? options.onRateLimit : tracked,
1512
+ headers,
1513
+ query: definition.query,
1514
+ context: origin,
1515
+ ...overrides
1516
+ });
1517
+ const fetcher = makeFetcher({
1518
+ baseUrl,
1519
+ authHeaders,
1520
+ onRateLimit: tracked
1521
+ });
1522
+ const ctx = {
1523
+ ...base,
1524
+ fetcher,
1525
+ createFetcher: makeFetcher,
1526
+ derive: (derivedOptions, derivedState) => createProvider(definition, derivedOptions, derivedState ?? state)
1527
+ };
1528
+ const declaredSpec = applyNotApplicable(definition.setup(ctx));
1529
+ const handlers = definition.webhooks?.(ctx);
1530
+ const spec = anonymous || options.readOnly ? restrict(declaredSpec, anonymous, definition.anonymous === "webhooks") : declaredSpec;
1531
+ const authKind = anonymous ? "anonymous" : givenAuth?.type ?? spec.traits.authKinds[0] ?? "anonymous";
1532
+ const env = { version: options.instanceVersion };
1533
+ const probeVersion = spec.probeVersion && memo(spec.probeVersion);
1534
+ const flags = {
1535
+ experimental: Boolean(definition.experimental),
1536
+ readOnly: Boolean(options.readOnly),
1537
+ webhook: Boolean(handlers)
1538
+ };
1539
+ let capabilities = capabilitiesOf(spec, env, flags);
1540
+ const unsupported = (verb, support, kind) => options.readOnly && WRITE_VERBS.has(verb) ? new ReadOnlyError(`${verb} is a write and this ${definition.forge} provider is read-only`, origin) : new UnsupportedOperationError(`${definition.forge} ${support === "not_applicable" ? "has no" : "does not support"} ${verb}${kind ? ` for a ${kind.replace("_", " ")}` : ""}`, origin);
1541
+ /** An iterable that rejects on first read, for listings the forge does not have. */
1542
+ const emptyIterable = (verb, support) => forgeIterable(async function* () {
1543
+ throw unsupported(verb, support);
1544
+ });
1545
+ /** Support is resolved at call time, so a version gate is honoured once the version is known. */
1546
+ function gate(verb, support, run) {
1547
+ return (...args) => {
1548
+ const level = resolve(support, env);
1549
+ return run && !isUnsupported(level) ? run(...args) : Promise.reject(unsupported(verb, level));
1550
+ };
1551
+ }
1552
+ /** A per-kind verb: rejects for kinds it does not support, or entirely when undeclared. */
1553
+ function kindGate(verb, kinds, run) {
1554
+ const name = verb.slice(verb.indexOf(".") + 1);
1555
+ return (...args) => {
1556
+ const kind = kindOf(name, args);
1557
+ const knownKind = kind && KINDS.includes(kind) ? kind : void 0;
1558
+ if (!run || options.readOnly && WRITE_VERBS.has(verb)) return Promise.reject(unsupported(verb, kinds && resolve(kinds[knownKind ?? "issue"], env)));
1559
+ if (knownKind) {
1560
+ const level = resolve(kinds?.[knownKind], env);
1561
+ if (isUnsupported(level)) return Promise.reject(unsupported(verb, level, knownKind));
1562
+ }
1563
+ return run(...args);
1564
+ };
1565
+ }
1566
+ const api = {};
1567
+ const set = (verb, value) => {
1568
+ const [group, name] = verb.split(".");
1569
+ (api[group] ??= {})[name] = value;
1570
+ };
1571
+ const call = (verb) => readPath(api, verb);
1572
+ const listing = (read, listOptions = {}) => Object.assign(iteratePages(read, listOptions), { page: () => read(listOptions) });
1573
+ const subscriptions = spec.threads.subscriptions;
1574
+ const createReview = spec.threads.createReview;
1575
+ const approve = spec.threads.approve ?? (createReview && {
1576
+ support: createReview.support,
1577
+ ...createReview.run ? { run: (ref, body, options) => createReview.run(ref, {
1578
+ event: "approve",
1579
+ body
1580
+ }, options) } : {}
1581
+ });
1582
+ const declaredStream = spec.sources?.stream;
1583
+ const alerts = spec.securityAlerts;
1584
+ const declaredInstallations = spec.installations;
1585
+ const installationsSupported = () => Boolean(declaredInstallations?.run && !isUnsupported(resolve(declaredInstallations.support, env)));
1586
+ const listThreads = kindGate("threads.list", spec.threads.listPage.kinds, spec.threads.listPage.run);
1587
+ const listOwnerRepos = gate("repos.byOwner", spec.repos.byOwnerPage?.support, spec.repos.byOwnerPage?.run);
1588
+ const listReviewThreads = gate("threads.reviewThreads", spec.threads.reviewThreadsPage?.support, spec.threads.reviewThreadsPage?.run);
1589
+ const listComments = kindGate("threads.comments", spec.threads.commentsPage.kinds, spec.threads.commentsPage.run);
1590
+ const listEvents = kindGate("threads.events", Object.fromEntries(KINDS.map((kind) => [kind, (kindEnv) => threadEventKinds(spec, kindEnv)[kind]])), spec.threads.eventsPage.run);
1591
+ const native = spec.search?.queryRaw;
1592
+ const search = (name) => {
1593
+ const run = gate(`search.${name.slice(0, -4)}`, spec.search?.[name]?.support, spec.search?.[name]?.run);
1594
+ return async ({ queryRaw, ...query } = {}) => {
1595
+ const page = await run(native ? {
1596
+ queryRaw,
1597
+ ...query
1598
+ } : query);
1599
+ return !queryRaw || native || !isFirstPage(query.cursor) ? page : {
1600
+ ...page,
1601
+ warnings: [{
1602
+ code: "filter_unsupported",
1603
+ message: "This search has no query syntax; queryRaw was ignored"
1604
+ }, ...page.warnings ?? []]
1605
+ };
1606
+ };
1607
+ };
1608
+ const feed = (verb) => {
1609
+ const declared = readPath(spec, verb);
1610
+ const run = gate(verb.slice(0, -4), declared?.support, declared?.run);
1611
+ return async (target, pageOptions) => {
1612
+ const page = await run(target, pageOptions);
1613
+ return {
1614
+ ...page,
1615
+ items: page.items.map(completeEvent)
1616
+ };
1617
+ };
1618
+ };
1619
+ const special = {
1620
+ "repos.eventsPage": feed("repos.eventsPage"),
1621
+ "users.eventsPage": feed("users.eventsPage"),
1622
+ "search.threadsPage": search("threadsPage"),
1623
+ "search.reposPage": search("reposPage"),
1624
+ "search.commitsPage": search("commitsPage"),
1625
+ "search.codePage": search("codePage"),
1626
+ "threads.listPage": async (repo, given = {}) => {
1627
+ if (given.state === "merged" && given.kind && given.kind !== "pull_request") return { items: [] };
1628
+ const query = { ...given };
1629
+ const ignored = THREAD_FILTERS.filter((filter) => query[filter] !== void 0 && !spec.threads.listFilters?.includes(filter));
1630
+ for (const filter of ignored) delete query[filter];
1631
+ const run = (cursor) => listThreads(repo, {
1632
+ ...query,
1633
+ ...query.state === "merged" ? { kind: "pull_request" } : {},
1634
+ cursor
1635
+ });
1636
+ const page = await nonEmptyPage(run, query.cursor);
1637
+ if (!ignored.length || !isFirstPage(query.cursor)) return page;
1638
+ const warnings = ignored.map((filter) => ({
1639
+ code: "filter_unsupported",
1640
+ message: `This listing has no ${filter} filter; it was ignored`
1641
+ }));
1642
+ return {
1643
+ ...page,
1644
+ warnings: [...warnings, ...page.warnings ?? []]
1645
+ };
1646
+ },
1647
+ "repos.byOwnerPage": (owner, query = {}) => nonEmptyPage(async (cursor) => {
1648
+ const page = await listOwnerRepos(owner, {
1649
+ ...query,
1650
+ cursor
1651
+ });
1652
+ return !query.visibility || query.visibility === "all" ? page : {
1653
+ ...page,
1654
+ items: page.items.filter((repo) => repo.visibility === query.visibility)
1655
+ };
1656
+ }, query.cursor),
1657
+ "threads.eventsPage": async (ref, listOptions) => {
1658
+ const page = await listEvents(ref, listOptions);
1659
+ return {
1660
+ ...page,
1661
+ items: page.items.map(completeEvent)
1662
+ };
1663
+ },
1664
+ "threads.commentsPage": (ref, listOptions = {}) => {
1665
+ const since = listOptions.since;
1666
+ if (!since) return listComments(ref, listOptions);
1667
+ return nonEmptyPage(async (cursor) => {
1668
+ const page = await listComments(ref, {
1669
+ ...listOptions,
1670
+ cursor
1671
+ });
1672
+ return {
1673
+ ...page,
1674
+ items: page.items.filter((comment) => (comment.updatedAt ?? comment.createdAt ?? since) >= since)
1675
+ };
1676
+ }, listOptions.cursor);
1677
+ },
1678
+ "threads.reviewThreadsPage": (ref, { state, ...listOptions } = {}) => nonEmptyPage(async (cursor) => {
1679
+ const page = await listReviewThreads(ref, {
1680
+ ...listOptions,
1681
+ cursor
1682
+ });
1683
+ return !state || state === "all" ? page : {
1684
+ ...page,
1685
+ items: page.items.filter((thread) => thread.resolved === (state === "resolved"))
1686
+ };
1687
+ }, listOptions.cursor),
1688
+ "threads.getComment": kindGate("threads.getComment", Object.fromEntries(KINDS.map((kind) => [kind, (kindEnv) => getCommentKinds(spec, kindEnv)[kind]])), (ref, options) => !isUnsupported(resolve(spec.threads.getComment?.kinds[ref.thread.kind], env)) ? spec.threads.getComment.run(ref, options) : listed(call("threads.comments")(ref.thread, options), ref.id, "Comment")),
1689
+ "threads.getReview": gate("threads.getReview", (reviewEnv) => getReviewSupport(spec, reviewEnv), (ref, options) => !isUnsupported(resolve(spec.threads.getReview?.support, env)) ? spec.threads.getReview.run(ref, options) : listed(call("threads.reviews")(ref.thread, options), ref.id, "Review")),
1690
+ "ci.getJob": gate("ci.getJob", (jobEnv) => ciJobSupport(spec, jobEnv), (ref, options) => {
1691
+ if (!isUnsupported(resolve(spec.ci?.getJob?.support, env))) return spec.ci.getJob.run(ref, options);
1692
+ if (!ref.run) return Promise.reject(new UnsupportedOperationError(`${definition.forge} reads a CI job from its run's jobs, and this ref names no run`, origin));
1693
+ return listed(call("ci.jobs")(ref.run, options), ref.id, "CI job");
1694
+ }),
1695
+ "commits.getComment": gate("commits.getComment", (commentEnv) => commitCommentSupport(spec, commentEnv), (ref, options) => !isUnsupported(resolve(spec.commits?.getComment?.support, env)) ? spec.commits.getComment.run(ref, options) : listed(call("commits.comments")(ref.commit, options), ref.id, "Comment")),
1696
+ "threads.subscribe": kindGate("threads.subscribe", subscriptions?.kinds, subscriptions?.run?.subscribe),
1697
+ "threads.unsubscribe": kindGate("threads.unsubscribe", subscriptions?.kinds, subscriptions?.run?.unsubscribe),
1698
+ "threads.approve": gate("threads.approve", approve?.support, approve?.run),
1699
+ "releases.downloadAsset": async (ref, options) => {
1700
+ const stream = await gate("releases.downloadAsset", spec.releases?.downloadAsset?.support, spec.releases?.downloadAsset?.run)(ref, options);
1701
+ if (!options?.as || options.as === "stream") return stream;
1702
+ const bytes = new Uint8Array(await new Response(stream).arrayBuffer());
1703
+ return options.as === "text" ? decodeText(bytes, `Release asset ${ref.id}`, origin) : bytes;
1704
+ },
1705
+ "contents.compare": async (repo, base, head, compareOptions = {}) => {
1706
+ const comparison = await gate("contents.compare", spec.contents?.compare?.support, spec.contents?.compare?.run)(repo, base, head, compareOptions);
1707
+ const { commitLimit, files } = compareOptions;
1708
+ if (commitLimit === void 0 && files !== false) return comparison;
1709
+ const commits = commitLimit === void 0 ? comparison.commits : comparison.commits.slice(0, Math.max(0, commitLimit));
1710
+ return {
1711
+ ...comparison,
1712
+ commits: files === false ? commits.map(({ files: _files, ...commit }) => commit) : commits,
1713
+ ...files === false ? { files: [] } : {}
1714
+ };
1715
+ },
1716
+ "contents.resolveRef": (repo, ref, options) => isSha(ref) ? Promise.resolve(ref.toLowerCase()) : gate("contents.resolveRef", spec.contents?.resolveRef?.support, spec.contents?.resolveRef?.run)(repo, ref, options),
1717
+ "contents.commitFiles": async (repo, input, options) => {
1718
+ const declared = spec.contents?.commitFiles;
1719
+ const level = resolve(declared?.support, env);
1720
+ if (!declared?.run || isUnsupported(level)) throw unsupported("contents.commitFiles", level);
1721
+ const changes = input.changes.map((change) => ({
1722
+ ...change,
1723
+ path: change.path.replace(/^\/+/, "")
1724
+ }));
1725
+ const paths = new Set(changes.map((change) => change.path));
1726
+ if (!changes.length || paths.size < changes.length) throw new TypeError("`changes` must name at least one file, and each file once");
1727
+ const invalid = changes.find((change) => change.path.split("/").some((segment) => segment === "" || segment === "." || segment === ".."));
1728
+ if (invalid) throw new TypeError(`\`${invalid.path}\` is not a path to a file: it has an empty, \`.\` or \`..\` segment`);
1729
+ if (!input.branch || !input.message.trim()) throw new TypeError("`branch` and `message` cannot be empty");
1730
+ if (input.expectedHead !== void 0 && !isSha(input.expectedHead)) throw new TypeError("`expectedHead` must be a full commit sha");
1731
+ if (input.expectedHead !== void 0 && input.createFrom !== void 0) throw new TypeError("`expectedHead` and `createFrom` cannot be combined: a branch created from `createFrom` has no head yet");
1732
+ return declared.run(repo, {
1733
+ ...input,
1734
+ changes
1735
+ }, options);
1736
+ },
1737
+ "webhooks.verify": handlers ? handlers.verify : () => Promise.reject(unsupported("webhooks.verify", capabilities.webhooks.ingest)),
1738
+ "webhooks.ingest": async (delivery) => {
1739
+ if (!handlers) throw unsupported("webhooks.ingest", capabilities.webhooks.ingest);
1740
+ if (!await handlers.verify(delivery)) throw new WebhookVerificationError("Webhook signature verification failed", origin);
1741
+ return (await handlers.translate(delivery)).map(completeEvent);
1742
+ },
1743
+ "sources.stream": (streamOptions) => declaredStream?.run && !isUnsupported(resolve(declaredStream.support, env)) ? completeItems(declaredStream.run(streamOptions)) : emptyIterable("sources.stream", resolve(declaredStream?.support, env)),
1744
+ "securityAlerts.listPage": (repo, listOptions = {}) => {
1745
+ if (!(alerts?.listPage && (listOptions.kind ? !isUnsupported(resolve(alerts.kinds[listOptions.kind], env)) : ALERT_KINDS.some((kind) => !isUnsupported(resolve(alerts.kinds[kind], env)))))) {
1746
+ const level = listOptions.kind ? resolve(alerts?.kinds[listOptions.kind], env) : ALERT_KINDS.every((kind) => resolve(alerts?.kinds[kind], env) === "not_applicable") ? "not_applicable" : false;
1747
+ return Promise.reject(listOptions.kind ? new UnsupportedOperationError(`${definition.forge} ${level === "not_applicable" ? "has no" : "cannot list"} ${listOptions.kind.replace("_", " ")} alerts`, origin) : unsupported("securityAlerts.list", level));
1748
+ }
1749
+ return alerts.listPage(repo, listOptions);
1750
+ },
1751
+ "installations.provider": (installation) => {
1752
+ if (!installationsSupported()) throw unsupported("installations.provider", resolve(declaredInstallations?.support, env));
1753
+ return declaredInstallations.run.provider(installation);
1754
+ },
1755
+ "installations.providers": () => installationsSupported() ? declaredInstallations.run.providers() : emptyIterable("installations.providers", resolve(declaredInstallations?.support, env))
1756
+ };
1757
+ for (const entry of CAPABILITY_TABLE) {
1758
+ const declared = entry.spec ? readPath(spec, entry.spec) : void 0;
1759
+ for (const verb of entry.verbs ?? []) if (verb in special) set(verb, special[verb]);
1760
+ else if (entry.listings?.includes(verb)) {
1761
+ const pageVerb = `${verb}Page`;
1762
+ const run = typeof declared?.run === "function" ? declared.run : declared?.run?.[pageVerb.slice(pageVerb.indexOf(".") + 1)];
1763
+ const page = special[pageVerb] ?? (entry.perKind ? kindGate(verb, declared?.kinds, run) : gate(verb, declared?.support, run));
1764
+ const untargeted = UNTARGETED.has(verb);
1765
+ set(verb, (...args) => listing((options) => page(...untargeted ? [] : [args[0]], options), (untargeted ? args[0] : args[1]) ?? {}));
1766
+ } else {
1767
+ const run = typeof declared?.run === "function" ? declared.run : declared?.run?.[verb.slice(verb.indexOf(".") + 1)];
1768
+ set(verb, entry.perKind ? kindGate(verb, declared?.kinds, run) : gate(verb, declared?.support, run));
1769
+ }
1770
+ }
1771
+ api.webhooks.events = handlers?.events ?? [];
1772
+ async function listed(items, id, what) {
1773
+ for await (const item of items) if (item.ref.id === id) return item;
1774
+ throw new NotFoundError(`${what} ${id} not found`, 404, "", origin);
1775
+ }
1776
+ return trackDeclared({
1777
+ ...declaredSpec.extensions,
1778
+ ...api,
1779
+ forge: definition.forge,
1780
+ instance,
1781
+ baseUrl,
1782
+ authKind,
1783
+ request: createRequest(spec.request ?? fetcher, options.readOnly ? { readOnly: (method, path) => new ReadOnlyError(`${method} ${path} is a write and this ${definition.forge} provider is read-only; pass \`mutates: false\` if it only reads`, origin) } : {}),
1784
+ get capabilities() {
1785
+ return capabilities;
1786
+ },
1787
+ rateLimits: spec.rateLimits ?? (() => {
1788
+ const now = Date.now();
1789
+ for (const [resource, budget] of budgets) if (budget.resetAt && budget.resetAt.getTime() <= now) budgets.delete(resource);
1790
+ return [...budgets.values()].map((budget) => ({ ...budget }));
1791
+ }),
1792
+ async refreshCapabilities() {
1793
+ if (!options.instanceVersion && probeVersion) {
1794
+ env.version = await probeVersion();
1795
+ capabilities = capabilitiesOf(spec, env, flags);
1796
+ }
1797
+ return capabilities;
1798
+ },
1799
+ normaliseMarkdown: spec.normaliseMarkdown ?? ((body) => body),
1800
+ scopesFor: (verb) => spec.scopes?.(verb) ?? {},
1801
+ can: (verb, kind) => can(capabilities, verb, kind),
1802
+ support: (verb, kind) => support(capabilities, verb, kind),
1803
+ urlFor: ((target) => spec.web ? webUrlFor(spec.web, target) : void 0),
1804
+ webOrigin: spec.web ? new URL(spec.web.baseUrl).origin : void 0,
1805
+ parseUrl: (url) => spec.web ? parseWebUrl(spec.web, url, origin) : void 0,
1806
+ referenceFor: (ref, referenceOptions) => referenceFor(spec.web, ref, referenceOptions),
1807
+ parseReferences: (text, { from }) => parseReferences(spec.web, text, from, origin)
1808
+ }, () => capabilitiesOf(spec, env, flags, true));
1809
+ }
1810
+ /**
1811
+ * Defines a forge provider. Returns the function end users call to create
1812
+ * one, for example `github({ auth })`. Nothing touches the network until a
1813
+ * method of the provider is called.
1814
+ * @param definition The defaults, authentication and setup of the forge.
1815
+ */
1816
+ function defineForgeProvider(definition) {
1817
+ return ((options = {}) => createProvider(definition, options));
1818
+ }
1819
+ //#endregion
1820
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/webhooks-Bc6QhmI8.mjs
1821
+ /** The first of `names` the delivery carries a non-empty value for. */
1822
+ function firstHeader(delivery, names) {
1823
+ for (const name of typeof names === "string" ? [names] : names) {
1824
+ const value = headerValue(delivery.headers, name);
1825
+ if (value) return value;
1826
+ }
1827
+ }
1828
+ /**
1829
+ * Checks a hex HMAC-SHA256 of the raw body, sent in the first of `header`
1830
+ * present, after an optional `prefix` such as `sha256=`. The delivery's own
1831
+ * `secret` takes precedence over the provider's.
1832
+ */
1833
+ async function verifyHmacSignature(delivery, secret, { header, prefix = "" }) {
1834
+ const signature = firstHeader(delivery, header);
1835
+ const key = delivery.secret ?? secret;
1836
+ if (!key || !signature) return false;
1837
+ return timingSafeEqual(signature.toLowerCase(), `${prefix}${await hmacSha256Hex(key, delivery.body)}`);
1838
+ }
1839
+ /** Checks a secret sent verbatim in `header`. */
1840
+ function verifySharedToken(delivery, secret, header) {
1841
+ const token = headerValue(delivery.headers, header);
1842
+ const key = delivery.secret ?? secret;
1843
+ return Boolean(key && token && timingSafeEqual(token, key));
1844
+ }
1845
+ /**
1846
+ * The kind, detail and summary of one ref update in a push: a deletion, a creation, or new commits. Without
1847
+ * `commits` or `commitCount`, the detail has no `commitCount`.
1848
+ */
1849
+ function refEvent(who, change) {
1850
+ const name = change.ref.replace(/^refs\/(?:heads|tags)\//, "");
1851
+ const refType = change.refType ?? (change.ref.startsWith("refs/tags/") ? "tag" : "branch");
1852
+ if (change.deleted || change.created) return {
1853
+ kind: "ref",
1854
+ action: change.deleted ? "deleted" : "created",
1855
+ detail: {
1856
+ type: "ref",
1857
+ ref: change.ref,
1858
+ refType
1859
+ },
1860
+ summary: `${who} ${change.deleted ? "deleted" : "created"} ${name}`
1861
+ };
1862
+ const count = change.commitCount ?? change.commits?.length;
1863
+ return {
1864
+ kind: "push",
1865
+ detail: {
1866
+ type: "push",
1867
+ ref: change.ref,
1868
+ before: change.before,
1869
+ after: change.after,
1870
+ commitCount: count,
1871
+ forced: change.forced ?? false,
1872
+ commits: change.commits ?? []
1873
+ },
1874
+ summary: count === void 0 ? `${who} pushed to ${name}` : `${who} pushed ${count} commit(s) to ${name}`
1875
+ };
1876
+ }
1877
+ /** The forge's own event names for `events`, plus any `nativeEvents` passed through unchanged. */
1878
+ function nativeEventsFor(map, events, nativeEvents) {
1879
+ const names = new Set(nativeEvents ?? []);
1880
+ for (const kind of events ?? []) for (const name of map[kind] ?? []) names.add(name);
1881
+ return [...names];
1882
+ }
1883
+ /** The normalised kinds a subscription to `nativeEvents` covers. */
1884
+ function eventKindsOf(map, nativeEvents) {
1885
+ const kinds = /* @__PURE__ */ new Set();
1886
+ for (const [kind, names] of Object.entries(map)) if (nativeEvents.includes("*") || names.some((name) => nativeEvents.includes(name))) kinds.add(kind);
1887
+ return [...kinds];
1888
+ }
1889
+ //#endregion
1890
+ export { headerValue as A, verb as C, rangeOf as D, lineOf as E, webUrlFor as O, toFileContent as S, githubShapedWeb as T, reviewState as _, verifyHmacSignature as a, supportOnly as b, changeBase64 as c, eventTime as d, existingFiles as f, perKind as g, isSha as h, refEvent as i, signRs256Jwt as j, bodyText as k, defineForgeProvider as l, inDirectories as m, firstHeader as n, verifySharedToken as o, fromBase64 as p, nativeEventsFor as r, WRITE_VERBS as s, eventKindsOf as t, eventAction as u, snapshotOfThread as v, OWNER_NAME as w, threadSnapshot as x, splitMessage as y };