@vite-hub/forge 0.7.0 → 0.8.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 (25) hide show
  1. package/README.md +8 -2
  2. package/dist/{webhooks-Bc6QhmI8-CvF2iFBp.js → define-C9xZZNVR-C-oojQRP.js} +3 -997
  3. package/dist/{definition-BQFdu9ti-BURTyX81.js → definition-BQFdu9ti-BZgR-gkB.js} +5 -4
  4. package/dist/{github-Csy_qzZc.js → definition-s83gxg2p-JwDgFji9.js} +26 -28
  5. package/dist/{events-BL0zcgMf-DGySmhNt.js → events-BL0zcgMf-Exs7JLX1.js} +4 -2
  6. package/dist/{events-DDdJnmD2-BhNdO8U_.js → events-DDdJnmD2-CdPFePvp.js} +4 -3
  7. package/dist/{events-DHqSJ5KI-DfFbbwBb.js → events-DHqSJ5KI-mRtn-qQ0.js} +4 -3
  8. package/dist/{events-DXE-Ul2S-U2BH_jTW.js → events-DXE-Ul2S-BEUw4sQF.js} +4 -3
  9. package/dist/{feed-B1OiHFg0-a2dzl1Va.js → feed-B1OiHFg0-ppQHqkxG.js} +4 -2
  10. package/dist/{feed-DROLF1tb-A1eZev0R.js → feed-DROLF1tb-CMAanXw8.js} +4 -2
  11. package/dist/{feed-iWegqepj-id4yPYnY.js → feed-iWegqepj-DKBLqhvD.js} +4 -2
  12. package/dist/{forgejo-aZiaqKRW.js → forgejo-Deckk49p.js} +2 -2
  13. package/dist/{gitea-CCZ3fS7H.js → gitea-ChQKeRrf.js} +2 -2
  14. package/dist/{gitee-CKt4pEC0-dsy0hiLG.js → gitee-CKt4pEC0-BuzC1PrM.js} +1 -1
  15. package/dist/{gitlab-AAJN-eVR.js → gitlab-CzCikZzN.js} +5 -4
  16. package/dist/{graphql-DxRA9BGO-CiA7HWVp.js → graphql-DxRA9BGO-Cy511t8-.js} +2 -1
  17. package/dist/index.d.ts +50 -4
  18. package/dist/index.js +187 -20
  19. package/dist/kit-CrquHPqr.js +4 -0
  20. package/dist/{templates-0m5QBVIh-Bop0TOo9.js → templates-0m5QBVIh-C1DcQ_yo.js} +1 -2
  21. package/dist/utils-DEwhctg5-BM3AMnSs.js +1213 -0
  22. package/dist/webhooks-Bc6QhmI8-CgoCnwj1.js +71 -0
  23. package/package.json +2 -2
  24. package/dist/kit-UEdJKGws.js +0 -3
  25. package/dist/model-Biiu1CfI-CVLamGai.js +0 -288
@@ -0,0 +1,1213 @@
1
+ // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/errors-DBJbfvy-.mjs
2
+ /** Base class for every error that forges throws. */
3
+ var ForgeError = class extends Error {
4
+ name = "ForgeError";
5
+ /** The forge that the request went to. */
6
+ forge;
7
+ instance;
8
+ url;
9
+ method;
10
+ constructor(message, context = {}, options) {
11
+ super(message, options);
12
+ this.forge = context.forge;
13
+ this.instance = context.instance;
14
+ this.url = context.url;
15
+ this.method = context.method;
16
+ }
17
+ };
18
+ /** The forge responded with an error. */
19
+ var ForgeApiError = class extends ForgeError {
20
+ name = "ForgeApiError";
21
+ status;
22
+ /** Truncated response body, for diagnostics. */
23
+ body;
24
+ constructor(message, status, body, context, options) {
25
+ super(message, context, options);
26
+ this.status = status;
27
+ this.body = body;
28
+ }
29
+ };
30
+ /** A 404: the resource does not exist, or the credential cannot see it. Many forges respond the same way to both. */
31
+ var NotFoundError = class extends ForgeApiError {
32
+ name = "NotFoundError";
33
+ };
34
+ /**
35
+ * A 401, or a 403 with a request budget of zero (GitHub GraphQL), for a request
36
+ * sent without credentials. A rejected credential is {@link TokenRevokedError}.
37
+ */
38
+ var AuthenticationRequiredError = class extends ForgeApiError {
39
+ name = "AuthenticationRequiredError";
40
+ };
41
+ /** The forge rate limited the request and a retry didn't help. Every rate limit rejects with this class, primary or secondary. */
42
+ var RateLimitedError = class extends ForgeApiError {
43
+ name = "RateLimitedError";
44
+ /** When to send again: after the forge's `retry-after`, or when a used-up budget resets. Absent when the forge names neither. */
45
+ resetAt;
46
+ /**
47
+ * Whether the forge applied a secondary limit, such as a limit on concurrent requests or on content creation,
48
+ * rather than a used-up request budget. No remaining-request counter predicts it.
49
+ */
50
+ secondary;
51
+ constructor(message, status, body, options = {}, errorOptions) {
52
+ super(message, status, body, options, errorOptions);
53
+ this.resetAt = options.resetAt;
54
+ this.secondary = options.secondary ?? false;
55
+ }
56
+ };
57
+ /** The credential was revoked or expired. */
58
+ var TokenRevokedError = class extends ForgeApiError {
59
+ name = "TokenRevokedError";
60
+ };
61
+ /** The credential is valid but lacks the scope or permission for this call. */
62
+ var InsufficientScopeError = class extends ForgeApiError {
63
+ name = "InsufficientScopeError";
64
+ /** Scopes that would allow the request, any one of them, where the forge names them (GitHub's `X-Accepted-OAuth-Scopes`). */
65
+ acceptedScopes;
66
+ /** Scopes the credential holds, where the forge reports them (GitHub's `X-OAuth-Scopes`). */
67
+ grantedScopes;
68
+ /** Fine-grained permissions that would allow the request, verbatim, such as `issues=write` (GitHub's `X-Accepted-GitHub-Permissions`). */
69
+ acceptedPermissionsRaw;
70
+ constructor(message, status, body, context, options) {
71
+ super(message, status, body, context, options);
72
+ this.acceptedScopes = context?.acceptedScopes;
73
+ this.grantedScopes = context?.grantedScopes;
74
+ this.acceptedPermissionsRaw = context?.acceptedPermissionsRaw;
75
+ }
76
+ };
77
+ /**
78
+ * The forge refused the request for a reason other than a missing scope or a
79
+ * rate limit: an organisation policy, an SSO requirement, a protected
80
+ * resource, a release the forge has marked immutable, or a resource that
81
+ * belongs to another app. A missing scope is
82
+ * {@link InsufficientScopeError}, and a rate limit {@link RateLimitedError}.
83
+ */
84
+ var ForbiddenError = class extends ForgeApiError {
85
+ name = "ForbiddenError";
86
+ /** Why the forge refused the request. */
87
+ reason;
88
+ /** The forge's own wording, for diagnostics and for reasons that have no `ForbiddenReason`. */
89
+ reasonRaw;
90
+ /** Where the user authorises the credential for the organisation, when `reason` is `sso_required` and the forge links it (GitHub's `X-GitHub-SSO`). */
91
+ ssoUrl;
92
+ constructor(message, status, body, reason, context, options) {
93
+ super(message, status, body, context, options);
94
+ this.reason = reason;
95
+ this.reasonRaw = context?.reasonRaw;
96
+ this.ssoUrl = context?.ssoUrl;
97
+ }
98
+ };
99
+ /** Body patterns that identify a 403 reason, most specific first. */
100
+ const FORBIDDEN_PATTERNS = [
101
+ ["org_restriction", /third[- ]party application|OAuth App access restrictions|organization has enabled OAuth|not authorized by the organization|blocked by the organization/i],
102
+ ["sso_required", /SAML|single sign[- ]on|\bSSO\b|must be granted .* organization/i],
103
+ ["resource_protected", /archived|read[- ]only|protected branch|repository has been disabled|is disabled/i],
104
+ ["unknown", /contributor list is too large[^".]*/i]
105
+ ];
106
+ /**
107
+ * Classifies a 403 body. Returns `undefined` for a body that names no policy
108
+ * the caller could act on, which stays {@link InsufficientScopeError}.
109
+ */
110
+ function forbiddenReason(body) {
111
+ for (const [reason, pattern] of FORBIDDEN_PATTERNS) {
112
+ const match = body.match(pattern);
113
+ if (match) return {
114
+ reason,
115
+ reasonRaw: match[0]
116
+ };
117
+ }
118
+ }
119
+ const SECONDARY_RATE_LIMIT_RE = /secondary rate limit|abuse detection|submitted too quickly/i;
120
+ /** Whether an error message names a secondary rate limit, such as GitHub's limits on concurrency and content creation. */
121
+ function isSecondaryRateLimit(message) {
122
+ return SECONDARY_RATE_LIMIT_RE.test(message);
123
+ }
124
+ /** The pull request cannot be merged yet, typically because of failing or pending checks or branch protection. */
125
+ var MergeBlockedError = class extends ForgeApiError {
126
+ name = "MergeBlockedError";
127
+ };
128
+ /** The merge conflicts with the base branch, or the head moved since `sha` was read. */
129
+ var MergeConflictError = class extends ForgeApiError {
130
+ name = "MergeConflictError";
131
+ };
132
+ /** `contents.commitFiles()` was given an `expectedHead`, or `threads.updateBranch()` a `sha`, and the branch no longer points at it. */
133
+ var BranchMovedError = class extends ForgeApiError {
134
+ name = "BranchMovedError";
135
+ };
136
+ /** A request or a pending merge exceeded `timeout`. */
137
+ var ForgeTimeoutError = class extends ForgeError {
138
+ name = "ForgeTimeoutError";
139
+ /** The timeout that was exceeded, in milliseconds. */
140
+ timeout;
141
+ constructor(message, timeout, context, options) {
142
+ super(message, context, options);
143
+ this.timeout = timeout;
144
+ }
145
+ };
146
+ /** The request never got a response: DNS, TLS, connection refused or a proxy refusal. */
147
+ var ForgeNetworkError = class extends ForgeError {
148
+ name = "ForgeNetworkError";
149
+ };
150
+ /** A delivery's signature didn't match. */
151
+ var WebhookVerificationError = class extends ForgeError {
152
+ name = "WebhookVerificationError";
153
+ };
154
+ /** The forge doesn't support the operation. */
155
+ var UnsupportedOperationError = class extends ForgeError {
156
+ name = "UnsupportedOperationError";
157
+ };
158
+ /** A write was called on a provider constructed with `readOnly: true`. */
159
+ var ReadOnlyError = class extends UnsupportedOperationError {
160
+ name = "ReadOnlyError";
161
+ };
162
+ /** `contents.getFile` was asked for text and the file's bytes are not valid UTF-8. */
163
+ var ContentNotTextError = class extends ForgeError {
164
+ name = "ContentNotTextError";
165
+ };
166
+ /** Maps a generic merge-endpoint failure onto {@link MergeBlockedError} or {@link MergeConflictError}. */
167
+ function toMergeError(error) {
168
+ if (!(error instanceof ForgeApiError) || error.constructor !== ForgeApiError) return error;
169
+ const context = {
170
+ forge: error.forge,
171
+ instance: error.instance,
172
+ url: error.url,
173
+ method: error.method
174
+ };
175
+ if (error.status === 405) return new MergeBlockedError("Pull request is not mergeable yet", error.status, error.body, context, { cause: error });
176
+ if (error.status === 406 || error.status === 409) return new MergeConflictError("Pull request conflicts with its base or the head has moved", error.status, error.body, context, { cause: error });
177
+ return error;
178
+ }
179
+ /** The thread ref has no number, or is a kind the provider cannot address. */
180
+ var UnresolvedThreadError = class extends ForgeError {
181
+ name = "UnresolvedThreadError";
182
+ };
183
+ /** No merge method was given, and the repository allows several or reports none. */
184
+ var MergeMethodRequiredError = class extends ForgeError {
185
+ name = "MergeMethodRequiredError";
186
+ /** The merge methods that the repository allows. */
187
+ allowed;
188
+ constructor(allowed, context, options) {
189
+ super(allowed.length ? `Repository allows ${allowed.join(", ")}; pass \`method\` to choose one` : "Repository reports no merge method this provider can use; pass `method` explicitly", context, options);
190
+ this.allowed = allowed;
191
+ }
192
+ };
193
+ /** Picks the only allowed merge method, or throws {@link MergeMethodRequiredError}. */
194
+ function soleMergeMethod(allowed, context) {
195
+ const methods = Object.keys(allowed).filter((method) => allowed[method]);
196
+ if (methods.length !== 1) throw new MergeMethodRequiredError(methods, context);
197
+ return methods[0];
198
+ }
199
+ // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/model-Biiu1CfI.mjs
200
+ /** Whether `support` means the operation cannot be called. Test this rather than `support === false`: `'not_applicable'` is a non-empty string. Accepts the declaration-only levels too, so a declared level can be tested before it resolves. */
201
+ function isUnsupported(support) {
202
+ return support === false || support === "not_applicable";
203
+ }
204
+ /** Every name {@link ReactionContent} covers. */
205
+ const REACTION_CONTENTS = [
206
+ "+1",
207
+ "-1",
208
+ "laugh",
209
+ "confused",
210
+ "heart",
211
+ "hooray",
212
+ "rocket",
213
+ "eyes"
214
+ ];
215
+ /** The normalised name for a forge-native reaction name, or `'other'` where there is none. */
216
+ function reactionContent(raw) {
217
+ return REACTION_CONTENTS.includes(raw) ? raw : "other";
218
+ }
219
+ const CASE_INSENSITIVE = /* @__PURE__ */ new Set([
220
+ "github",
221
+ "gitlab",
222
+ "forgejo",
223
+ "gitea",
224
+ "bitbucket",
225
+ "gitee",
226
+ "azure-devops"
227
+ ]);
228
+ /** Whether `forge` treats owner and repository names case-insensitively. Unknown forges are assumed not to. */
229
+ function namesAreCaseInsensitive(forge) {
230
+ return CASE_INSENSITIVE.has(forge);
231
+ }
232
+ /** `repo` with `owner` and `name` lowercased where the forge ignores case, so equal repositories compare equal. */
233
+ function normaliseRepoName(repo) {
234
+ return namesAreCaseInsensitive(repo.forge) ? {
235
+ ...repo,
236
+ owner: repo.owner.toLowerCase(),
237
+ name: repo.name.toLowerCase()
238
+ } : repo;
239
+ }
240
+ /** Whether `ref` addresses an organisation, group or workspace rather than a repository, by its `kind`. */
241
+ function isNamespaceRef(ref) {
242
+ return ref.kind === "namespace";
243
+ }
244
+ /**
245
+ * The ref of a repository on `origin` from the `owner/name` that people type. The name is what follows the last
246
+ * slash, so a GitLab subgroup stays in `owner`.
247
+ * @param origin The forge and instance, such as a provider.
248
+ * @param slug The repository, such as `acme/widgets` or `acme/platform/widgets`.
249
+ * @throws {TypeError} When `slug` has no owner or no name.
250
+ * @example
251
+ * ```ts
252
+ * const repo = repoRef(provider, 'acme/widgets')
253
+ * ```
254
+ */
255
+ function repoRef(origin, slug) {
256
+ const last = slug.lastIndexOf("/");
257
+ if (last <= 0 || last === slug.length - 1) throw new TypeError(`Repository ${JSON.stringify(slug)} is not in the form owner/name`);
258
+ return {
259
+ forge: origin.forge,
260
+ instance: origin.instance,
261
+ owner: slug.slice(0, last),
262
+ name: slug.slice(last + 1)
263
+ };
264
+ }
265
+ /**
266
+ * The ref of an organisation, group, workspace or project on `origin`, as `orgs`, `repos.byOwner()` and
267
+ * namespace webhooks take it.
268
+ * @param origin The forge and instance, such as a provider.
269
+ * @param owner The namespace path, such as `acme`, `acme/platform` on GitLab or `acme/Widgets` on Azure DevOps.
270
+ * @example
271
+ * ```ts
272
+ * const teams = provider.orgs.teams(namespaceRef(provider, 'acme'))
273
+ * ```
274
+ */
275
+ function namespaceRef(origin, owner) {
276
+ return {
277
+ forge: origin.forge,
278
+ instance: origin.instance,
279
+ owner,
280
+ name: "",
281
+ kind: "namespace"
282
+ };
283
+ }
284
+ /** Whether a thread ref has a number, so that it is a `ResolvedThreadRef`. */
285
+ function isResolvedThread(thread) {
286
+ return typeof thread.number === "string" && thread.number !== "";
287
+ }
288
+ // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/utils-DEwhctg5.mjs
289
+ const BODY_EXCERPT_LENGTH = 512;
290
+ const REDIRECT_STATUSES = /* @__PURE__ */ new Set([
291
+ 301,
292
+ 302,
293
+ 303,
294
+ 307,
295
+ 308
296
+ ]);
297
+ /** A forge's plain-text rate limit refusal, such as Gitee's `403 Forbidden (Rate Limit Exceeded)`. */
298
+ const PLAIN_RATE_LIMIT_RE = /^[^{<]{0,80}\brate limit exceeded\b/i;
299
+ const DOT_SEGMENT_RE = /^(?:\.|%2e){1,2}$/i;
300
+ /** Parses an RFC 5988 `Link` header into a map of rel to URL. */
301
+ function parseLinkHeader(header) {
302
+ const links = {};
303
+ if (!header) return links;
304
+ for (const part of header.split(",")) {
305
+ const match = /^<([^>]+)>\s*;\s*(.+)/.exec(part.trim());
306
+ if (!match?.[1] || !match[2]) continue;
307
+ const rel = /rel\s*=\s*"?([^";]+)"?/.exec(match[2])?.[1];
308
+ if (rel) links[rel.trim()] = match[1];
309
+ }
310
+ return links;
311
+ }
312
+ function cursorFrom(response) {
313
+ const next = parseLinkHeader(response.headers.get("link")).next;
314
+ const etag = response.headers.get("etag") ?? void 0;
315
+ if (!next && !etag) return;
316
+ return {
317
+ nextUrl: next,
318
+ etag
319
+ };
320
+ }
321
+ /** The page size a URL carries, under the names forges use for it. */
322
+ function pageSize(url) {
323
+ for (const name of [
324
+ "per_page",
325
+ "limit",
326
+ "perPage",
327
+ "pagelen"
328
+ ]) {
329
+ const value = Number(url.searchParams.get(name));
330
+ if (Number.isInteger(value) && value > 0) return value;
331
+ }
332
+ }
333
+ /**
334
+ * The exact total a response reports in a pagination header. GitLab sends
335
+ * `x-total`, and Forgejo and Gitea send `x-total-count`. A Forgejo or Gitea
336
+ * timeline reports the page's own length there, so a count no larger than the
337
+ * page is ignored for timeline requests; everywhere else it is exact, even
338
+ * when it equals the number of items on a single page.
339
+ */
340
+ function headerTotal(response, itemCount, requestUrl) {
341
+ const total = headerNumber(response, "x-total");
342
+ if (total !== void 0) return total;
343
+ const counted = headerNumber(response, "x-total-count");
344
+ if (counted === void 0) return;
345
+ return counted <= itemCount && /\/timeline(?:\?|$)/.test(requestUrl) ? void 0 : counted;
346
+ }
347
+ /**
348
+ * The total a `Link` header implies: the page number of its `rel="last"`
349
+ * entry times the page size that URL, or the request URL, reports. GitHub,
350
+ * GitLab, Forgejo and Gitea page by number, so their last page times their
351
+ * page size approximates the total. A last page of one means a single page,
352
+ * whose total is the items on it. `undefined` when the header carries no
353
+ * usable last page.
354
+ */
355
+ function linkTotal(header, requestUrl, itemCount) {
356
+ const last = parseLinkHeader(header).last;
357
+ if (!last) return;
358
+ let lastUrl;
359
+ let request;
360
+ try {
361
+ lastUrl = new URL(last);
362
+ request = new URL(requestUrl);
363
+ } catch {
364
+ return;
365
+ }
366
+ const page = Number(lastUrl.searchParams.get("page"));
367
+ if (!Number.isInteger(page) || page < 1) return;
368
+ if (page === 1) return itemCount;
369
+ const size = pageSize(lastUrl) ?? pageSize(request);
370
+ return size === void 0 ? void 0 : page * size;
371
+ }
372
+ function retryAfterMs(response) {
373
+ const header = response.headers.get("retry-after");
374
+ if (!header) return;
375
+ const seconds = Number(header);
376
+ if (Number.isFinite(seconds)) return seconds * 1e3;
377
+ const date = Date.parse(header);
378
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
379
+ }
380
+ /** `x-ratelimit-reset` and `ratelimit-reset` hold a Unix time in seconds on some forges, and seconds from now on others. */
381
+ function resetDate(response, now) {
382
+ const reset = headerNumber(response, "x-ratelimit-reset", "ratelimit-reset");
383
+ if (reset === void 0) return;
384
+ return new Date(reset > 1e9 ? reset * 1e3 : now + reset * 1e3);
385
+ }
386
+ /** A budget with requests left resets on its own schedule, which says nothing about when a secondary limit lifts. */
387
+ function rateLimitReset(response, budget) {
388
+ const after = retryAfterMs(response);
389
+ if (after !== void 0) return new Date(Date.now() + after);
390
+ return budget?.remaining ? void 0 : budget?.resetAt;
391
+ }
392
+ /** The leading number of the first of `names` to hold one, such as `60` of `60, 60;w=3600`. */
393
+ function headerNumber(response, ...names) {
394
+ for (const name of names) {
395
+ const value = response.headers.get(name)?.split(/[,;]/, 1)[0].trim();
396
+ if (value && Number.isFinite(Number(value))) return Number(value);
397
+ }
398
+ }
399
+ /** The members of a structured-field list such as `"burst";r=10;t=5, "day";r=900;t=3600`, by name. */
400
+ function fieldMembers(response, name) {
401
+ const members = /* @__PURE__ */ new Map();
402
+ for (const member of response.headers.get(name)?.split(",") ?? []) {
403
+ const [key = "", ...params] = member.split(";");
404
+ members.set(key.trim().replace(/^"(.*)"$/, "$1"), Object.fromEntries(params.map((param) => {
405
+ const [field = "", value] = param.split("=");
406
+ return [field.trim(), Number(value)];
407
+ })));
408
+ }
409
+ return members;
410
+ }
411
+ /** The IETF `ratelimit` and `ratelimit-policy` fields, for the policy with the fewest requests left. */
412
+ function structuredRateLimit(response, now) {
413
+ const [name, state] = [...fieldMembers(response, "ratelimit")].filter(([, params]) => Number.isFinite(params.r)).sort(([, a], [, b]) => a.r - b.r)[0] ?? [];
414
+ if (!state) return;
415
+ const limit = fieldMembers(response, "ratelimit-policy").get(name)?.q;
416
+ return {
417
+ ...Number.isFinite(limit) ? { limit } : {},
418
+ remaining: state.r,
419
+ ...Number.isFinite(state.t) ? { resetAt: new Date(now + state.t * 1e3) } : {},
420
+ ...name ? { resource: name } : {}
421
+ };
422
+ }
423
+ /** The request budget a response reports, from `x-ratelimit-*` or `ratelimit-*` headers, or the IETF `ratelimit` field. */
424
+ function rateLimitOf(response, now = Date.now()) {
425
+ const limit = headerNumber(response, "x-ratelimit-limit", "ratelimit-limit");
426
+ const remaining = headerNumber(response, "x-ratelimit-remaining", "ratelimit-remaining");
427
+ const reset = resetDate(response, now);
428
+ if (limit === void 0 && remaining === void 0 && reset === void 0) return structuredRateLimit(response, now);
429
+ const resource = response.headers.get("x-ratelimit-resource") || response.headers.get("ratelimit-name") || void 0;
430
+ return {
431
+ ...limit === void 0 ? {} : { limit },
432
+ ...remaining === void 0 ? {} : { remaining },
433
+ ...reset === void 0 ? {} : { resetAt: reset },
434
+ ...resource === void 0 ? {} : { resource }
435
+ };
436
+ }
437
+ /** Whether the `message` or an `errors[].message` of a JSON error body names a secondary rate limit. */
438
+ function scopeList(header) {
439
+ return header === null ? void 0 : header.split(",").map((scope) => scope.trim()).filter(Boolean);
440
+ }
441
+ function namesSecondaryRateLimit(body) {
442
+ let parsed;
443
+ try {
444
+ parsed = JSON.parse(body);
445
+ } catch {
446
+ return false;
447
+ }
448
+ const { message, errors } = parsed ?? {};
449
+ return [message, ...Array.isArray(errors) ? errors.map((error) => error?.message) : []].some((text) => typeof text === "string" && isSecondaryRateLimit(text));
450
+ }
451
+ /** GitHub sends a secondary limit as a 403 or a 429, and its content creation limit can arrive as a 422. */
452
+ function isRateLimited(response, budget, body) {
453
+ if (response.status === 429) return true;
454
+ if ((response.status === 403 || response.status === 422) && namesSecondaryRateLimit(body)) return true;
455
+ if (response.status !== 403 || budget?.limit === 0) return false;
456
+ return budget?.remaining === 0 || response.headers.has("retry-after") || !budget && PLAIN_RATE_LIMIT_RE.test(body.trim());
457
+ }
458
+ /**
459
+ * One signal that aborts when any of `signals` does. `AbortSignal.any` would
460
+ * do this, but StarlingMonkey (the wasm runtime) does not implement it.
461
+ */
462
+ function anySignal(signals) {
463
+ const aborted = signals.find((signal) => signal.aborted);
464
+ if (aborted) return aborted;
465
+ if (signals.length === 1) return signals[0];
466
+ const controller = new AbortController();
467
+ const listeners = [];
468
+ for (const signal of signals) {
469
+ const listener = () => {
470
+ controller.abort(signal.reason);
471
+ for (const [other, removed] of listeners) other.removeEventListener("abort", removed);
472
+ };
473
+ listeners.push([signal, listener]);
474
+ signal.addEventListener("abort", listener, { once: true });
475
+ }
476
+ return controller.signal;
477
+ }
478
+ function assertUrl(url) {
479
+ if (url.protocol !== "https:" && url.protocol !== "http:" || url.username || url.password) throw new TypeError("Invalid request URL");
480
+ return url;
481
+ }
482
+ function assertInput(input) {
483
+ for (const char of input) {
484
+ const code = char.charCodeAt(0);
485
+ if (code <= 32 || code === 127) throw new TypeError("Invalid request URL");
486
+ }
487
+ }
488
+ function assertRelativePath(path) {
489
+ const pathname = path.split("?", 1)[0];
490
+ if (path.includes("#") || pathname.includes("\\") || pathname.split("/").some((segment) => DOT_SEGMENT_RE.test(segment))) throw new TypeError(`Unsafe request path ${JSON.stringify(path)}; check the refs passed to the provider`);
491
+ return path;
492
+ }
493
+ function sleep(ms, signal) {
494
+ return new Promise((resolve, reject) => {
495
+ if (signal?.aborted) {
496
+ reject(signal.reason);
497
+ return;
498
+ }
499
+ const timer = setTimeout(() => {
500
+ signal?.removeEventListener("abort", onAbort);
501
+ resolve();
502
+ }, ms);
503
+ function onAbort() {
504
+ clearTimeout(timer);
505
+ reject(signal.reason);
506
+ }
507
+ signal?.addEventListener("abort", onAbort, { once: true });
508
+ });
509
+ }
510
+ /** Settles as `promise` does, or rejects with the signal's reason once it aborts, leaving `promise` running. */
511
+ function abortable(promise, signal) {
512
+ if (!signal) return promise;
513
+ if (signal.aborted) return Promise.reject(signal.reason);
514
+ return new Promise((resolve, reject) => {
515
+ const onAbort = () => reject(signal.reason);
516
+ signal.addEventListener("abort", onAbort, { once: true });
517
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
518
+ });
519
+ }
520
+ /**
521
+ * Creates a fetcher for one forge API.
522
+ * @param options The base URL and the credentials, timeout and error context of every request.
523
+ */
524
+ function createFetcher(options) {
525
+ const timeout = options.timeout ?? 3e4;
526
+ const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
527
+ assertInput(options.baseUrl);
528
+ const base = assertUrl(new URL(options.baseUrl));
529
+ if (base.search || base.hash) throw new TypeError("Invalid API base URL");
530
+ base.pathname = `${base.pathname.replace(/\/$/, "")}/`;
531
+ const baseOrigin = base.origin;
532
+ function resolve(path, query) {
533
+ assertInput(path);
534
+ let url;
535
+ try {
536
+ url = new URL(path);
537
+ } catch {
538
+ if (path.startsWith("//") || path.split("/", 1)[0].includes(":")) throw new TypeError("Invalid request URL");
539
+ }
540
+ url = assertUrl(url ?? new URL(assertRelativePath(path).replace(/^\//, ""), base));
541
+ for (const [key, value] of Object.entries(query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
542
+ return url.toString();
543
+ }
544
+ function withDefaultQuery(url) {
545
+ if (!options.query) return url;
546
+ const target = new URL(url);
547
+ for (const [key, value] of Object.entries(options.query)) if (!target.searchParams.has(key)) target.searchParams.set(key, value);
548
+ return target.toString();
549
+ }
550
+ async function send(url, options_, attempt, authenticated = true, download = false, redirects = 0, streaming = false, follow = false) {
551
+ const target = assertUrl(new URL(url));
552
+ const trusted = authenticated && target.origin === baseOrigin;
553
+ const controller = streaming ? new AbortController() : void 0;
554
+ const timer = controller ? setTimeout(() => controller.abort(new DOMException("Request timed out", "TimeoutError")), timeout) : void 0;
555
+ const signals = [controller?.signal ?? AbortSignal.timeout(timeout)];
556
+ if (options_.signal) signals.push(options_.signal);
557
+ const headers = new Headers(trusted ? options.headers : void 0);
558
+ for (const [key, value] of Object.entries(trusted ? await (options.authHeaders?.() ?? {}) : {})) headers.set(key, value);
559
+ for (const [key, value] of new Headers(options_.headers)) headers.set(key, value);
560
+ if (options_.etag) headers.set("if-none-match", options_.etag);
561
+ const { json: payload, mapError: _mapError, ...init } = options_;
562
+ if (payload !== void 0) headers.set("content-type", "application/json");
563
+ let response;
564
+ try {
565
+ response = await doFetch(trusted ? withDefaultQuery(url) : url, {
566
+ ...init,
567
+ redirect: follow ? "follow" : "manual",
568
+ credentials: trusted ? init.credentials : "omit",
569
+ headers,
570
+ body: payload === void 0 ? init.body : JSON.stringify(payload),
571
+ signal: anySignal(signals)
572
+ });
573
+ } catch (cause) {
574
+ if (options_.signal?.aborted) throw options_.signal.reason ?? cause;
575
+ if (cause instanceof Error && (cause.name === "TimeoutError" || cause.name === "AbortError")) throw new ForgeTimeoutError(`Request to ${url} timed out after ${timeout}ms`, timeout, {
576
+ ...options.context,
577
+ url,
578
+ method: options_.method ?? "GET"
579
+ }, { cause });
580
+ const inner = cause instanceof Error ? cause.cause : void 0;
581
+ const reason = typeof inner?.code === "string" ? inner.code : inner?.message;
582
+ throw new ForgeNetworkError(`Request to ${url} failed: ${cause instanceof Error ? cause.message : String(cause)}${typeof reason === "string" && reason ? ` (${reason})` : ""}`, {
583
+ ...options.context,
584
+ url,
585
+ method: options_.method ?? "GET"
586
+ }, { cause });
587
+ } finally {
588
+ clearTimeout(timer);
589
+ }
590
+ if (response.type === "opaqueredirect" && options_.redirect !== "manual") {
591
+ const method = (options_.method ?? "GET").toUpperCase();
592
+ if (options_.redirect === "error" || method !== "GET" && method !== "HEAD") throw new TypeError("Hidden redirect refused");
593
+ return send(url, options_, attempt, authenticated, download, redirects, streaming, true);
594
+ }
595
+ if (follow && response.redirected && response.url) {
596
+ const final = assertUrl(new URL(response.url));
597
+ if (final.origin !== target.origin && !download || target.protocol === "https:" && final.protocol !== "https:") {
598
+ await response.body?.cancel();
599
+ throw new TypeError("Unsafe request redirect");
600
+ }
601
+ }
602
+ const budget = rateLimitOf(response);
603
+ if (budget && options.onRateLimit && target.origin === baseOrigin) options.onRateLimit({
604
+ url,
605
+ method: options_.method ?? "GET",
606
+ rateLimit: budget
607
+ });
608
+ const location = REDIRECT_STATUSES.has(response.status) ? response.headers.get("location") : null;
609
+ if (location && options_.redirect !== "manual") {
610
+ await response.body?.cancel();
611
+ if (options_.redirect === "error" || redirects >= 20) throw new TypeError("Request redirect refused");
612
+ assertInput(location);
613
+ const next = assertUrl(new URL(location, target));
614
+ const sameOrigin = next.origin === target.origin;
615
+ if (!sameOrigin && !download || target.protocol === "https:" && next.protocol !== "https:") throw new TypeError("Unsafe request redirect");
616
+ const method = (options_.method ?? "GET").toUpperCase();
617
+ if (!sameOrigin && method !== "GET" && method !== "HEAD") throw new TypeError("Unsafe request redirect");
618
+ let nextOptions = options_;
619
+ if (!sameOrigin) nextOptions = {
620
+ method,
621
+ signal: options_.signal,
622
+ credentials: "omit"
623
+ };
624
+ else if (response.status === 303 && method !== "HEAD" || (response.status === 301 || response.status === 302) && method === "POST") {
625
+ const nextHeaders = new Headers(options_.headers);
626
+ for (const name of [
627
+ "content-type",
628
+ "content-length",
629
+ "content-encoding",
630
+ "content-language",
631
+ "content-location"
632
+ ]) nextHeaders.delete(name);
633
+ nextOptions = {
634
+ ...options_,
635
+ method: "GET",
636
+ body: void 0,
637
+ json: void 0,
638
+ headers: nextHeaders
639
+ };
640
+ }
641
+ return send(next.toString(), nextOptions, attempt, authenticated && sameOrigin, download, redirects + 1, streaming);
642
+ }
643
+ if (response.ok || response.status === 304 || options_.redirect === "manual" && (response.type === "opaqueredirect" || response.status >= 300 && response.status < 400)) return response;
644
+ const text = await response.text();
645
+ const body = text.slice(0, BODY_EXCERPT_LENGTH);
646
+ const context = {
647
+ ...options.context,
648
+ url,
649
+ method: options_.method ?? "GET"
650
+ };
651
+ const credentialed = trusted && options.authenticated || headers.has("authorization");
652
+ if (response.status === 401) throw credentialed ? new TokenRevokedError("Credentials were rejected by the forge", 401, body, context) : new AuthenticationRequiredError("Credentials are required for this request", 401, body, context);
653
+ if (response.status === 403 && !credentialed && budget?.limit === 0) throw new AuthenticationRequiredError("Credentials are required for this request", 403, body, context);
654
+ if (response.status === 404) throw new NotFoundError(`Nothing found at ${options_.method ?? "GET"} ${url}, or the credential cannot see it`, 404, body, context);
655
+ if (isRateLimited(response, budget, text)) {
656
+ const secondary = namesSecondaryRateLimit(text) || budget?.remaining !== 0 && (response.status !== 429 || response.headers.has("retry-after"));
657
+ const wait = retryAfterMs(response);
658
+ if (attempt === 0 && wait !== void 0 && wait <= 6e4) {
659
+ options.onRetry?.({
660
+ url,
661
+ method: options_.method ?? "GET",
662
+ wait
663
+ });
664
+ await sleep(wait, options_.signal);
665
+ return send(url, options_, attempt + 1, authenticated, download, redirects, streaming, follow);
666
+ }
667
+ throw new RateLimitedError("Rate limited by the forge", response.status, body, {
668
+ ...context,
669
+ resetAt: rateLimitReset(response, budget),
670
+ secondary
671
+ });
672
+ }
673
+ if (response.status === 403) {
674
+ const acceptedScopes = scopeList(response.headers.get("x-accepted-oauth-scopes"));
675
+ const grantedScopes = scopeList(response.headers.get("x-oauth-scopes"));
676
+ const missingScope = acceptedScopes?.length && !acceptedScopes.some((scope) => grantedScopes?.includes(scope));
677
+ const ssoUrl = response.headers.get("x-github-sso")?.match(/\burl=(\S+)/)?.[1];
678
+ const forbidden = missingScope ? void 0 : ssoUrl ? {
679
+ reason: "sso_required",
680
+ reasonRaw: forbiddenReason(body)?.reasonRaw
681
+ } : forbiddenReason(body);
682
+ if (!forbidden) {
683
+ const acceptedPermissionsRaw = response.headers.get("x-accepted-github-permissions") || void 0;
684
+ throw new InsufficientScopeError("Credentials lack the scope or permission for this request", 403, body, {
685
+ ...context,
686
+ acceptedScopes,
687
+ grantedScopes,
688
+ acceptedPermissionsRaw
689
+ });
690
+ }
691
+ throw new ForbiddenError(`Forge refused the request (${forbidden.reason})`, 403, body, forbidden.reason, {
692
+ ...context,
693
+ reasonRaw: forbidden.reasonRaw,
694
+ ssoUrl
695
+ });
696
+ }
697
+ throw new ForgeApiError(`Forge responded with ${response.status} for ${options_.method ?? "GET"} ${url}`, response.status, body, context);
698
+ }
699
+ async function raw(path, options_ = {}) {
700
+ try {
701
+ return await send(resolve(path, options_.query), options_, 0);
702
+ } catch (error) {
703
+ throw options_.mapError ? options_.mapError(error) : error;
704
+ }
705
+ }
706
+ async function json(path, options_ = {}) {
707
+ const response = await raw(path, options_);
708
+ if (response.status === 304 || response.status === 204) return {
709
+ data: void 0,
710
+ response,
711
+ notModified: response.status === 304,
712
+ cursor: cursorFrom(response)
713
+ };
714
+ const text = await response.text();
715
+ return {
716
+ data: text ? parseJson(text) : void 0,
717
+ response,
718
+ notModified: false,
719
+ cursor: cursorFrom(response)
720
+ };
721
+ }
722
+ async function page(path, options_ = {}) {
723
+ const { select, cursor, conditional = true, ...requestOptions } = options_;
724
+ const initial = resolve(path, requestOptions.query);
725
+ const url = cursor?.nextUrl ? resolve(cursor.nextUrl) : initial;
726
+ if (new URL(url).origin !== new URL(initial).origin) throw new TypeError("Pagination URL must remain on the requested origin");
727
+ const first = conditional && !cursor?.nextUrl && !cursor?.token;
728
+ const sent = first ? requestOptions.etag ?? cursor?.etag : void 0;
729
+ const result = await json(url, {
730
+ ...requestOptions,
731
+ etag: sent,
732
+ query: void 0
733
+ });
734
+ const validator = first ? result.response.headers.get("etag") ?? (result.notModified ? sent : void 0) : void 0;
735
+ const etag = validator ? { etag: validator } : {};
736
+ if (result.notModified) return {
737
+ ...result,
738
+ data: [],
739
+ cursor: void 0,
740
+ ...etag
741
+ };
742
+ const next = select ? select(result.data, result.cursor?.nextUrl) : void 0;
743
+ const items = next ? next.items : result.data ?? [];
744
+ const total = next?.total ?? headerTotal(result.response, items.length, url) ?? linkTotal(result.response.headers.get("link"), url, items.length);
745
+ if (!next) return {
746
+ ...result,
747
+ data: items,
748
+ cursor: result.cursor?.nextUrl ? result.cursor : void 0,
749
+ ...total !== void 0 ? { total } : {},
750
+ ...etag
751
+ };
752
+ return {
753
+ ...result,
754
+ data: items,
755
+ cursor: next.next ? {
756
+ ...result.cursor,
757
+ nextUrl: next.next
758
+ } : void 0,
759
+ ...total !== void 0 ? { total } : {},
760
+ ...etag
761
+ };
762
+ }
763
+ async function* items(path, options_ = {}) {
764
+ let cursor;
765
+ do {
766
+ const result = await page(path, {
767
+ ...options_,
768
+ cursor
769
+ });
770
+ yield* result.data ?? [];
771
+ cursor = result.notModified ? void 0 : result.cursor;
772
+ } while (cursor?.nextUrl);
773
+ }
774
+ async function stream(path, options_ = {}) {
775
+ try {
776
+ const response = await send(resolve(path, options_.query), options_, 0, true, true, 0, true);
777
+ return {
778
+ status: response.status,
779
+ headers: response.headers,
780
+ body: response.body ?? emptyStream()
781
+ };
782
+ } catch (error) {
783
+ throw options_.mapError ? options_.mapError(error) : error;
784
+ }
785
+ }
786
+ return {
787
+ raw,
788
+ stream,
789
+ json,
790
+ page,
791
+ items,
792
+ resolve
793
+ };
794
+ }
795
+ const LONG_NUMBER_RE = /\d{16}/;
796
+ const INTEGER_RE = /^-?\d+$/;
797
+ /**
798
+ * Parses JSON, keeping integers beyond `Number.MAX_SAFE_INTEGER` (such as
799
+ * GitHub webhook delivery ids) as their exact digits, where the runtime gives
800
+ * the reviver the source text.
801
+ */
802
+ function parseJson(text) {
803
+ if (!LONG_NUMBER_RE.test(text)) return JSON.parse(text);
804
+ return JSON.parse(text, (_key, value, context) => typeof value === "number" && !Number.isSafeInteger(value) && context?.source && INTEGER_RE.test(context.source) ? context.source : value);
805
+ }
806
+ function emptyStream() {
807
+ return new Blob([]).stream();
808
+ }
809
+ const SAFE_METHODS = /* @__PURE__ */ new Set([
810
+ "GET",
811
+ "HEAD",
812
+ "OPTIONS"
813
+ ]);
814
+ /**
815
+ * Builds a provider's `request()` escape hatch on top of its fetcher.
816
+ * @param fetcher The fetcher to send requests with.
817
+ * @param createOptions Where to reject writes, for a read-only provider.
818
+ */
819
+ function createRequest(fetcher, createOptions = {}) {
820
+ const { readOnly } = createOptions;
821
+ return (async (method, path, options = {}) => {
822
+ const upperMethod = method.toUpperCase();
823
+ if (readOnly && (options.mutates ?? !SAFE_METHODS.has(upperMethod))) throw readOnly(upperMethod, path);
824
+ const json = options.body !== void 0 && isJsonBody(options.body);
825
+ const init = {
826
+ method: upperMethod,
827
+ query: options.query,
828
+ signal: options.signal,
829
+ headers: {
830
+ ...json ? { "content-type": "application/json" } : {},
831
+ ...options.headers
832
+ },
833
+ body: options.body === void 0 ? void 0 : json ? JSON.stringify(options.body) : options.body
834
+ };
835
+ if ("raw" in options && options.raw) return fetcher.stream(path, init);
836
+ const result = await fetcher.json(path, init);
837
+ const rateLimit = rateLimitOf(result.response);
838
+ return {
839
+ status: result.response.status,
840
+ data: result.data,
841
+ headers: result.response.headers,
842
+ ...rateLimit ? { rateLimit } : {}
843
+ };
844
+ });
845
+ }
846
+ function isJsonBody(value) {
847
+ return typeof value !== "string" && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && !(typeof Blob !== "undefined" && value instanceof Blob) && !(typeof FormData !== "undefined" && value instanceof FormData) && !(value instanceof URLSearchParams) && !(typeof ReadableStream !== "undefined" && value instanceof ReadableStream);
848
+ }
849
+ /**
850
+ * Wraps a generator so warnings it reports are collected on the returned
851
+ * iterable rather than interrupting iteration.
852
+ */
853
+ function forgeIterable(run) {
854
+ const warnings = [];
855
+ return {
856
+ warnings,
857
+ [Symbol.asyncIterator]: () => run((warning) => warnings.push(warning))[Symbol.asyncIterator]()
858
+ };
859
+ }
860
+ /** Drives a `page()` function until it reports no further cursor, collecting page warnings. */
861
+ function iteratePages(page, options = {}) {
862
+ return forgeIterable(async function* (warn) {
863
+ let cursor = options.cursor;
864
+ while (true) {
865
+ const result = await page({
866
+ ...options,
867
+ cursor
868
+ });
869
+ result.warnings?.forEach(warn);
870
+ yield* result.items;
871
+ if (!result.cursor?.nextUrl && !result.cursor?.token || result.notModified) return;
872
+ cursor = result.cursor;
873
+ }
874
+ });
875
+ }
876
+ /** Turns a caught error into a serialisable warning. */
877
+ function toWarning(code, error, subject) {
878
+ const err = error instanceof Error ? error : new Error(String(error));
879
+ return {
880
+ code,
881
+ message: err.message,
882
+ subject,
883
+ cause: {
884
+ name: err.name,
885
+ message: err.message,
886
+ status: err instanceof ForgeApiError ? err.status : void 0
887
+ }
888
+ };
889
+ }
890
+ /** Whether a failed side read may become a warning; rate limits, revoked tokens and errors from outside forges still stop the read. */
891
+ function degradesToWarning(error) {
892
+ return error instanceof ForgeError && !(error instanceof RateLimitedError) && !(error instanceof TokenRevokedError);
893
+ }
894
+ /** Maps with at most `limit` calls in flight, preserving order. Once a call rejects, no further calls start. */
895
+ async function mapConcurrent(items, limit, fn) {
896
+ const results = Array.from({ length: items.length });
897
+ let next = 0;
898
+ let failed = false;
899
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
900
+ while (!failed && next < items.length) {
901
+ const index = next++;
902
+ try {
903
+ results[index] = await fn(items[index]);
904
+ } catch (error) {
905
+ failed = true;
906
+ throw error;
907
+ }
908
+ }
909
+ }));
910
+ return results;
911
+ }
912
+ /** `threads.getMany` for forges without a batch endpoint. A rate limit or a rejected credential rejects the call; other failures become per-item warnings. */
913
+ function getManyConcurrently(refs, get, options = {}) {
914
+ return mapConcurrent(refs, 4, (ref) => get(ref, options).then((thread) => ({
915
+ ok: true,
916
+ ref,
917
+ thread
918
+ }), (error) => {
919
+ if (options.signal?.aborted) throw options.signal.reason;
920
+ if (error instanceof ForgeError && !degradesToWarning(error)) throw error;
921
+ return {
922
+ ok: false,
923
+ ref,
924
+ warning: toWarning(error instanceof UnresolvedThreadError ? "thread_unresolved" : "thread_unreadable", error, ref.number)
925
+ };
926
+ }));
927
+ }
928
+ /** The comment that a notification's `latest_comment_url` names: an issue comment on a thread subject with a number, or a comment on a commit subject. */
929
+ function latestCommentOf(subject, url) {
930
+ if (subject.type === "commit") {
931
+ const id = /\/repos\/[^/]+\/[^/]+\/comments\/(\d+)$/.exec(url ?? "")?.[1];
932
+ return id ? {
933
+ forge: subject.commit.forge,
934
+ instance: subject.commit.instance,
935
+ commit: subject.commit,
936
+ id
937
+ } : void 0;
938
+ }
939
+ const id = /\/issues\/comments\/(\d+)$/.exec(url ?? "")?.[1];
940
+ if (!id || subject.type !== "thread" || !isResolvedThread(subject.thread)) return;
941
+ return {
942
+ forge: subject.thread.forge,
943
+ instance: subject.thread.instance,
944
+ thread: subject.thread,
945
+ id
946
+ };
947
+ }
948
+ /** Compares dotted numeric versions, ignoring any suffix after the numbers. */
949
+ function versionAtLeast(version, minimum) {
950
+ if (!version) return false;
951
+ const parts = (value) => (/^\D*(\d+(?:\.\d+)*)/.exec(value)?.[1] ?? "0").split(".").map(Number);
952
+ const [a, b] = [parts(version), parts(minimum)];
953
+ for (let index = 0; index < Math.max(a.length, b.length); index++) {
954
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
955
+ if (difference !== 0) return difference > 0;
956
+ }
957
+ return true;
958
+ }
959
+ /** Reads a timestamp from a forge response, or `undefined` when it is empty or not a date. */
960
+ function toDate(value) {
961
+ if (value === null || value === void 0 || value === "") return;
962
+ const date = new Date(value);
963
+ return Number.isNaN(date.getTime()) ? void 0 : date;
964
+ }
965
+ /** The host of `baseUrl`, including the port when there is one. */
966
+ function hostOf(baseUrl) {
967
+ return new URL(baseUrl).host;
968
+ }
969
+ /** The namespace ref of `ref`'s owner, for the `org` of a team's ref. */
970
+ function teamOrg(ref) {
971
+ return isNamespaceRef(ref) ? ref : namespaceRef(ref, ref.owner);
972
+ }
973
+ /** Narrows a ref to one a provider can address, or throws {@link UnresolvedThreadError}. */
974
+ function requireThread(ref, context) {
975
+ if (!isResolvedThread(ref)) throw new UnresolvedThreadError("Thread ref has no number; resolve it before calling the forge", context ?? {
976
+ forge: ref.forge,
977
+ instance: ref.instance
978
+ });
979
+ return ref;
980
+ }
981
+ /**
982
+ * Narrows a ref to an issue or pull request, or throws
983
+ * {@link UnsupportedOperationError} naming the verb that needs one.
984
+ */
985
+ function requireIssueOrPull(ref, context, verb) {
986
+ const thread = requireThread(ref, context);
987
+ if (thread.kind !== "issue" && thread.kind !== "pull_request") throw new UnsupportedOperationError(`${context.forge ?? "This forge"} cannot ${verb} a ${thread.kind}`, context);
988
+ return thread;
989
+ }
990
+ /** The token in `auth`, read again on every call when it is a function. */
991
+ async function resolveToken(auth) {
992
+ return typeof auth.token === "function" ? await auth.token() : auth.token;
993
+ }
994
+ /**
995
+ * The forge-native id `threads.setMilestone` sends: the milestone's `id`, a
996
+ * string of digits as it is, or the id of the milestone with that title.
997
+ */
998
+ async function milestoneId(milestone, page, context, options = {}) {
999
+ const value = typeof milestone === "string" ? milestone : milestone.id;
1000
+ if (/^\d+$/.test(value)) return Number(value);
1001
+ for await (const candidate of iteratePages(page, {
1002
+ state: "all",
1003
+ signal: options.signal
1004
+ })) if (candidate.title === value) return Number(candidate.id);
1005
+ throw new UnsupportedOperationError(`No milestone titled ${value}`, context);
1006
+ }
1007
+ /** Joins the merge commit title and message for a forge that takes them as one string. */
1008
+ function mergeCommitMessage({ title, message }) {
1009
+ return title && message ? `${title}\n\n${message}` : title || message;
1010
+ }
1011
+ /** A login from either a login string or an actor. */
1012
+ function actorLogin(actor) {
1013
+ return typeof actor === "string" ? actor : actor.login;
1014
+ }
1015
+ /** Maps one fetched page into a {@link Page}. The cursor is kept only when there is a next page. */
1016
+ function toPage(result, map, warnings) {
1017
+ return {
1018
+ items: (result.data ?? []).flatMap((raw) => {
1019
+ const item = map(raw);
1020
+ return item === void 0 ? [] : [item];
1021
+ }),
1022
+ ...result.total !== void 0 ? { total: result.total } : {},
1023
+ cursor: result.cursor?.nextUrl || result.cursor?.token ? result.cursor : void 0,
1024
+ ...result.etag ? { etag: result.etag } : {},
1025
+ notModified: result.notModified || void 0,
1026
+ ...warnings?.length ? { warnings } : {},
1027
+ ...rateLimitPart(result.response)
1028
+ };
1029
+ }
1030
+ /**
1031
+ * Adds the validator of a listing's first page to `page`: the response's `etag`, or on a `304` the one
1032
+ * `cursor` sent. Later pages are left as they are.
1033
+ */
1034
+ function withEtag(page, result, cursor) {
1035
+ if (!isFirstPage(cursor)) return page;
1036
+ const etag = result.response.headers.get("etag") ?? (result.notModified ? cursor?.etag : void 0);
1037
+ return etag ? {
1038
+ ...page,
1039
+ etag
1040
+ } : page;
1041
+ }
1042
+ /** Whether `cursor` asks for the first page of a listing: it has neither `nextUrl` nor `token`, though it may have an `etag`. */
1043
+ function isFirstPage(cursor) {
1044
+ return !cursor?.nextUrl && !cursor?.token;
1045
+ }
1046
+ /** The `etag` of `cursor` when it asks for the first page, to send as `If-None-Match`. */
1047
+ function firstPageEtag(cursor) {
1048
+ return isFirstPage(cursor) ? cursor?.etag : void 0;
1049
+ }
1050
+ /** Builds a {@link Listing} for a forge that names its page-size parameter `pageParam`. */
1051
+ function createListing(fetcher, pageParam, defaultPerPage) {
1052
+ return async (path, options, map, { warnings, query, ...extras } = {}) => toPage(await fetcher.page(path, {
1053
+ ...extras,
1054
+ query: {
1055
+ ...query,
1056
+ [pageParam]: options.perPage ?? defaultPerPage
1057
+ },
1058
+ cursor: options.cursor,
1059
+ signal: options.signal
1060
+ }), map, warnings);
1061
+ }
1062
+ /** The `rateLimit` of a page built by hand: the budget of the response behind it, or of the page it maps. */
1063
+ function rateLimitPart(source) {
1064
+ const rateLimit = source && ("headers" in source ? rateLimitOf(source) : source.rateLimit);
1065
+ return rateLimit ? { rateLimit } : {};
1066
+ }
1067
+ /**
1068
+ * Chains listings that a forge serves from separate endpoints. The cursor
1069
+ * `token` records which phase is next, ahead of the phase's own token. With
1070
+ * one phase, the first page is conditional as that phase's is; with more,
1071
+ * one validator cannot cover every endpoint, so no page has an `etag`.
1072
+ */
1073
+ async function phased(phases, cursor) {
1074
+ const match = /^(\d+):(.*)$/s.exec(cursor?.token ?? "");
1075
+ const index = match ? Number(match[1]) : 0;
1076
+ const conditional = phases.length === 1;
1077
+ const inner = cursor && (cursor.nextUrl || match?.[2]) ? {
1078
+ ...cursor,
1079
+ token: match?.[2] || void 0
1080
+ } : conditional && cursor?.etag ? { etag: cursor.etag } : void 0;
1081
+ const { etag, ...rest } = await phases[index](inner);
1082
+ const page = conditional && etag ? {
1083
+ ...rest,
1084
+ etag
1085
+ } : rest;
1086
+ if (page.cursor) return {
1087
+ ...page,
1088
+ cursor: {
1089
+ ...page.cursor,
1090
+ token: `${index}:${page.cursor.token ?? ""}`
1091
+ }
1092
+ };
1093
+ return index + 1 < phases.length ? {
1094
+ ...page,
1095
+ cursor: { token: `${index + 1}:` }
1096
+ } : page;
1097
+ }
1098
+ /** Whether `labels` include every name in `wanted`; true when nothing is wanted. */
1099
+ function hasEveryLabel(labels, wanted) {
1100
+ return !wanted?.length || wanted.every((name) => labels?.some((label) => label.name === name));
1101
+ }
1102
+ /** The counts that are numbers, or `undefined` when none are. */
1103
+ function toPullStats(counts) {
1104
+ const known = Object.entries(counts).filter(([, count]) => typeof count === "number");
1105
+ return known.length ? Object.fromEntries(known) : void 0;
1106
+ }
1107
+ /** Any failure fails, else any pending is pending, else any unknown (or none at all) is unknown, else success. */
1108
+ function summariseChecks(states, url) {
1109
+ const failed = states.filter((state) => state === "failure").length;
1110
+ return {
1111
+ state: failed ? "failure" : states.includes("pending") ? "pending" : !states.length || states.includes("unknown") ? "unknown" : "success",
1112
+ total: states.length,
1113
+ failed,
1114
+ ...url ? { url } : {}
1115
+ };
1116
+ }
1117
+ const FAILED_CONCLUSIONS = /* @__PURE__ */ new Set([
1118
+ "failure",
1119
+ "timed_out",
1120
+ "cancelled",
1121
+ "action_required",
1122
+ "startup_failure"
1123
+ ]);
1124
+ /**
1125
+ * State of a check run reported as a status plus a conclusion once completed.
1126
+ * Cancelled, timed-out, action-required and startup failures count as
1127
+ * failures; skipped and neutral runs as neutral.
1128
+ */
1129
+ function checkRunState(status, conclusion) {
1130
+ if (status !== "completed") return "pending";
1131
+ if (conclusion === "success") return "success";
1132
+ if (conclusion && FAILED_CONCLUSIONS.has(conclusion)) return "failure";
1133
+ return conclusion === "neutral" || conclusion === "skipped" ? "neutral" : "unknown";
1134
+ }
1135
+ /** Maps a forge's own file-change word onto {@link FileStatus}; unknown words become `'changed'`. */
1136
+ function toFileStatus(raw) {
1137
+ switch (raw?.toLowerCase()) {
1138
+ case "added":
1139
+ case "new":
1140
+ case "add": return "added";
1141
+ case "removed":
1142
+ case "deleted":
1143
+ case "remove": return "removed";
1144
+ case "renamed":
1145
+ case "rename": return "renamed";
1146
+ case "copied":
1147
+ case "copy": return "copied";
1148
+ case "modified":
1149
+ case "edit":
1150
+ case "change": return "modified";
1151
+ default: return "changed";
1152
+ }
1153
+ }
1154
+ /**
1155
+ * Caches the result of `load` after its first call. A rejected load is
1156
+ * forgotten so the next call retries; with `ttl` (milliseconds) a resolved
1157
+ * value is reloaded once it is older than that.
1158
+ */
1159
+ function memo(load, ttl) {
1160
+ let cached;
1161
+ return () => {
1162
+ if (!cached || ttl !== void 0 && Date.now() - cached.at > ttl) {
1163
+ const promise = load();
1164
+ cached = {
1165
+ promise,
1166
+ at: Date.now()
1167
+ };
1168
+ promise.catch(() => {
1169
+ if (cached?.promise === promise) cached = void 0;
1170
+ });
1171
+ }
1172
+ return cached.promise;
1173
+ };
1174
+ }
1175
+ /** {@link memo} per key. */
1176
+ function memoBy(load) {
1177
+ const cache = /* @__PURE__ */ new Map();
1178
+ return (key) => {
1179
+ let entry = cache.get(key);
1180
+ if (!entry) {
1181
+ entry = memo(() => load(key));
1182
+ cache.set(key, entry);
1183
+ }
1184
+ return entry();
1185
+ };
1186
+ }
1187
+ /**
1188
+ * A review standing in for an approval, vote or participant state on a forge
1189
+ * that has no review objects. `comments` is `false` because there is nothing
1190
+ * to hang inline comments on.
1191
+ */
1192
+ function syntheticReview(thread, id, state, extras) {
1193
+ const { author, stateRaw, submittedAt, raw } = extras;
1194
+ return {
1195
+ ref: {
1196
+ forge: thread.forge,
1197
+ instance: thread.instance,
1198
+ thread,
1199
+ id
1200
+ },
1201
+ author,
1202
+ state,
1203
+ stateRaw,
1204
+ submittedAt,
1205
+ comments: false,
1206
+ raw
1207
+ };
1208
+ }
1209
+ /** A label colour as six hex digits, with the `#` prefix the forge expects. `ededed` when none is given. */
1210
+ function hexColour(colour, prefix = "") {
1211
+ return `${prefix}${(colour ?? "ededed").replace(/^#/, "")}`;
1212
+ }
1213
+ export { ForbiddenError as $, resolveToken as A, versionAtLeast as B, parseLinkHeader as C, rateLimitReset as D, rateLimitPart as E, toDate as F, isUnsupported as G, REACTION_CONTENTS as H, toFileStatus as I, reactionContent as J, namespaceRef as K, toPage as L, summariseChecks as M, syntheticReview as N, requireIssueOrPull as O, teamOrg as P, ContentNotTextError as Q, toPullStats as R, milestoneId as S, rateLimitOf as T, isNamespaceRef as U, withEtag as V, isResolvedThread as W, AuthenticationRequiredError as X, repoRef as Y, BranchMovedError as Z, latestCommentOf as _, createFetcher as a, MergeConflictError as at, memoBy as b, degradesToWarning as c, ReadOnlyError as ct, getManyConcurrently as d, UnsupportedOperationError as dt, ForgeApiError as et, hasEveryLabel as f, WebhookVerificationError as ft, iteratePages as g, isFirstPage as h, toMergeError as ht, checkRunState as i, MergeBlockedError as it, sleep as j, requireThread as k, firstPageEtag as l, TokenRevokedError as lt, hostOf as m, soleMergeMethod as mt, actorLogin as n, ForgeTimeoutError as nt, createListing as o, NotFoundError as ot, hexColour as p, isSecondaryRateLimit as pt, normaliseRepoName as q, anySignal as r, InsufficientScopeError as rt, createRequest as s, RateLimitedError as st, abortable as t, ForgeError as tt, forgeIterable as u, UnresolvedThreadError as ut, mapConcurrent as v, phased as w, mergeCommitMessage as x, memo as y, toWarning as z };