@vite-hub/forge 0.1.0 → 0.3.1

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 (29) hide show
  1. package/README.md +43 -7
  2. package/dist/{association-Cm0dUTDU-CDDhJnIh.js → association-Ds6Tgs0W-Cu9_YCGq.js} +1 -1
  3. package/dist/build/node.d.ts +12 -0
  4. package/dist/build/node.js +106 -0
  5. package/dist/build.d.ts +2 -0
  6. package/dist/build.js +2 -0
  7. package/dist/{events-saDWbqbf-VX_k8jtr.js → events-C6C7lk1x-J8VCAjEX.js} +4 -4
  8. package/dist/{events-DudKM7vq-Cj_PCDdt.js → events-DW3SFUDA-D2rhS9D-.js} +4 -4
  9. package/dist/{events-CeChclTf-CX-gD8oy.js → events-DjRw3KSr-C72gY7Vu.js} +4 -4
  10. package/dist/{events-CRaLy7U3-3PNNp5WZ.js → events-DmSWTdpS-BdJBABfI.js} +4 -4
  11. package/dist/{events-7EBoeIPd-A2RUkJi5.js → events-uCMi3LHU-Bz79PQtq.js} +4 -4
  12. package/dist/{feed-Dyf730Ys-D0HgBba6.js → feed-BlzdKdNv-DbxuSgsx.js} +4 -4
  13. package/dist/{feed-DsC7Vws1-M_de2nSK.js → feed-BwdcTgZq-Bm_c8br8.js} +4 -4
  14. package/dist/{feed-CmBoYS3Z-CuC4i0fH.js → feed-CIaAZINm-Dpe9DxwK.js} +4 -4
  15. package/dist/{forgejo-BN8ItCfl.js → forgejo-UNPc42cY.js} +50 -8
  16. package/dist/{gitee-DExkQP6X-BxJS2dRY.js → gitee-BXyl2_3W-dQOAjWqr.js} +2 -2
  17. package/dist/{github-DtncTfmv.js → github-CUiEF2FK.js} +65 -40
  18. package/dist/{gitlab-BoDm8-BC.js → gitlab-zvWb9zOi.js} +65 -8
  19. package/dist/{graphql-DG5aJBT3-DceyFYdM.js → graphql-BDhuP5jN-BSpB8lWf.js} +59 -7
  20. package/dist/identity-CNTWZZuv.d.ts +27 -0
  21. package/dist/identity-CmVEBLP5.js +38 -0
  22. package/dist/index.d.ts +332 -110
  23. package/dist/index.js +815 -313
  24. package/dist/{knot-BpyTK9D7-CVIsX4I2.js → knot-bGebBK_B-CeDHcJUz.js} +16 -9
  25. package/dist/{tangled-DPt_0u21-zS41xdG5.js → tangled-8lg_73Wi-bSufNXiN.js} +1 -1
  26. package/dist/{templates-Bn8a-pd2-D9DhJEVD.js → templates-BGDqQMu4-PSB43E1j.js} +2 -2
  27. package/dist/{utils-CA_4WJhJ-DNgT61X2.js → utils-DC7MBR65-B7Vr2hFm.js} +3 -306
  28. package/dist/{webhooks-DgHwxxYz-D1V2LOr1.js → webhooks-Bc6QhmI8-CNgCERCq.js} +326 -5
  29. package/package.json +19 -8
package/dist/index.js CHANGED
@@ -1,8 +1,33 @@
1
- import { a as ForgeApiError, d as NotFoundError, f as RateLimitedError, l as MergeBlockedError, n as BranchMovedError, s as ForgeTimeoutError, yt as repoRef } from "./utils-CA_4WJhJ-DNgT61X2.js";
1
+ import { a as ForgeApiError, d as NotFoundError, f as RateLimitedError, l as MergeBlockedError, mt as repoRef, n as BranchMovedError, s as ForgeTimeoutError } from "./utils-DC7MBR65-B7Vr2hFm.js";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { defineErrors, isRuntimeDiagnostic } from "@vite-hub/runtime";
2
4
  import { defineDiagnostics } from "nostics";
3
- import { Buffer } from "node:buffer";
4
5
  import { createHash } from "node:crypto";
5
- //#region src/env.ts
6
+ import { Buffer } from "node:buffer";
7
+ //#region ../internal/src/runtime/cloudflare-env-lookup.ts
8
+ /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
9
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
10
+ let activeEnv;
11
+ /** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
12
+ function getScopedCloudflareEnv() {
13
+ return globalThis[activeEnvStorageKey]?.getStore();
14
+ }
15
+ function getActiveCloudflareEnv() {
16
+ const scoped = getScopedCloudflareEnv();
17
+ if (scoped) return scoped.env;
18
+ const host = globalThis;
19
+ return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
20
+ }
21
+ //#endregion
22
+ //#region ../internal/src/runtime/cloudflare-env.ts
23
+ const runtimeGlobal = globalThis;
24
+ runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
25
+ function getActiveCloudflareBinding(name) {
26
+ const env = getActiveCloudflareEnv();
27
+ return env && Object.hasOwn(env, name) ? env[name] : void 0;
28
+ }
29
+ //#endregion
30
+ //#region ../internal/src/forge.ts
6
31
  /**
7
32
  * Server Env of each Forge, keyed by the `env.server.<forge>.<field>` path.
8
33
  * Channels, Capabilities, Workspaces and Sources read the same names.
@@ -59,56 +84,199 @@ const forgeEnv = {
59
84
  function readForgeEnv(field, env = globalThis.process?.env ?? {}) {
60
85
  for (const name of field.names) {
61
86
  const value = typeof env === "function" ? env(name) : env[name];
62
- if (!isString(value)) continue;
87
+ if (typeof value !== "string") continue;
63
88
  const trimmed = value.trim();
64
89
  if (trimmed) return trimmed;
65
90
  }
66
91
  }
67
- function isString(value) {
68
- return typeof value === "string";
92
+ /** The HTTP status of a failed Forge request, or undefined for other errors. */
93
+ function forgeErrorStatus(error) {
94
+ if (!(error instanceof Error) || !("status" in error)) return void 0;
95
+ return typeof error.status === "number" ? error.status : void 0;
69
96
  }
70
97
  //#endregion
98
+ //#region src/errors.ts
99
+ const forgeErrors = /*#__PURE__*/ defineErrors({
100
+ docs: "https://vitehub.dev/docs/forge/diagnostics",
101
+ codes: {
102
+ FORGE_APP_NOT_INSTALLED: {
103
+ why: ({ repository }) => `The GitHub App is not installed on ${repository}.`,
104
+ fix: "Install the GitHub App on the repository, or map its owner to an installation that can reach it in VITEHUB_GITHUB_APP_INSTALLATIONS."
105
+ },
106
+ FORGE_REQUEST_FAILED: {
107
+ why: ({ operation, status }) => status === void 0 ? `${operation} failed.` : `${operation} failed with HTTP ${status}.`,
108
+ fix: "Read `error.cause` for the Forge error. A 401 means that the App ID, the private key, or the token is wrong. Retry after a 5xx or a network error."
109
+ },
110
+ FORGE_MISSING_ENV: {
111
+ why: ({ forge, names }) => `The ${forge} Forge has no credentials. It reads ${names}.`,
112
+ fix: "Set the variables in the host environment, or pass `env` to `useForge()`."
113
+ },
114
+ FORGE_INVALID_ENV: {
115
+ why: ({ name, problem }) => `${name} ${problem}.`,
116
+ fix: "Correct the variable in the host environment."
117
+ },
118
+ FORGE_MISSING_INSTALLATION: {
119
+ why: "The GitHub App needs an installation. The call has no `repository`, and VITEHUB_GITHUB_INSTALLATION_ID is not set.",
120
+ fix: "Pass `{ repository: 'owner/name' }`, or set VITEHUB_GITHUB_INSTALLATION_ID with VITEHUB_GITHUB_APP_OWNER."
121
+ },
122
+ FORGE_NOT_APP: {
123
+ why: "`forge.app()` needs a GitHub App, and this Forge uses a token.",
124
+ fix: "Set VITEHUB_GITHUB_APP_ID with VITEHUB_GITHUB_PRIVATE_KEY or VITEHUB_GITHUB_PRIVATE_KEY_PATH, or check `forge.auth` before you call `app()`."
125
+ }
126
+ }
127
+ });
128
+ //#endregion
71
129
  //#region src/error-diagnostics.ts
72
130
  const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
73
131
  const forgeDiagnostics = /*#__PURE__*/ defineDiagnostics({
74
- docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
132
+ docsBase: "https://vitehub.dev/docs/forge/diagnostics",
75
133
  codes: {
76
134
  /** The GitHub App installation lookup failed or the App is not installed. */
77
- FORGE_R0001: dynamicError,
135
+ FORGE_R0001: {
136
+ ...dynamicError,
137
+ fix: "Install the GitHub App on the repository that the message names, and check that the app credentials can read it. For a failed request, `error.cause` holds the GitHub answer."
138
+ },
78
139
  /** `forgeArchive()` was called for a Forge without archive support. */
79
- FORGE_R0002: dynamicError,
140
+ FORGE_R0002: {
141
+ ...dynamicError,
142
+ fix: "Call `forgeArchive()` with a GitHub provider, because other forges have no archive download here."
143
+ },
80
144
  /** `forgeGitCredentials()` received an invalid base URL or repository. */
81
- FORGE_R0003: dynamicError,
145
+ FORGE_R0003: {
146
+ ...dynamicError,
147
+ fix: "Pass a forge base URL that starts with `https://` or `http://`, and a repository as `owner/name`."
148
+ },
82
149
  /** `forgeBlob()` was called for a Forge without blob reads. */
83
- FORGE_R0004: dynamicError,
150
+ FORGE_R0004: {
151
+ ...dynamicError,
152
+ fix: "Call `forgeBlob()` with a GitHub provider, because other forges cannot read a blob by sha here."
153
+ },
84
154
  /** `forgeCommitFiles()` received a file mode for a Forge without file mode writes. */
85
- FORGE_R0005: dynamicError,
155
+ FORGE_R0005: {
156
+ ...dynamicError,
157
+ fix: "Remove `mode` from the file changes, or commit them with a GitHub provider."
158
+ },
86
159
  /** A GitHub-only Forge helper received a provider for another Forge. */
87
- FORGE_R0006: dynamicError,
160
+ FORGE_R0006: {
161
+ ...dynamicError,
162
+ fix: "Call the helper that the message names with a GitHub provider."
163
+ },
88
164
  /** `githubBranchRuleDetails()` got branch rules that are not complete GitHub rulesets or classic protection. */
89
- FORGE_R0007: dynamicError,
90
- /** GitHub did not return complete review threads. */
91
- FORGE_R0008: dynamicError,
165
+ FORGE_R0007: {
166
+ ...dynamicError,
167
+ fix: "Read the branch rules with a GitHub token that can read the branch protection and rulesets of the repository, and pass the result of `provider.repos.branchRules()` unchanged."
168
+ },
92
169
  /** A GitHub-only Forge helper received a reference that is not a numbered pull request, or an empty input. */
93
- FORGE_R0009: dynamicError
170
+ FORGE_R0009: {
171
+ ...dynamicError,
172
+ fix: "Pass a pull request thread with a `number` and a nonempty base branch. For `forgeMerge({ bypassRules })`, also pass `method` and `sha`."
173
+ },
174
+ FORGE_RESPONSE_INVALID: {
175
+ why: ({ problem }) => problem,
176
+ fix: "Check that the GitHub App, the token, or the forge webhook can read the resource that the message names, then retry. A retry helps when the forge was only unavailable."
177
+ },
178
+ FORGE_UNSUPPORTED: {
179
+ why: "Unsupported Forge.",
180
+ fix: "Set `forge` of the Forge connection to `github`, `gitlab`, or `forgejo`."
181
+ }
94
182
  }
95
183
  });
96
184
  //#endregion
97
- //#region src/gaps/archive.ts
185
+ //#region src/conditional.ts
186
+ const storedHeaders = [
187
+ "content-type",
188
+ "link",
189
+ "last-modified"
190
+ ];
191
+ const bodyHeaders = [
192
+ "content-length",
193
+ "content-encoding",
194
+ "transfer-encoding"
195
+ ];
196
+ /** An in-memory LRU of Forge responses, bounded by the total size of the bodies it keeps. */
197
+ function forgeMemoryCache(options = {}) {
198
+ const maxSize = options.maxSize ?? 33554432;
199
+ const maxEntrySize = options.maxEntrySize ?? 1048576;
200
+ const entries = /* @__PURE__ */ new Map();
201
+ let size = 0;
202
+ const remove = (key) => {
203
+ const entry = entries.get(key);
204
+ if (!entry) return;
205
+ entries.delete(key);
206
+ size -= entry.body.length;
207
+ };
208
+ return {
209
+ get(key) {
210
+ const entry = entries.get(key);
211
+ if (!entry) return void 0;
212
+ entries.delete(key);
213
+ entries.set(key, entry);
214
+ return entry;
215
+ },
216
+ set(key, value) {
217
+ remove(key);
218
+ if (value.body.length > maxEntrySize) return;
219
+ entries.set(key, value);
220
+ size += value.body.length;
221
+ while (size > maxSize) remove(entries.keys().next().value);
222
+ },
223
+ delete: remove
224
+ };
225
+ }
226
+ const sharedCache = forgeMemoryCache();
98
227
  /**
99
- * The repository tree at `ref` as a gzipped tarball stream.
100
- * Gap: `forges` has no `contents.archive()`. Proposed upstream as `provider.contents.archive(repo, options)`.
228
+ * Wrap `fetch` so authenticated GETs send `If-None-Match` with the ETag of the last response, and a `304`
229
+ * returns that response's body again. GitHub does not count a `304` against the primary rate limit.
230
+ * Every read still reaches the Forge, so a cached body is only returned when the Forge says it is current.
101
231
  */
102
- async function forgeArchive(provider, repo, options) {
103
- if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0002({ message: `Repository archives are not supported for ${provider.forge}.` });
104
- const owner = encodeURIComponent(repo.owner);
105
- const name = encodeURIComponent(repo.name);
106
- const ref = options.ref.split("/").map(encodeURIComponent).join("/");
107
- const path = provider.authKind === "anonymous" && provider.baseUrl.replace(/\/+$/, "") === "https://api.github.com" ? `https://codeload.github.com/${owner}/${name}/tar.gz/${ref}` : `/repos/${owner}/${name}/tarball/${ref}`;
108
- return (await provider.request("GET", path, {
109
- raw: true,
110
- signal: options.signal
111
- })).body;
232
+ function conditionalFetch(fetcher, options = {}) {
233
+ const cache = options.cache ?? sharedCache;
234
+ return async (input, init) => {
235
+ const request = input instanceof Request ? input : void 0;
236
+ const method = (init?.method ?? request?.method ?? "GET").toUpperCase();
237
+ const headers = new Headers(request?.headers);
238
+ for (const [name, value] of new Headers(init?.headers)) headers.set(name, value);
239
+ const authorization = headers.get("authorization");
240
+ if (method !== "GET" || !authorization || headers.has("if-none-match") || headers.has("if-modified-since")) return await fetcher(input, init);
241
+ const url = request?.url ?? String(input);
242
+ const key = createHash("sha256").update(`${options.identity ?? authorization}\0${url}\0${headers.get("accept") ?? ""}`).digest("base64url");
243
+ const cached = cache.get(key);
244
+ if (cached) headers.set("if-none-match", cached.etag);
245
+ const response = await fetcher(input, {
246
+ ...init,
247
+ headers
248
+ });
249
+ if (response.status === 304 && cached) {
250
+ const merged = new Headers(cached.headers);
251
+ for (const [name, value] of response.headers) if (!bodyHeaders.includes(name)) merged.set(name, value);
252
+ return new Response(cached.body, {
253
+ status: 200,
254
+ statusText: "OK",
255
+ headers: merged
256
+ });
257
+ }
258
+ const etag = response.headers.get("etag");
259
+ if (response.status !== 200 || !etag || response.redirected || !response.headers.get("content-type")?.includes("json")) {
260
+ if (cached) cache.delete(key);
261
+ return response;
262
+ }
263
+ const body = await response.text();
264
+ cache.set(key, {
265
+ etag,
266
+ body,
267
+ headers: storedHeaders.flatMap((name) => {
268
+ const value = response.headers.get(name);
269
+ return value === null ? [] : [[name, value]];
270
+ })
271
+ });
272
+ const copy = new Headers(response.headers);
273
+ for (const name of bodyHeaders) copy.delete(name);
274
+ return new Response(body, {
275
+ status: response.status,
276
+ statusText: response.statusText,
277
+ headers: copy
278
+ });
279
+ };
112
280
  }
113
281
  //#endregion
114
282
  //#region src/provider.ts
@@ -117,9 +285,11 @@ async function forgeProvider(connection) {
117
285
  type: "token",
118
286
  token: connection.token
119
287
  } : { type: "anonymous" };
288
+ const conditional = connection.conditionalRequests ?? connection.forge === "github";
289
+ const fetcher = conditional ? conditionalFetch(connection.fetch ?? ((input, init) => globalThis.fetch(input, init)), conditional === true ? {} : conditional) : connection.fetch;
120
290
  const options = {
121
291
  ...connection.baseUrl ? { baseUrl: connection.baseUrl } : {},
122
- ...connection.fetch ? { fetch: connection.fetch } : {},
292
+ ...fetcher ? { fetch: fetcher } : {},
123
293
  userAgent: connection.userAgent ?? "vitehub",
124
294
  ...connection.timeout === void 0 ? {} : { timeout: connection.timeout },
125
295
  ...connection.readOnly === void 0 ? {} : { readOnly: connection.readOnly },
@@ -127,28 +297,27 @@ async function forgeProvider(connection) {
127
297
  };
128
298
  switch (connection.forge) {
129
299
  case "github": {
130
- const { github } = await import("./github-DtncTfmv.js");
300
+ const { github } = await import("./github-CUiEF2FK.js");
131
301
  return github(options);
132
302
  }
133
303
  case "gitlab": {
134
- const { gitlab } = await import("./gitlab-BoDm8-BC.js");
304
+ const { gitlab } = await import("./gitlab-zvWb9zOi.js");
135
305
  return gitlab(options);
136
306
  }
137
307
  case "forgejo": {
138
- const { forgejo } = await import("./forgejo-BN8ItCfl.js");
308
+ const { forgejo } = await import("./forgejo-UNPc42cY.js");
139
309
  return forgejo(options);
140
310
  }
141
311
  }
142
- throw new Error("Unsupported Forge.");
312
+ throw forgeDiagnostics.FORGE_UNSUPPORTED();
143
313
  }
144
- /** A Forge response that succeeded but did not include the expected data. */
145
- var ForgeResponseError = class extends Error {
146
- name = "ForgeResponseError";
147
- };
148
- /** The HTTP status of a failed Forge request, or undefined for other errors. */
149
- function forgeErrorStatus(error) {
150
- if (!(error instanceof Error) || !("status" in error)) return void 0;
151
- return typeof error.status === "number" ? error.status : void 0;
314
+ /** A Forge response that succeeded but did not include the expected data: `FORGE_RESPONSE_INVALID`. */
315
+ function forgeResponseError(problem) {
316
+ return forgeDiagnostics.FORGE_RESPONSE_INVALID({ problem });
317
+ }
318
+ /** Whether a Forge response did not include the expected data. */
319
+ function isForgeResponseError(error) {
320
+ return error instanceof Error && Reflect.get(error, "code") === "FORGE_RESPONSE_INVALID";
152
321
  }
153
322
  /** The error that a cancelled Forge operation rejects with. */
154
323
  function abortError(signal) {
@@ -175,17 +344,458 @@ async function withSignal(promise, signal) {
175
344
  });
176
345
  }
177
346
  //#endregion
347
+ //#region ../internal/src/object.ts
348
+ /** A non-null object that is not an array. Functions do not pass. */
349
+ function isRecord(value) {
350
+ return typeof value === "object" && value !== null && !Array.isArray(value);
351
+ }
352
+ //#endregion
353
+ //#region src/github-app.ts
354
+ const appProviders = /* @__PURE__ */ new Map();
355
+ const installationTokens = /* @__PURE__ */ new WeakMap();
356
+ const appProviderLimit = 128;
357
+ const fetchIds = /* @__PURE__ */ new WeakMap();
358
+ let nextFetchId = 0;
359
+ function fetchId(fetcher) {
360
+ if (!fetcher) return 0;
361
+ let id = fetchIds.get(fetcher);
362
+ if (id === void 0) {
363
+ id = ++nextFetchId;
364
+ fetchIds.set(fetcher, id);
365
+ }
366
+ return id;
367
+ }
368
+ function appProviderKey(input, installationId) {
369
+ return createHash("sha256").update(`${input.baseUrl || "https://api.github.com"}\0${input.appId}\0${input.privateKey}\0${input.userAgent ?? ""}\0${fetchId(input.fetch)}\0${installationId}`).digest("hex");
370
+ }
371
+ /**
372
+ * One App provider per installation, so `refresh` replaces the token of that installation only.
373
+ * App-level requests use the entry with an empty installation ID.
374
+ */
375
+ function appProvider(input, installationId = "", refresh = false) {
376
+ const key = appProviderKey(input, installationId);
377
+ if (refresh) appProviders.delete(key);
378
+ const cached = appProviders.get(key);
379
+ if (cached) return cached;
380
+ const pending = import("./github-CUiEF2FK.js").then(({ github }) => github({
381
+ ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
382
+ ...input.fetch ? { fetch: input.fetch } : {},
383
+ userAgent: input.userAgent ?? "vitehub",
384
+ auth: {
385
+ type: "app",
386
+ appId: input.appId,
387
+ privateKey: input.privateKey
388
+ }
389
+ }));
390
+ pending.catch(() => appProviders.delete(key));
391
+ appProviders.set(key, pending);
392
+ if (appProviders.size > appProviderLimit) appProviders.delete(appProviders.keys().next().value);
393
+ return pending;
394
+ }
395
+ function positiveId(value) {
396
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
397
+ }
398
+ /**
399
+ * GitHub App credentials. App providers are cached per API base, App, private key, user agent,
400
+ * fetch function, and installation, so installation tokens are minted once and reused until they expire.
401
+ */
402
+ function githubAppCredentials(input) {
403
+ return {
404
+ async installationToken(installationId, options = {}) {
405
+ const id = String(installationId);
406
+ const provider = await withSignal(appProvider(input, id, options.refresh), options.signal);
407
+ const cached = installationTokens.get(provider);
408
+ if (cached && cached.expiresAt > Date.now() + Math.max(options.minLifetime ?? 0, 6e4)) return {
409
+ token: cached.token,
410
+ expiresAt: new Date(cached.expiresAt)
411
+ };
412
+ const response = await withSignal(provider.request("POST", `/app/installations/${id}/access_tokens`, { signal: options.signal }), options.signal);
413
+ if (!response.data.token) throw forgeResponseError("GitHub App installation token response did not include token.");
414
+ const details = {
415
+ token: response.data.token,
416
+ expiresAt: new Date(response.data.expires_at)
417
+ };
418
+ installationTokens.set(provider, {
419
+ token: details.token,
420
+ expiresAt: details.expiresAt.getTime()
421
+ });
422
+ return details;
423
+ },
424
+ async installation(repository, signal) {
425
+ const provider = await withSignal(appProvider(input), signal);
426
+ const path = `/repos/${repository}/installation`;
427
+ try {
428
+ const response = await provider.request("GET", path, { signal });
429
+ const id = positiveId(isRecord(response.data) ? response.data.id : void 0);
430
+ if (!id) throw forgeDiagnostics.FORGE_R0001({ message: `GitHub App is not installed for ${repository}.` });
431
+ return id;
432
+ } catch (error) {
433
+ if (signal?.aborted) throw abortError(signal);
434
+ const status = forgeErrorStatus(error);
435
+ if (status === void 0) throw error;
436
+ throw forgeDiagnostics.FORGE_R0001({
437
+ message: `GitHub App request ${path} failed with ${status}.`,
438
+ cause: error
439
+ });
440
+ }
441
+ },
442
+ async app(signal) {
443
+ const response = await (await withSignal(appProvider(input), signal)).request("GET", "/app", { signal });
444
+ const id = positiveId(isRecord(response.data) ? response.data.id : void 0);
445
+ const slug = isRecord(response.data) && typeof response.data.slug === "string" ? response.data.slug : void 0;
446
+ if (!id) throw forgeResponseError("GitHub App metadata did not include an ID.");
447
+ if (!slug) throw forgeResponseError("GitHub App response did not include a slug.");
448
+ return {
449
+ id,
450
+ slug,
451
+ login: `${slug}[bot]`
452
+ };
453
+ },
454
+ async repositories(signal) {
455
+ const provider = await withSignal(appProvider(input), signal);
456
+ const repositories = [];
457
+ for await (const installation of provider.installations.list({
458
+ perPage: 100,
459
+ signal
460
+ })) {
461
+ const installationId = positiveId(Number(installation.id));
462
+ if (!installationId || isRecord(installation.raw) && installation.raw.suspended_at) continue;
463
+ for await (const repo of provider.installations.repos(installation, {
464
+ perPage: 100,
465
+ signal
466
+ })) repositories.push({
467
+ repository: `${repo.ref.owner}/${repo.ref.name}`,
468
+ installationId,
469
+ archived: repo.isArchived
470
+ });
471
+ }
472
+ return repositories;
473
+ },
474
+ async failedDeliveries(since, signal) {
475
+ const provider = await withSignal(appProvider(input), signal);
476
+ const attempts = [];
477
+ let cursor;
478
+ for (let page = 0; page < 200; page++) {
479
+ const response = await provider.request("GET", "/app/hook/deliveries", {
480
+ query: {
481
+ per_page: 100,
482
+ ...cursor ? { cursor } : {}
483
+ },
484
+ signal,
485
+ raw: true
486
+ });
487
+ const data = JSON.parse((await new Response(response.body).text()).replace(/"id":\s*(\d+)/g, "\"id\":\"$1\""));
488
+ const items = Array.isArray(data) ? data.flatMap(delivery) : [];
489
+ attempts.push(...items);
490
+ cursor = /[?&]cursor=([^&>]+)[^>]*>;\s*rel="next"/.exec(response.headers.get("link") ?? "")?.[1];
491
+ if (!cursor || !items.length || items.at(-1).deliveredAt < since) break;
492
+ }
493
+ const recent = attempts.filter((item) => item.deliveredAt >= since);
494
+ const delivered = new Set(recent.filter((item) => item.statusCode >= 200 && item.statusCode < 300).map((item) => item.guid));
495
+ const failed = /* @__PURE__ */ new Map();
496
+ for (const item of recent) {
497
+ if (delivered.has(item.guid)) continue;
498
+ const seen = failed.get(item.guid);
499
+ failed.set(item.guid, seen ? {
500
+ ...seen.deliveredAt > item.deliveredAt ? seen : item,
501
+ attempts: seen.attempts + 1
502
+ } : item);
503
+ }
504
+ return [...failed.values()].sort((a, b) => a.deliveredAt - b.deliveredAt);
505
+ },
506
+ async redeliver(id, signal) {
507
+ await (await withSignal(appProvider(input), signal)).request("POST", `/app/hook/deliveries/${id}/attempts`, { signal });
508
+ }
509
+ };
510
+ }
511
+ function delivery(value) {
512
+ if (!isRecord(value)) return [];
513
+ const id = typeof value.id === "string" && /^[1-9]\d*$/.test(value.id) ? value.id : void 0;
514
+ const deliveredAt = typeof value.delivered_at === "string" ? Date.parse(value.delivered_at) : NaN;
515
+ if (!id || typeof value.guid !== "string" || typeof value.event !== "string" || typeof value.status_code !== "number" || Number.isNaN(deliveredAt)) return [];
516
+ return [{
517
+ id,
518
+ guid: value.guid,
519
+ event: value.event,
520
+ ...typeof value.action === "string" ? { action: value.action } : {},
521
+ deliveredAt,
522
+ statusCode: value.status_code,
523
+ attempts: 1
524
+ }];
525
+ }
526
+ /** Read a GitHub App private key from an inline value or a file path. Escaped "\\n" becomes a newline. */
527
+ async function readGitHubAppPrivateKey(inline, path) {
528
+ const value = inline?.trim();
529
+ if (value) return value.replace(/\\n/g, "\n");
530
+ if (!path) return void 0;
531
+ const { readFile } = await import(
532
+ /* @vite-ignore */
533
+ "node:fs/promises"
534
+ );
535
+ const file = (await readFile(path, "utf8")).trim();
536
+ return file ? file.replace(/\\n/g, "\n") : void 0;
537
+ }
538
+ //#endregion
539
+ //#region src/github-installations.ts
540
+ const names = {
541
+ installationId: forgeEnv.github.installationId.names[0],
542
+ appOwner: forgeEnv.github.appOwner.names[0],
543
+ appInstallations: forgeEnv.github.appInstallations.names[0]
544
+ };
545
+ function installationNumber(value, name) {
546
+ const id = typeof value === "string" && value.trim() ? Number(value) : value;
547
+ if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0) throw forgeErrors.FORGE_INVALID_ENV({
548
+ name,
549
+ problem: "must be a positive integer"
550
+ });
551
+ return id;
552
+ }
553
+ /**
554
+ * Reads the installation routing from Server Env values. Throws `FORGE_INVALID_ENV` when
555
+ * `VITEHUB_GITHUB_INSTALLATION_ID` has no `VITEHUB_GITHUB_APP_OWNER`, because an installation belongs to one owner.
556
+ */
557
+ function githubInstallationRouting(env) {
558
+ const owner = env.appOwner?.trim().toLowerCase() || void 0;
559
+ const fixed = env.installationId?.trim() || void 0;
560
+ if (fixed !== void 0 && owner === void 0) throw forgeErrors.FORGE_INVALID_ENV({
561
+ name: names.installationId,
562
+ problem: `needs ${names.appOwner}, the repository owner of that installation. For more owners, set ${names.appInstallations}`
563
+ });
564
+ let installations = {};
565
+ const mappings = env.appInstallations?.trim();
566
+ if (mappings) {
567
+ let parsed;
568
+ try {
569
+ parsed = JSON.parse(mappings);
570
+ } catch {
571
+ parsed = void 0;
572
+ }
573
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw forgeErrors.FORGE_INVALID_ENV({
574
+ name: names.appInstallations,
575
+ problem: "must be a JSON object that maps repository owners to installation IDs, such as {\"acme\":123}"
576
+ });
577
+ installations = Object.fromEntries(Object.entries(parsed).map(([name, id]) => [name.toLowerCase(), installationNumber(id, `${names.appInstallations} entry "${name}"`)]));
578
+ }
579
+ return {
580
+ ...fixed === void 0 ? {} : { installationId: installationNumber(fixed, names.installationId) },
581
+ ...owner === void 0 ? {} : { owner },
582
+ installations
583
+ };
584
+ }
585
+ /**
586
+ * The configured installation for `repository`: its owner in `installations`, else the fixed installation when the
587
+ * owner matches. Without `repository`, the fixed installation. `undefined` means: ask GitHub which installation can
588
+ * reach the repository.
589
+ */
590
+ function githubInstallationFor(routing, repository) {
591
+ if (repository === void 0) return routing.installationId;
592
+ const owner = repository.split("/", 1)[0].toLowerCase();
593
+ return (Object.hasOwn(routing.installations, owner) ? routing.installations[owner] : void 0) ?? (owner === routing.owner ? routing.installationId : void 0);
594
+ }
595
+ //#endregion
596
+ //#region src/use-forge.ts
597
+ function hostEnv(name) {
598
+ return getActiveCloudflareBinding(name) ?? globalThis.process?.env?.[name];
599
+ }
600
+ function primaryName(field) {
601
+ return field.names[0];
602
+ }
603
+ function readGitHubApp(env) {
604
+ const { github } = forgeEnv;
605
+ const appId = readForgeEnv(github.appId, env);
606
+ const privateKey = readForgeEnv(github.privateKey, env);
607
+ const privateKeyPath = readForgeEnv(github.privateKeyPath, env);
608
+ if (!appId && !privateKey && !privateKeyPath) return void 0;
609
+ if (!appId) throw forgeErrors.FORGE_MISSING_ENV({
610
+ forge: "github",
611
+ names: primaryName(github.appId)
612
+ });
613
+ if (!privateKey && !privateKeyPath) throw forgeErrors.FORGE_MISSING_ENV({
614
+ forge: "github",
615
+ names: `${primaryName(github.privateKey)} or ${primaryName(github.privateKeyPath)}`
616
+ });
617
+ return {
618
+ appId,
619
+ installations: githubInstallationRouting({
620
+ installationId: readForgeEnv(github.installationId, env),
621
+ appOwner: readForgeEnv(github.appOwner, env),
622
+ appInstallations: readForgeEnv(github.appInstallations, env)
623
+ }),
624
+ privateKey,
625
+ privateKeyPath
626
+ };
627
+ }
628
+ function requestFailed(operation, cause, signal) {
629
+ if (signal?.aborted) throw abortError(signal);
630
+ const status = forgeErrorStatus(cause) ?? (isRuntimeDiagnostic(cause) ? forgeErrorStatus(cause.cause) : void 0);
631
+ return forgeErrors.FORGE_REQUEST_FAILED({
632
+ cause,
633
+ operation,
634
+ ...status === void 0 ? {} : { status }
635
+ });
636
+ }
637
+ /**
638
+ * The Forge identity of this deployment, read from the same Server Env as Channels, Workspaces and Sources.
639
+ * GitHub uses a GitHub App when `VITEHUB_GITHUB_APP_ID` is set, and `VITEHUB_GITHUB_TOKEN` otherwise.
640
+ * Throws a config error when the env has no credentials. Runtime operations return `[error, data]`.
641
+ *
642
+ * ```ts
643
+ * const [error, provider] = await useForge().provider({ repository: "acme/web" })
644
+ * ```
645
+ */
646
+ function useForge(options = {}) {
647
+ const kind = options.forge ?? "github";
648
+ const env = options.env ?? hostEnv;
649
+ const fields = forgeEnv;
650
+ const githubApp = kind === "github" ? readGitHubApp(env) : void 0;
651
+ const configuredToken = githubApp ? void 0 : readForgeEnv(forgeEnv[kind].token, env);
652
+ const credential = githubApp ? { app: githubApp } : configuredToken ? { token: configuredToken } : void 0;
653
+ if (!credential) {
654
+ const names = kind === "github" ? "VITEHUB_GITHUB_APP_ID with VITEHUB_GITHUB_PRIVATE_KEY or VITEHUB_GITHUB_PRIVATE_KEY_PATH, or VITEHUB_GITHUB_TOKEN" : primaryName(forgeEnv[kind].token);
655
+ throw forgeErrors.FORGE_MISSING_ENV({
656
+ forge: kind,
657
+ names
658
+ });
659
+ }
660
+ const baseField = fields[kind].baseUrl;
661
+ const baseUrl = options.baseUrl ?? (baseField ? readForgeEnv(baseField, env) : void 0);
662
+ const userAgent = options.userAgent ?? "vitehub";
663
+ let credentials;
664
+ function appCredentials(config) {
665
+ credentials ??= readGitHubAppPrivateKey(config.privateKey, config.privateKeyPath).then((privateKey) => {
666
+ if (!privateKey) throw forgeErrors.FORGE_INVALID_ENV({
667
+ name: primaryName(forgeEnv.github.privateKeyPath),
668
+ problem: `names an empty file: ${config.privateKeyPath}`
669
+ });
670
+ return githubAppCredentials({
671
+ appId: config.appId,
672
+ privateKey,
673
+ userAgent,
674
+ ...baseUrl ? { baseUrl } : {},
675
+ ...options.fetch ? { fetch: options.fetch } : {}
676
+ });
677
+ }, (cause) => {
678
+ throw forgeErrors.FORGE_INVALID_ENV({
679
+ cause,
680
+ name: primaryName(forgeEnv.github.privateKeyPath),
681
+ problem: `names a file that cannot be read: ${config.privateKeyPath}`
682
+ });
683
+ });
684
+ credentials.catch(() => {
685
+ credentials = void 0;
686
+ });
687
+ return credentials;
688
+ }
689
+ async function installationToken(config, call) {
690
+ const { repository, signal } = call;
691
+ const client = await appCredentials(config);
692
+ let installation = call.installation ?? githubInstallationFor(config.installations, repository);
693
+ if (installation === void 0) {
694
+ if (!repository) throw forgeErrors.FORGE_MISSING_INSTALLATION();
695
+ try {
696
+ installation = await client.installation(repository, signal);
697
+ } catch (cause) {
698
+ if (signal?.aborted) throw abortError(signal);
699
+ const lookup = isRuntimeDiagnostic(cause) && cause.code === "FORGE_R0001";
700
+ const status = lookup ? forgeErrorStatus(cause.cause) : void 0;
701
+ if (lookup && (status === void 0 || status === 404)) return [forgeErrors.FORGE_APP_NOT_INSTALLED({
702
+ cause,
703
+ repository
704
+ }), void 0];
705
+ return [requestFailed(`GET /repos/${repository}/installation`, cause, signal), void 0];
706
+ }
707
+ }
708
+ try {
709
+ const minted = await client.installationToken(installation, {
710
+ signal,
711
+ ...call.refresh ? { refresh: true } : {},
712
+ ...call.minLifetime === void 0 ? {} : { minLifetime: call.minLifetime }
713
+ });
714
+ return [void 0, {
715
+ token: minted.token,
716
+ expiresAt: minted.expiresAt,
717
+ identity: `app:${config.appId}:${installation}`
718
+ }];
719
+ } catch (cause) {
720
+ return [requestFailed(`POST /app/installations/${installation}/access_tokens`, cause, signal), void 0];
721
+ }
722
+ }
723
+ return {
724
+ kind,
725
+ auth: "app" in credential ? "app" : "token",
726
+ baseUrl,
727
+ async token(call = {}) {
728
+ if (call.signal?.aborted) throw abortError(call.signal);
729
+ if (!("app" in credential)) return [void 0, {
730
+ token: credential.token,
731
+ expiresAt: void 0
732
+ }];
733
+ const [error, minted] = await installationToken(credential.app, call);
734
+ return error ? [error, void 0] : [void 0, {
735
+ token: minted.token,
736
+ expiresAt: minted.expiresAt
737
+ }];
738
+ },
739
+ async provider(call = {}) {
740
+ if (call.signal?.aborted) throw abortError(call.signal);
741
+ const [error, minted] = "app" in credential ? await installationToken(credential.app, call) : [void 0, {
742
+ token: credential.token,
743
+ identity: void 0
744
+ }];
745
+ if (call.signal?.aborted) throw abortError(call.signal);
746
+ if (error) return [error, void 0];
747
+ const provider = await forgeProvider({
748
+ forge: kind,
749
+ token: minted.token,
750
+ userAgent,
751
+ ...options.conditionalRequests === false ? { conditionalRequests: false } : minted.identity ? { conditionalRequests: { identity: minted.identity } } : {},
752
+ ...baseUrl ? { baseUrl } : {},
753
+ ...options.fetch ? { fetch: options.fetch } : {}
754
+ });
755
+ if (call.signal?.aborted) throw abortError(call.signal);
756
+ return [void 0, provider];
757
+ },
758
+ async app(call = {}) {
759
+ if (!("app" in credential)) throw forgeErrors.FORGE_NOT_APP();
760
+ const client = await appCredentials(credential.app);
761
+ try {
762
+ return [void 0, await client.app(call.signal)];
763
+ } catch (cause) {
764
+ return [requestFailed("GET /app", cause, call.signal), void 0];
765
+ }
766
+ }
767
+ };
768
+ }
769
+ //#endregion
770
+ //#region src/gaps/archive.ts
771
+ /**
772
+ * The repository tree at `ref` as a gzipped tarball stream.
773
+ * Gap: `forges` has no `contents.archive()`. Proposed upstream as `provider.contents.archive(repo, options)`
774
+ * (https://github.com/danielroe/forges/issues/191).
775
+ */
776
+ async function forgeArchive(provider, repo, options) {
777
+ if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0002({ message: `Repository archives are not supported for ${provider.forge}.` });
778
+ const owner = encodeURIComponent(repo.owner);
779
+ const name = encodeURIComponent(repo.name);
780
+ const ref = options.ref.split("/").map(encodeURIComponent).join("/");
781
+ const path = provider.authKind === "anonymous" && provider.baseUrl.replace(/\/+$/, "") === "https://api.github.com" ? `https://codeload.github.com/${owner}/${name}/tar.gz/${ref}` : `/repos/${owner}/${name}/tarball/${ref}`;
782
+ return (await provider.request("GET", path, {
783
+ raw: true,
784
+ signal: options.signal
785
+ })).body;
786
+ }
787
+ //#endregion
178
788
  //#region src/gaps/blob.ts
179
789
  /**
180
790
  * The bytes of one Git blob, by its sha. The blob of a symlink holds the link target.
181
791
  * Gap: `forges` reads files by path only, and GitHub follows a symlink path to its target.
182
- * Proposed upstream as `provider.contents.blob(repo, sha, options)`.
792
+ * Proposed upstream as `provider.contents.blob(repo, sha, options)` (https://github.com/danielroe/forges/issues/295).
183
793
  */
184
794
  async function forgeBlob(provider, repo, sha, options = {}) {
185
795
  if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0004({ message: `Reading a blob by sha is not supported for ${provider.forge}.` });
186
796
  const { data } = await provider.request("GET", `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}/git/blobs/${encodeURIComponent(sha)}`, { signal: options.signal });
187
797
  const bytes = decodeBase64Blob(data);
188
- if (!bytes) throw new ForgeResponseError(`GitHub returned a malformed blob ${sha}.`);
798
+ if (!bytes) throw forgeResponseError(`GitHub returned a malformed blob ${sha}.`);
189
799
  return new Uint8Array(bytes);
190
800
  }
191
801
  function decodeBase64Blob(value) {
@@ -213,9 +823,6 @@ function isGitHubProvider(provider) {
213
823
  function repositoryPath$1(repo) {
214
824
  return `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
215
825
  }
216
- function isRecord$1(value) {
217
- return typeof value === "object" && value !== null && !Array.isArray(value);
218
- }
219
826
  //#endregion
220
827
  //#region src/gaps/branch-rules.ts
221
828
  const mergeMethods = {
@@ -232,12 +839,12 @@ function invalid(message) {
232
839
  */
233
840
  function githubBranchRuleDetails(rules) {
234
841
  const raw = rules.raw;
235
- if (!isRecord$1(raw) || !isRecord$1(raw.branch) || !Array.isArray(raw.rules)) throw invalid("Branch rules are not complete GitHub branch rules.");
842
+ if (!isRecord(raw) || !isRecord(raw.branch) || !Array.isArray(raw.rules)) throw invalid("Branch rules are not complete GitHub branch rules.");
236
843
  let requiredWorkflows = false;
237
844
  let allowed;
238
845
  for (const value of raw.rules) {
239
- if (!isRecord$1(value) || typeof value.type !== "string") throw invalid("Incomplete active branch rule.");
240
- const parameters = isRecord$1(value.parameters) ? value.parameters : void 0;
846
+ if (!isRecord(value) || typeof value.type !== "string") throw invalid("Incomplete active branch rule.");
847
+ const parameters = isRecord(value.parameters) ? value.parameters : void 0;
241
848
  if (value.type === "required_workflows") requiredWorkflows = true;
242
849
  else if (value.type === "workflows") {
243
850
  if (!Array.isArray(parameters?.workflows)) throw invalid("Incomplete ruleset workflow parameters.");
@@ -251,18 +858,18 @@ function githubBranchRuleDetails(rules) {
251
858
  }
252
859
  }
253
860
  if (typeof raw.branch.protected !== "boolean") throw invalid("Branch protection summary is incomplete.");
254
- const protection = isRecord$1(raw.branch.protection) ? raw.branch.protection : void 0;
861
+ const protection = isRecord(raw.branch.protection) ? raw.branch.protection : void 0;
255
862
  let classicSource = "unprotected-branch";
256
863
  if (raw.branch.protected === true) {
257
864
  if (!protection || typeof protection.enabled !== "boolean") throw invalid("Branch protection summary is incomplete.");
258
865
  if (protection.enabled !== true) throw invalid("Branch protection summary is incomplete.");
259
866
  const checks = protection.required_status_checks;
260
867
  if (checks !== void 0) {
261
- if (!isRecord$1(checks) || !Array.isArray(checks.contexts) || !checks.contexts.every((context) => typeof context === "string") || checks.checks !== void 0 && !Array.isArray(checks.checks)) throw invalid("Classic protection response is ambiguous; branch summary is incomplete.");
868
+ if (!isRecord(checks) || !Array.isArray(checks.contexts) || !checks.contexts.every((context) => typeof context === "string") || checks.checks !== void 0 && !Array.isArray(checks.checks)) throw invalid("Classic protection response is ambiguous; branch summary is incomplete.");
262
869
  if (checks.enforcement_level !== "everyone" && checks.enforcement_level !== "non_admins" && checks.enforcement_level !== "off") throw invalid("Classic protection response has an unsupported enforcement level.");
263
870
  const bound = Array.isArray(checks.checks) ? checks.checks : [];
264
871
  if (checks.enforcement_level === "off" && (checks.contexts.length > 0 || bound.length > 0)) throw invalid("Disabled classic checks contain required-check data.");
265
- if (bound.length > 0 && (bound.some((item) => !isRecord$1(item) || typeof item.context !== "string") || checks.contexts.some((context) => !bound.some((item) => isRecord$1(item) && item.context === context)))) throw invalid("Branch summary omits required-check integration bindings.");
872
+ if (bound.length > 0 && (bound.some((item) => !isRecord(item) || typeof item.context !== "string") || checks.contexts.some((context) => !bound.some((item) => isRecord(item) && item.context === context)))) throw invalid("Branch summary omits required-check integration bindings.");
266
873
  }
267
874
  classicSource = rules.warnings?.some((warning) => warning.code === "insufficient_scope") ? "branch-summary" : "protection-endpoint";
268
875
  } else if (protection !== void 0 && protection.enabled !== false) throw invalid("Branch protection summary is incomplete.");
@@ -272,17 +879,46 @@ function githubBranchRuleDetails(rules) {
272
879
  classicSource
273
880
  };
274
881
  }
882
+ /**
883
+ * Read branch rules with `provider.repos.branchRules()`. GitHub answers 403 for the rules of a private repository
884
+ * on a plan without rulesets or branch protection. When it gives that reason and the branch summary reports the
885
+ * branch unprotected, this returns no rules. Any other 403 still rejects, so a missing permission never reads as no rules.
886
+ */
887
+ async function forgeBranchRules(provider, repo, branch, options) {
888
+ try {
889
+ return await provider.repos.branchRules(repo, branch, options);
890
+ } catch (error) {
891
+ if (provider.forge !== "github" || !planWithoutRules(error)) throw error;
892
+ const path = `${repositoryPath$1(repo)}/branches/${branch.split("/").map(encodeURIComponent).join("/")}`;
893
+ const summary = (await provider.request("GET", path, { signal: options?.signal })).data;
894
+ if (!isRecord(summary) || summary.protected !== false) throw error;
895
+ return {
896
+ branch,
897
+ requiredChecks: [],
898
+ requiredApprovals: 0,
899
+ raw: {
900
+ branch: summary,
901
+ rules: []
902
+ }
903
+ };
904
+ }
905
+ }
906
+ function planWithoutRules(error) {
907
+ if (forgeErrorStatus(error) !== 403 || !(error instanceof Error)) return false;
908
+ const body = "body" in error && typeof error.body === "string" ? error.body : "";
909
+ return /Upgrade to GitHub Pro or make this repository public/i.test(`${error.message}\n${body}`);
910
+ }
275
911
  //#endregion
276
912
  //#region src/gaps/commit-files.ts
277
913
  /**
278
914
  * `provider.contents.commitFiles()` with Git file modes, and the sha of the new commit.
279
- * Without a `mode`, the call goes to `commitFiles()`. When one change has a `mode`, every write without one is `100644`.
915
+ * Without a `mode` or a GitHub author, the call goes to `commitFiles()`. Every write without a mode is `100644`.
280
916
  * Rejects with `BranchMovedError` when the branch no longer points at `expectedHead`, as `commitFiles()` does.
281
917
  * Gap: `FileChange` has no mode, so `commitFiles()` cannot write a symlink or an executable file.
282
- * Proposed upstream as `FileChange.mode`.
918
+ * Proposed upstream as `FileChange.mode` (https://github.com/danielroe/forges/issues/296).
283
919
  */
284
920
  async function forgeCommitFiles(provider, repo, input, options = {}) {
285
- if (input.changes.length > 0 && !input.changes.some((change) => change.mode)) return (await provider.contents.commitFiles(repo, input, options)).sha;
921
+ if (!(provider.forge === "github" && input.author) && input.changes.length > 0 && !input.changes.some((change) => change.mode)) return (await provider.contents.commitFiles(repo, input, options)).sha;
286
922
  if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0005({ message: `Git file modes are not supported for ${provider.forge}.` });
287
923
  const signal = options.signal;
288
924
  const base = `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}/git`;
@@ -319,15 +955,31 @@ async function forgeCommitFiles(provider, repo, input, options = {}) {
319
955
  },
320
956
  signal
321
957
  })).data, void 0, "tree");
322
- const commit = sha((await provider.request("POST", `${base}/commits`, {
323
- body: {
324
- message: input.message,
325
- parents: [parent],
326
- tree: treeSha,
327
- ...input.author ? { author: input.author } : {}
328
- },
958
+ const body = {
959
+ message: input.message,
960
+ parents: [parent],
961
+ tree: treeSha
962
+ };
963
+ let result = (await provider.request("POST", `${base}/commits`, {
964
+ body,
329
965
  signal
330
- })).data, void 0, "commit");
966
+ })).data;
967
+ if (input.author) {
968
+ const committer = result instanceof Object && "committer" in result ? result.committer : void 0;
969
+ if (!(committer instanceof Object) || !("name" in committer) || typeof committer.name !== "string" || !("email" in committer) || typeof committer.email !== "string") throw forgeResponseError("GitHub returned a malformed commit committer response.");
970
+ result = (await provider.request("POST", `${base}/commits`, {
971
+ body: {
972
+ ...body,
973
+ author: input.author,
974
+ committer: {
975
+ name: committer.name,
976
+ email: committer.email
977
+ }
978
+ },
979
+ signal
980
+ })).data;
981
+ }
982
+ const commit = sha(result, void 0, "commit");
331
983
  if (input.createFrom !== void 0) {
332
984
  await provider.request("POST", `${base}/refs`, {
333
985
  body: {
@@ -362,7 +1014,7 @@ async function forgeCommitFiles(provider, repo, input, options = {}) {
362
1014
  function sha(value, key, description) {
363
1015
  const target = key && value instanceof Object && key in value ? Reflect.get(value, key) : value;
364
1016
  const result = target instanceof Object && "sha" in target ? target.sha : void 0;
365
- if (typeof result !== "string" || !result) throw new ForgeResponseError(`GitHub returned a malformed ${description} response.`);
1017
+ if (typeof result !== "string" || !result) throw forgeResponseError(`GitHub returned a malformed ${description} response.`);
366
1018
  return result;
367
1019
  }
368
1020
  //#endregion
@@ -396,6 +1048,7 @@ function repositoryPath(repository) {
396
1048
  /**
397
1049
  * Git smart HTTP remote and credentials for one repository.
398
1050
  * Gap: `forges` exposes `Repo.cloneUrls` but no transport credential.
1051
+ * Remove when forges releases it (https://github.com/danielroe/forges/issues/192).
399
1052
  */
400
1053
  function forgeGitCredentials(input) {
401
1054
  const url = `${instanceRoot(input.forge, input.baseUrl)}/${repositoryPath(input.repository)}.git`;
@@ -420,6 +1073,101 @@ function forgeGitAuthHeader(credentials) {
420
1073
  };
421
1074
  }
422
1075
  //#endregion
1076
+ //#region src/gaps/merge.ts
1077
+ const pollDelays = [
1078
+ 500,
1079
+ 1e3,
1080
+ 2e3
1081
+ ];
1082
+ /** `threads.merge()`, which can also bypass GitHub branch rules. */
1083
+ async function forgeMerge(provider, thread, options = {}) {
1084
+ const { bypassRules, timeout = 3e4, ...mergeOptions } = options;
1085
+ if (!bypassRules) return await provider.threads.merge(thread, mergeOptions);
1086
+ const github = requireGitHub(provider, "forgeMerge({ bypassRules })");
1087
+ if (thread.kind !== "pull_request" || !thread.number) throw forgeDiagnostics.FORGE_R0009({ message: "Only a pull request with a number can merge past branch rules." });
1088
+ const { method, sha, signal } = mergeOptions;
1089
+ if (!method || !sha) throw forgeDiagnostics.FORGE_R0009({ message: "A merge past branch rules needs the merge method and the expected head sha." });
1090
+ const path = `${repositoryPath$1(thread.repo)}/pulls/${encodeURIComponent(thread.number)}/merge-async`;
1091
+ const budget = AbortSignal.timeout(timeout);
1092
+ const requestSignal = signal ? AbortSignal.any([signal, budget]) : budget;
1093
+ const timedOut = (uuid) => new ForgeTimeoutError(uuid ? `Merge request ${uuid} for pull request ${thread.number} was still pending after ${timeout}ms; GitHub may still complete it` : `Merge of pull request ${thread.number} got no response within ${timeout}ms; GitHub may still complete it`, timeout);
1094
+ let uuid;
1095
+ try {
1096
+ let state;
1097
+ try {
1098
+ state = (await github.request("PUT", path, {
1099
+ body: {
1100
+ merge_method: method,
1101
+ sha,
1102
+ commit_title: mergeOptions.title,
1103
+ commit_message: mergeOptions.message,
1104
+ merge_action: "direct_merge",
1105
+ bypass_rules: true
1106
+ },
1107
+ signal: requestSignal
1108
+ })).data;
1109
+ } catch (error) {
1110
+ if (budget.aborted) throw error;
1111
+ state = pendingMerge(error, method, sha, mergeOptions.title !== void 0 || mergeOptions.message !== void 0);
1112
+ }
1113
+ for (let attempt = 0; isRecord(state) && state.status === "pending"; attempt++) {
1114
+ uuid = isRecord(state.details) && typeof state.details.uuid === "string" ? state.details.uuid : void 0;
1115
+ if (!uuid) throw new ForgeApiError("GitHub reported a pending merge without a request id", 202, JSON.stringify(state).slice(0, 512));
1116
+ await sleep(pollDelays[Math.min(attempt, pollDelays.length - 1)], requestSignal);
1117
+ state = (await github.request("GET", `${path}/${encodeURIComponent(uuid)}`, { signal: requestSignal })).data;
1118
+ }
1119
+ const status = isRecord(state) ? state.status : void 0;
1120
+ const details = isRecord(state) && isRecord(state.details) ? state.details : {};
1121
+ const excerpt = JSON.stringify(state).slice(0, 512);
1122
+ if (status === "merged") return {
1123
+ status: "merged",
1124
+ ...typeof details.sha === "string" ? { sha: details.sha } : {},
1125
+ raw: state
1126
+ };
1127
+ if (status === "enqueued") throw new MergeBlockedError("Pull request was added to a merge queue and has not merged", 200, excerpt);
1128
+ if (status === "failed") throw new MergeBlockedError(typeof details.message === "string" && details.message ? details.message : "GitHub could not merge the pull request", 200, excerpt);
1129
+ throw new ForgeApiError(`GitHub reported an unknown merge status ${JSON.stringify(status)}`, 200, excerpt);
1130
+ } catch (error) {
1131
+ throw budget.aborted && !signal?.aborted ? timedOut(uuid) : error;
1132
+ }
1133
+ }
1134
+ /**
1135
+ * GitHub answers 409 while another merge request for the pull request is pending. Wait for that request
1136
+ * only when it asked for exactly this merge, so a different request never counts as this one.
1137
+ */
1138
+ function pendingMerge(error, method, sha, customMessage) {
1139
+ if (!(error instanceof ForgeApiError) || error.constructor !== ForgeApiError) throw error;
1140
+ if (error.status === 400) throw new MergeBlockedError("Pull request cannot be merged in its current state", 400, error.body, {}, { cause: error });
1141
+ if (error.status !== 409) throw error;
1142
+ let pending;
1143
+ try {
1144
+ pending = JSON.parse(error.body);
1145
+ } catch {
1146
+ throw error;
1147
+ }
1148
+ const details = isRecord(pending) && isRecord(pending.details) ? pending.details : void 0;
1149
+ if (!details || typeof details.uuid !== "string") throw error;
1150
+ if (customMessage || details.merge_action !== "direct_merge" || details.merge_method !== method || details.bypass_rules !== true || details.expected_head_sha !== sha) throw new MergeBlockedError("Another merge request is pending whose options do not match or cannot be verified", 409, error.body, {}, { cause: error });
1151
+ return {
1152
+ status: "pending",
1153
+ details
1154
+ };
1155
+ }
1156
+ async function sleep(ms, signal) {
1157
+ signal.throwIfAborted();
1158
+ await new Promise((resolve, reject) => {
1159
+ const abort = () => {
1160
+ clearTimeout(timer);
1161
+ reject(signal.reason);
1162
+ };
1163
+ const timer = setTimeout(() => {
1164
+ signal.removeEventListener("abort", abort);
1165
+ resolve();
1166
+ }, ms);
1167
+ signal.addEventListener("abort", abort, { once: true });
1168
+ });
1169
+ }
1170
+ //#endregion
423
1171
  //#region src/gaps/retarget.ts
424
1172
  /** Change the base branch of a GitHub pull request. */
425
1173
  async function retargetPullRequest(provider, thread, base, options) {
@@ -432,250 +1180,4 @@ async function retargetPullRequest(provider, thread, base, options) {
432
1180
  });
433
1181
  }
434
1182
  //#endregion
435
- //#region src/gaps/review-threads.ts
436
- const THREADS = `query ForgeReviewThreads($owner:String!,$name:String!,$number:Int!,$after:String) {
437
- repository(owner:$owner,name:$name) { pullRequest(number:$number) { reviewThreads(first:100,after:$after) {
438
- nodes { id isResolved isOutdated path line originalLine startLine originalStartLine
439
- comments(first:100) { nodes { id databaseId } pageInfo { hasNextPage endCursor } }
440
- } pageInfo { hasNextPage endCursor }
441
- } } }
442
- }`;
443
- const THREAD_COMMENTS = `query ForgeReviewThreadComments($id:ID!,$after:String!) {
444
- node(id:$id) { ... on PullRequestReviewThread { comments(first:100,after:$after) {
445
- nodes { id databaseId } pageInfo { hasNextPage endCursor }
446
- } } }
447
- }`;
448
- const THREAD = `query ForgeReviewThread($id:ID!) {
449
- node(id:$id) { ... on PullRequestReviewThread { id isResolved pullRequest { id } } }
450
- }`;
451
- async function graphql(provider, query, variables, options) {
452
- const operationName = /\b(?:query|mutation)\s+([A-Za-z0-9_]+)/.exec(query)?.[1];
453
- const response = await provider.request("POST", "/graphql", {
454
- body: {
455
- query,
456
- variables,
457
- ...operationName ? { operationName } : {}
458
- },
459
- signal: options?.signal
460
- });
461
- const payload = isRecord$1(response.data) ? response.data : void 0;
462
- const errors = payload?.errors;
463
- if (Array.isArray(errors) && errors.length) throw incomplete(`GitHub review thread query failed: ${errors.map((error) => isRecord$1(error) && typeof error.message === "string" ? error.message : String(error)).join("; ")}`);
464
- return payload?.data ?? response.data;
465
- }
466
- function incomplete(message) {
467
- return forgeDiagnostics.FORGE_R0008({ message });
468
- }
469
- function field(value, ...path) {
470
- let current = value;
471
- for (const key of path) current = isRecord$1(current) ? current[key] : void 0;
472
- return current;
473
- }
474
- function connection(value) {
475
- const page = field(value, "pageInfo");
476
- const nodes = field(value, "nodes");
477
- if (!Array.isArray(nodes) || !isRecord$1(page) || typeof page.hasNextPage !== "boolean") throw incomplete("GitHub returned an incomplete review thread page.");
478
- const endCursor = typeof page.endCursor === "string" && page.endCursor ? page.endCursor : void 0;
479
- if (page.hasNextPage && !endCursor) throw incomplete("GitHub omitted a review thread cursor.");
480
- return {
481
- nodes,
482
- hasNextPage: page.hasNextPage,
483
- ...endCursor ? { endCursor } : {}
484
- };
485
- }
486
- function advance(page, seen) {
487
- if (!page.hasNextPage) return void 0;
488
- if (seen.has(page.endCursor)) throw incomplete("GitHub repeated a review thread cursor.");
489
- seen.add(page.endCursor);
490
- return page.endCursor;
491
- }
492
- function comment(value) {
493
- if (!isRecord$1(value) || typeof value.id !== "string") throw incomplete("GitHub returned an incomplete review comment.");
494
- return {
495
- id: value.id,
496
- ...typeof value.databaseId === "number" ? { restId: String(value.databaseId) } : {}
497
- };
498
- }
499
- function optionalNumber(value) {
500
- return typeof value === "number" ? value : void 0;
501
- }
502
- /** List every review conversation of a GitHub pull request, with the identity of every comment in it. */
503
- async function listReviewThreads(provider, thread, options) {
504
- requireGitHub(provider, "listReviewThreads()");
505
- if (thread.kind !== "pull_request" || !thread.number) throw forgeDiagnostics.FORGE_R0009({ message: "Review threads belong to a pull request with a number." });
506
- const threads = [];
507
- const pages = /* @__PURE__ */ new Set();
508
- let after;
509
- do {
510
- const page = connection(field(await graphql(provider, THREADS, {
511
- owner: thread.repo.owner,
512
- name: thread.repo.name,
513
- number: Number(thread.number),
514
- after: after ?? null
515
- }, options), "repository", "pullRequest", "reviewThreads"));
516
- after = advance(page, pages);
517
- for (const node of page.nodes) {
518
- if (!isRecord$1(node) || typeof node.id !== "string" || typeof node.isResolved !== "boolean") throw incomplete("GitHub returned incomplete review thread metadata.");
519
- const first = connection(node.comments);
520
- const comments = first.nodes.map(comment);
521
- const commentPages = /* @__PURE__ */ new Set();
522
- let commentAfter = advance(first, commentPages);
523
- while (commentAfter) {
524
- const more = connection(field(await graphql(provider, THREAD_COMMENTS, {
525
- id: node.id,
526
- after: commentAfter
527
- }, options), "node", "comments"));
528
- comments.push(...more.nodes.map(comment));
529
- commentAfter = advance(more, commentPages);
530
- }
531
- const { comments: _comments, ...raw } = node;
532
- threads.push({
533
- id: node.id,
534
- resolved: node.isResolved,
535
- outdated: node.isOutdated === true,
536
- path: typeof node.path === "string" ? node.path : void 0,
537
- line: optionalNumber(node.line),
538
- startLine: optionalNumber(node.startLine),
539
- originalLine: optionalNumber(node.originalLine),
540
- originalStartLine: optionalNumber(node.originalStartLine),
541
- comments,
542
- raw
543
- });
544
- }
545
- } while (after);
546
- return threads;
547
- }
548
- /** Look up one review conversation by its id. Returns undefined when the id names no review conversation. */
549
- async function getReviewThread(provider, id, options) {
550
- requireGitHub(provider, "getReviewThread()");
551
- const node = field(await graphql(provider, THREAD, { id }, options), "node");
552
- if (node === null || isRecord$1(node) && Object.keys(node).length === 0) return void 0;
553
- const pullRequestId = field(node, "pullRequest", "id");
554
- if (!isRecord$1(node) || typeof node.id !== "string" || typeof node.isResolved !== "boolean" || typeof pullRequestId !== "string") throw incomplete("GitHub returned an incomplete review thread.");
555
- return {
556
- id: node.id,
557
- resolved: node.isResolved,
558
- pullRequestId
559
- };
560
- }
561
- //#endregion
562
- //#region src/github-app.ts
563
- const appProviders = /* @__PURE__ */ new Map();
564
- const installationTokens = /* @__PURE__ */ new WeakMap();
565
- const appProviderLimit = 128;
566
- const fetchIds = /* @__PURE__ */ new WeakMap();
567
- let nextFetchId = 0;
568
- function fetchId(fetcher) {
569
- if (!fetcher) return 0;
570
- let id = fetchIds.get(fetcher);
571
- if (id === void 0) {
572
- id = ++nextFetchId;
573
- fetchIds.set(fetcher, id);
574
- }
575
- return id;
576
- }
577
- function appProviderKey(input, installationId) {
578
- return createHash("sha256").update(`${input.baseUrl || "https://api.github.com"}\0${input.appId}\0${input.privateKey}\0${input.userAgent ?? ""}\0${fetchId(input.fetch)}\0${installationId}`).digest("hex");
579
- }
580
- /**
581
- * One App provider per installation, so `refresh` replaces the token of that installation only.
582
- * App-level requests use the entry with an empty installation ID.
583
- */
584
- function appProvider(input, installationId = "", refresh = false) {
585
- const key = appProviderKey(input, installationId);
586
- if (refresh) appProviders.delete(key);
587
- const cached = appProviders.get(key);
588
- if (cached) return cached;
589
- const pending = import("./github-DtncTfmv.js").then(({ github }) => github({
590
- ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
591
- ...input.fetch ? { fetch: input.fetch } : {},
592
- userAgent: input.userAgent ?? "vitehub",
593
- auth: {
594
- type: "app",
595
- appId: input.appId,
596
- privateKey: input.privateKey
597
- }
598
- }));
599
- pending.catch(() => appProviders.delete(key));
600
- appProviders.set(key, pending);
601
- if (appProviders.size > appProviderLimit) appProviders.delete(appProviders.keys().next().value);
602
- return pending;
603
- }
604
- function isRecord(value) {
605
- return typeof value === "object" && value !== null && !Array.isArray(value);
606
- }
607
- function positiveId(value) {
608
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
609
- }
610
- /**
611
- * GitHub App credentials. App providers are cached per API base, App, private key, user agent,
612
- * fetch function, and installation, so installation tokens are minted once and reused until they expire.
613
- */
614
- function githubAppCredentials(input) {
615
- return {
616
- async installationToken(installationId, options = {}) {
617
- const id = String(installationId);
618
- const provider = await withSignal(appProvider(input, id, options.refresh), options.signal);
619
- const cached = installationTokens.get(provider);
620
- if (cached && cached.expiresAt > Date.now() + 6e4) return {
621
- token: cached.token,
622
- expiresAt: new Date(cached.expiresAt)
623
- };
624
- const response = await withSignal(provider.request("POST", `/app/installations/${id}/access_tokens`, { signal: options.signal }), options.signal);
625
- if (!response.data.token) throw new ForgeResponseError("GitHub App installation token response did not include token.");
626
- const details = {
627
- token: response.data.token,
628
- expiresAt: new Date(response.data.expires_at)
629
- };
630
- installationTokens.set(provider, {
631
- token: details.token,
632
- expiresAt: details.expiresAt.getTime()
633
- });
634
- return details;
635
- },
636
- async installation(repository, signal) {
637
- const provider = await withSignal(appProvider(input), signal);
638
- const path = `/repos/${repository}/installation`;
639
- try {
640
- const response = await provider.request("GET", path, { signal });
641
- const id = positiveId(isRecord(response.data) ? response.data.id : void 0);
642
- if (!id) throw forgeDiagnostics.FORGE_R0001({ message: `GitHub App is not installed for ${repository}.` });
643
- return id;
644
- } catch (error) {
645
- if (signal?.aborted) throw abortError(signal);
646
- const status = forgeErrorStatus(error);
647
- if (status === void 0) throw error;
648
- throw forgeDiagnostics.FORGE_R0001({
649
- message: `GitHub App request ${path} failed with ${status}.`,
650
- cause: error
651
- });
652
- }
653
- },
654
- async app(signal) {
655
- const response = await (await withSignal(appProvider(input), signal)).request("GET", "/app", { signal });
656
- const id = positiveId(isRecord(response.data) ? response.data.id : void 0);
657
- const slug = isRecord(response.data) && typeof response.data.slug === "string" ? response.data.slug : void 0;
658
- if (!id) throw new ForgeResponseError("GitHub App metadata did not include an ID.");
659
- if (!slug) throw new ForgeResponseError("GitHub App response did not include a slug.");
660
- return {
661
- id,
662
- slug,
663
- login: `${slug}[bot]`
664
- };
665
- }
666
- };
667
- }
668
- /** Read a GitHub App private key from an inline value or a file path. Escaped "\\n" becomes a newline. */
669
- async function readGitHubAppPrivateKey(inline, path) {
670
- const value = inline?.trim();
671
- if (value) return value.replace(/\\n/g, "\n");
672
- if (!path) return void 0;
673
- const { readFile } = await import(
674
- /* @vite-ignore */
675
- "node:fs/promises"
676
- );
677
- const file = (await readFile(path, "utf8")).trim();
678
- return file ? file.replace(/\\n/g, "\n") : void 0;
679
- }
680
- //#endregion
681
- export { BranchMovedError, ForgeApiError, ForgeResponseError, ForgeTimeoutError, MergeBlockedError, NotFoundError, RateLimitedError, abortError, forgeArchive, forgeBlob, forgeCommitFiles, forgeEnv, forgeErrorStatus, forgeGitAuthHeader, forgeGitCredentials, forgeProvider, getReviewThread, githubAppCredentials, githubBranchRuleDetails, listReviewThreads, readForgeEnv, readGitHubAppPrivateKey, repoRef, retargetPullRequest, withSignal };
1183
+ export { BranchMovedError, ForgeApiError, ForgeTimeoutError, MergeBlockedError, NotFoundError, RateLimitedError, abortError, conditionalFetch, forgeArchive, forgeBlob, forgeBranchRules, forgeCommitFiles, forgeEnv, forgeErrorStatus, forgeGitAuthHeader, forgeGitCredentials, forgeMemoryCache, forgeMerge, forgeProvider, forgeResponseError, githubAppCredentials, githubBranchRuleDetails, githubInstallationFor, githubInstallationRouting, isForgeResponseError, readForgeEnv, readGitHubAppPrivateKey, repoRef, retargetPullRequest, useForge, withSignal };