@vite-hub/forge 0.4.1 → 0.5.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 (32) hide show
  1. package/README.md +11 -4
  2. package/dist/{association-Ds6Tgs0W-Cu9_YCGq.js → association-Ds6Tgs0W-CgBVH3ii.js} +1 -2
  3. package/dist/build/node.d.ts +1 -3
  4. package/dist/build/node.js +3 -6
  5. package/dist/build.d.ts +1 -1
  6. package/dist/build.js +1 -2
  7. package/dist/{forgejo-UNPc42cY.js → definition-BQFdu9ti-WxMjcAEl.js} +15 -13
  8. package/dist/{events-DW3SFUDA-D2rhS9D-.js → events-BL0zcgMf-9TwyYtCt.js} +3 -5
  9. package/dist/{events-uCMi3LHU-Bz79PQtq.js → events-DDdJnmD2-BSMoOqjV.js} +4 -5
  10. package/dist/{events-DjRw3KSr-C72gY7Vu.js → events-DHqSJ5KI-z2-5_1vo.js} +59 -60
  11. package/dist/{events-DmSWTdpS-BdJBABfI.js → events-DXE-Ul2S-BzTkugIK.js} +4 -5
  12. package/dist/{feed-BlzdKdNv-DbxuSgsx.js → feed-B1OiHFg0-DevZZe0y.js} +3 -5
  13. package/dist/{feed-CIaAZINm-Dpe9DxwK.js → feed-DROLF1tb-CtRfA_7N.js} +3 -5
  14. package/dist/{feed-BwdcTgZq-Bm_c8br8.js → feed-iWegqepj-ConxMpg4.js} +3 -5
  15. package/dist/forgejo-4sbZukng.js +6 -0
  16. package/dist/gitea-Cj7qy2X3.js +10 -0
  17. package/dist/{gitee-BXyl2_3W-dQOAjWqr.js → gitee-CKt4pEC0-BuLWggck.js} +2 -3
  18. package/dist/{github-CUiEF2FK.js → github-CHzhqYOr.js} +377 -293
  19. package/dist/{gitlab-zvWb9zOi.js → gitlab-CS0shW2u.js} +12 -10
  20. package/dist/{graphql-BDhuP5jN-BSpB8lWf.js → graphql-DxRA9BGO-BBbmTmWi.js} +43 -33
  21. package/dist/{identity-CmVEBLP5.js → identity-BwC2_3S9.js} +1 -2
  22. package/dist/{identity-CNTWZZuv.d.ts → identity-D2-HaDku.d.ts} +0 -2
  23. package/dist/index.d.ts +50 -44
  24. package/dist/index.js +149 -98
  25. package/dist/model-Biiu1CfI-CVLamGai.js +288 -0
  26. package/dist/{templates-BGDqQMu4-PSB43E1j.js → templates-0m5QBVIh-D1fZeoC-.js} +3 -3
  27. package/dist/{webhooks-Bc6QhmI8-CNgCERCq.js → webhooks-Bc6QhmI8-eK71_mJE.js} +1034 -98
  28. package/package.json +8 -7
  29. package/dist/events-C6C7lk1x-J8VCAjEX.js +0 -131
  30. package/dist/knot-bGebBK_B-CeDHcJUz.js +0 -350
  31. package/dist/tangled-8lg_73Wi-bSufNXiN.js +0 -43
  32. package/dist/utils-DC7MBR65-B7Vr2hFm.js +0 -1214
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
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";
1
+ import { b as NotFoundError, c as repoRef, g as ForgeTimeoutError, p as ForgeApiError, u as BranchMovedError, v as MergeBlockedError, x as RateLimitedError } from "./model-Biiu1CfI-CVLamGai.js";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  import { defineErrors, isRuntimeDiagnostic } from "@vite-hub/runtime";
4
4
  import { defineDiagnostics } from "nostics";
5
5
  import { createHash } from "node:crypto";
6
6
  import { Buffer } from "node:buffer";
7
- //#region ../internal/src/runtime/cloudflare-env-lookup.ts
7
+ // ../internal/src/runtime/cloudflare-env-lookup.ts
8
8
  /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
9
9
  const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
10
10
  let activeEnv;
@@ -18,16 +18,14 @@ function getActiveCloudflareEnv() {
18
18
  const host = globalThis;
19
19
  return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
20
20
  }
21
- //#endregion
22
- //#region ../internal/src/runtime/cloudflare-env.ts
21
+ // ../internal/src/runtime/cloudflare-env.ts
23
22
  const runtimeGlobal = globalThis;
24
23
  runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
25
24
  function getActiveCloudflareBinding(name) {
26
25
  const env = getActiveCloudflareEnv();
27
26
  return env && Object.hasOwn(env, name) ? env[name] : void 0;
28
27
  }
29
- //#endregion
30
- //#region ../internal/src/forge.ts
28
+ // ../internal/src/forge.ts
31
29
  /**
32
30
  * Server Env of each Forge, keyed by the `env.server.<forge>.<field>` path.
33
31
  * Channels, Capabilities, Workspaces and Sources read the same names.
@@ -75,6 +73,17 @@ const forgeEnv = {
75
73
  names: ["VITEHUB_FORGEJO_WEBHOOK_SECRET", "FORGES_FORGEJO_WEBHOOK_SECRET"],
76
74
  secret: true
77
75
  }
76
+ },
77
+ gitea: {
78
+ baseUrl: { names: ["VITEHUB_GITEA_BASE_URL", "FORGES_GITEA_BASE_URL"] },
79
+ token: {
80
+ names: ["VITEHUB_GITEA_TOKEN", "FORGES_GITEA_TOKEN"],
81
+ secret: true
82
+ },
83
+ webhookSecret: {
84
+ names: ["VITEHUB_GITEA_WEBHOOK_SECRET", "FORGES_GITEA_WEBHOOK_SECRET"],
85
+ secret: true
86
+ }
78
87
  }
79
88
  };
80
89
  /**
@@ -94,8 +103,7 @@ function forgeErrorStatus(error) {
94
103
  if (!(error instanceof Error) || !("status" in error)) return void 0;
95
104
  return typeof error.status === "number" ? error.status : void 0;
96
105
  }
97
- //#endregion
98
- //#region src/errors.ts
106
+ // src/errors.ts
99
107
  const forgeErrors = /*#__PURE__*/ defineErrors({
100
108
  docs: "https://vitehub.dev/docs/forge/diagnostics",
101
109
  codes: {
@@ -125,48 +133,39 @@ const forgeErrors = /*#__PURE__*/ defineErrors({
125
133
  }
126
134
  }
127
135
  });
128
- //#endregion
129
- //#region src/error-diagnostics.ts
136
+ // src/error-diagnostics.ts
130
137
  const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
131
138
  const forgeDiagnostics = /*#__PURE__*/ defineDiagnostics({
132
139
  docsBase: "https://vitehub.dev/docs/forge/diagnostics",
133
140
  codes: {
134
- /** The GitHub App installation lookup failed or the App is not installed. */
135
141
  FORGE_R0001: {
136
142
  ...dynamicError,
137
143
  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
144
  },
139
- /** `forgeArchive()` was called for a Forge without archive support. */
140
145
  FORGE_R0002: {
141
146
  ...dynamicError,
142
147
  fix: "Call `forgeArchive()` with a GitHub provider, because other forges have no archive download here."
143
148
  },
144
- /** `forgeGitCredentials()` received an invalid base URL or repository. */
145
149
  FORGE_R0003: {
146
150
  ...dynamicError,
147
151
  fix: "Pass a forge base URL that starts with `https://` or `http://`, and a repository as `owner/name`."
148
152
  },
149
- /** `forgeBlob()` was called for a Forge without blob reads. */
150
153
  FORGE_R0004: {
151
154
  ...dynamicError,
152
155
  fix: "Call `forgeBlob()` with a GitHub provider, because other forges cannot read a blob by sha here."
153
156
  },
154
- /** `forgeCommitFiles()` received a file mode for a Forge without file mode writes. */
155
157
  FORGE_R0005: {
156
158
  ...dynamicError,
157
159
  fix: "Remove `mode` from the file changes, or commit them with a GitHub provider."
158
160
  },
159
- /** A GitHub-only Forge helper received a provider for another Forge. */
160
161
  FORGE_R0006: {
161
162
  ...dynamicError,
162
163
  fix: "Call the helper that the message names with a GitHub provider."
163
164
  },
164
- /** `githubBranchRuleDetails()` got branch rules that are not complete GitHub rulesets or classic protection. */
165
165
  FORGE_R0007: {
166
166
  ...dynamicError,
167
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
168
  },
169
- /** A GitHub-only Forge helper received a reference that is not a numbered pull request, or an empty input. */
170
169
  FORGE_R0009: {
171
170
  ...dynamicError,
172
171
  fix: "Pass a pull request thread with a `number` and a nonempty base branch. For `forgeMerge({ bypassRules })`, also pass `method` and `sha`."
@@ -177,12 +176,11 @@ const forgeDiagnostics = /*#__PURE__*/ defineDiagnostics({
177
176
  },
178
177
  FORGE_UNSUPPORTED: {
179
178
  why: "Unsupported Forge.",
180
- fix: "Set `forge` of the Forge connection to `github`, `gitlab`, or `forgejo`."
179
+ fix: "Set `forge` of the Forge connection to `github`, `gitlab`, `forgejo`, or `gitea`."
181
180
  }
182
181
  }
183
182
  });
184
- //#endregion
185
- //#region src/conditional.ts
183
+ // src/conditional.ts
186
184
  const storedHeaders = [
187
185
  "content-type",
188
186
  "link",
@@ -234,8 +232,8 @@ function conditionalFetch(fetcher, options = {}) {
234
232
  return async (input, init) => {
235
233
  const request = input instanceof Request ? input : void 0;
236
234
  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);
235
+ const { headers: inputHeaders = request?.headers } = init ?? {};
236
+ const headers = new Headers(inputHeaders);
239
237
  const authorization = headers.get("authorization");
240
238
  if (method !== "GET" || !authorization || headers.has("if-none-match") || headers.has("if-modified-since")) return await fetcher(input, init);
241
239
  const url = request?.url ?? String(input);
@@ -278,8 +276,7 @@ function conditionalFetch(fetcher, options = {}) {
278
276
  });
279
277
  };
280
278
  }
281
- //#endregion
282
- //#region src/provider.ts
279
+ // src/provider.ts
283
280
  async function forgeProvider(connection) {
284
281
  const auth = connection.token ? {
285
282
  type: "token",
@@ -297,17 +294,25 @@ async function forgeProvider(connection) {
297
294
  };
298
295
  switch (connection.forge) {
299
296
  case "github": {
300
- const { github } = await import("./github-CUiEF2FK.js");
297
+ const { github } = await import("./github-CHzhqYOr.js");
301
298
  return github(options);
302
299
  }
303
300
  case "gitlab": {
304
- const { gitlab } = await import("./gitlab-zvWb9zOi.js");
301
+ const { gitlab } = await import("./gitlab-CS0shW2u.js");
305
302
  return gitlab(options);
306
303
  }
307
304
  case "forgejo": {
308
- const { forgejo } = await import("./forgejo-UNPc42cY.js");
305
+ const { forgejo } = await import("./forgejo-4sbZukng.js");
309
306
  return forgejo(options);
310
307
  }
308
+ case "gitea": {
309
+ const { gitea } = await import("./gitea-Cj7qy2X3.js");
310
+ const { webhookSecret } = connection;
311
+ return gitea({
312
+ ...options,
313
+ ...webhookSecret ? { webhookSecret } : {}
314
+ });
315
+ }
311
316
  }
312
317
  throw forgeDiagnostics.FORGE_UNSUPPORTED();
313
318
  }
@@ -327,13 +332,10 @@ function abortError(signal) {
327
332
  /** Reject with the abort reason when `signal` aborts before `promise` settles. */
328
333
  async function withSignal(promise, signal) {
329
334
  if (!signal) return await promise;
330
- if (signal.aborted) {
331
- promise.catch(() => void 0);
332
- throw abortError(signal);
333
- }
334
335
  return await new Promise((resolve, reject) => {
335
336
  const abort = () => reject(abortError(signal));
336
- signal.addEventListener("abort", abort, { once: true });
337
+ if (signal.aborted) abort();
338
+ else signal.addEventListener("abort", abort, { once: true });
337
339
  promise.then((value) => {
338
340
  signal.removeEventListener("abort", abort);
339
341
  resolve(value);
@@ -343,17 +345,55 @@ async function withSignal(promise, signal) {
343
345
  });
344
346
  });
345
347
  }
346
- //#endregion
347
- //#region ../internal/src/object.ts
348
+ // ../internal/src/object.ts
348
349
  /** A non-null object that is not an array. Functions do not pass. */
349
350
  function isRecord(value) {
350
351
  return typeof value === "object" && value !== null && !Array.isArray(value);
351
352
  }
352
- //#endregion
353
- //#region src/github-app.ts
353
+ // src/github-app.ts
354
354
  const appProviders = /* @__PURE__ */ new Map();
355
355
  const installationTokens = /* @__PURE__ */ new WeakMap();
356
+ const tokenMints = /* @__PURE__ */ new WeakMap();
357
+ function tokenMint(provider, installationId) {
358
+ const shared = globalThis.navigator?.userAgent !== "Cloudflare-Workers";
359
+ const existing = shared ? tokenMints.get(provider) : void 0;
360
+ if (existing) return existing;
361
+ const controller = new AbortController();
362
+ let stopped = false;
363
+ const forget = () => {
364
+ if (tokenMints.get(provider) === mint) tokenMints.delete(provider);
365
+ };
366
+ const mint = {
367
+ waiters: 0,
368
+ minted: provider.request("POST", `/app/installations/${installationId}/access_tokens`, { signal: controller.signal }).then((response) => {
369
+ if (!response.data.token) throw forgeResponseError("GitHub App installation token response did not include token.");
370
+ const minted = {
371
+ token: response.data.token,
372
+ expiresAt: new Date(response.data.expires_at).getTime()
373
+ };
374
+ if (!stopped) installationTokens.set(provider, minted);
375
+ return minted;
376
+ }).finally(forget),
377
+ stop(reason) {
378
+ stopped = true;
379
+ forget();
380
+ controller.abort(reason);
381
+ }
382
+ };
383
+ if (shared) tokenMints.set(provider, mint);
384
+ return mint;
385
+ }
386
+ async function joinTokenMint(mint, signal) {
387
+ mint.waiters++;
388
+ try {
389
+ return await withSignal(mint.minted, signal);
390
+ } finally {
391
+ mint.waiters--;
392
+ if (!mint.waiters && signal?.aborted) mint.stop(signal.reason);
393
+ }
394
+ }
356
395
  const appProviderLimit = 128;
396
+ const appIdentities = /* @__PURE__ */ new Map();
357
397
  const fetchIds = /* @__PURE__ */ new WeakMap();
358
398
  let nextFetchId = 0;
359
399
  function fetchId(fetcher) {
@@ -368,16 +408,12 @@ function fetchId(fetcher) {
368
408
  function appProviderKey(input, installationId) {
369
409
  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
410
  }
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
411
  function appProvider(input, installationId = "", refresh = false) {
376
412
  const key = appProviderKey(input, installationId);
377
413
  if (refresh) appProviders.delete(key);
378
414
  const cached = appProviders.get(key);
379
415
  if (cached) return cached;
380
- const pending = import("./github-CUiEF2FK.js").then(({ github }) => github({
416
+ const pending = import("./github-CHzhqYOr.js").then(({ github }) => github({
381
417
  ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
382
418
  ...input.fetch ? { fetch: input.fetch } : {},
383
419
  userAgent: input.userAgent ?? "vitehub",
@@ -395,6 +431,29 @@ function appProvider(input, installationId = "", refresh = false) {
395
431
  function positiveId(value) {
396
432
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
397
433
  }
434
+ async function appIdentity(input) {
435
+ const response = await (await appProvider(input)).request("GET", "/app");
436
+ const id = positiveId(isRecord(response.data) ? response.data.id : void 0);
437
+ const slug = isRecord(response.data) && typeof response.data.slug === "string" ? response.data.slug : void 0;
438
+ if (!id) throw forgeResponseError("GitHub App metadata did not include an ID.");
439
+ if (!slug) throw forgeResponseError("GitHub App response did not include a slug.");
440
+ const login = `${slug}[bot]`;
441
+ const { github } = await import("./github-CHzhqYOr.js");
442
+ const userId = await github({
443
+ ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
444
+ ...input.fetch ? { fetch: input.fetch } : {},
445
+ userAgent: input.userAgent ?? "vitehub"
446
+ }).request("GET", `/users/${encodeURIComponent(login)}`).then((user) => positiveId(isRecord(user.data) ? user.data.id : void 0), () => void 0);
447
+ return {
448
+ verified: userId !== void 0,
449
+ identity: {
450
+ id,
451
+ slug,
452
+ login,
453
+ email: userId ? `${userId}+${login}@users.noreply.github.com` : `${login}@users.noreply.github.com`
454
+ }
455
+ };
456
+ }
398
457
  /**
399
458
  * GitHub App credentials. App providers are cached per API base, App, private key, user agent,
400
459
  * fetch function, and installation, so installation tokens are minted once and reused until they expire.
@@ -409,17 +468,11 @@ function githubAppCredentials(input) {
409
468
  token: cached.token,
410
469
  expiresAt: new Date(cached.expiresAt)
411
470
  };
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)
471
+ const minted = await joinTokenMint(tokenMint(provider, id), options.signal);
472
+ return {
473
+ token: minted.token,
474
+ expiresAt: new Date(minted.expiresAt)
417
475
  };
418
- installationTokens.set(provider, {
419
- token: details.token,
420
- expiresAt: details.expiresAt.getTime()
421
- });
422
- return details;
423
476
  },
424
477
  async installation(repository, signal) {
425
478
  const provider = await withSignal(appProvider(input), signal);
@@ -440,16 +493,21 @@ function githubAppCredentials(input) {
440
493
  }
441
494
  },
442
495
  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
- };
496
+ const key = appProviderKey(input, "");
497
+ let pending = appIdentities.get(key);
498
+ if (!pending) {
499
+ const lookup = appIdentity(input);
500
+ const evict = () => {
501
+ if (appIdentities.get(key) === lookup) appIdentities.delete(key);
502
+ };
503
+ lookup.then(({ verified }) => {
504
+ if (!verified) evict();
505
+ }, evict);
506
+ appIdentities.set(key, lookup);
507
+ pending = lookup;
508
+ if (appIdentities.size > appProviderLimit) appIdentities.delete(appIdentities.keys().next().value);
509
+ }
510
+ return (await withSignal(pending, signal)).identity;
453
511
  },
454
512
  async repositories(signal) {
455
513
  const provider = await withSignal(appProvider(input), signal);
@@ -535,8 +593,7 @@ async function readGitHubAppPrivateKey(inline, path) {
535
593
  const file = (await readFile(path, "utf8")).trim();
536
594
  return file ? file.replace(/\\n/g, "\n") : void 0;
537
595
  }
538
- //#endregion
539
- //#region src/github-installations.ts
596
+ // src/github-installations.ts
540
597
  const names = {
541
598
  installationId: forgeEnv.github.installationId.names[0],
542
599
  appOwner: forgeEnv.github.appOwner.names[0],
@@ -592,8 +649,7 @@ function githubInstallationFor(routing, repository) {
592
649
  const owner = repository.split("/", 1)[0].toLowerCase();
593
650
  return (Object.hasOwn(routing.installations, owner) ? routing.installations[owner] : void 0) ?? (owner === routing.owner ? routing.installationId : void 0);
594
651
  }
595
- //#endregion
596
- //#region src/use-forge.ts
652
+ // src/use-forge.ts
597
653
  function hostEnv(name) {
598
654
  return getActiveCloudflareBinding(name) ?? globalThis.process?.env?.[name];
599
655
  }
@@ -659,6 +715,7 @@ function useForge(options = {}) {
659
715
  }
660
716
  const baseField = fields[kind].baseUrl;
661
717
  const baseUrl = options.baseUrl ?? (baseField ? readForgeEnv(baseField, env) : void 0);
718
+ const webhookSecret = kind === "gitea" ? readForgeEnv(forgeEnv.gitea.webhookSecret, env) : void 0;
662
719
  const userAgent = options.userAgent ?? "vitehub";
663
720
  let credentials;
664
721
  function appCredentials(config) {
@@ -750,6 +807,7 @@ function useForge(options = {}) {
750
807
  userAgent,
751
808
  ...options.conditionalRequests === false ? { conditionalRequests: false } : minted.identity ? { conditionalRequests: { identity: minted.identity } } : {},
752
809
  ...baseUrl ? { baseUrl } : {},
810
+ ...webhookSecret ? { webhookSecret } : {},
753
811
  ...options.fetch ? { fetch: options.fetch } : {}
754
812
  });
755
813
  if (call.signal?.aborted) throw abortError(call.signal);
@@ -766,8 +824,7 @@ function useForge(options = {}) {
766
824
  }
767
825
  };
768
826
  }
769
- //#endregion
770
- //#region src/gaps/archive.ts
827
+ // src/gaps/archive.ts
771
828
  /**
772
829
  * The repository tree at `ref` as a gzipped tarball stream.
773
830
  * Gap: `forges` has no `contents.archive()`. Proposed upstream as `provider.contents.archive(repo, options)`
@@ -784,8 +841,7 @@ async function forgeArchive(provider, repo, options) {
784
841
  signal: options.signal
785
842
  })).body;
786
843
  }
787
- //#endregion
788
- //#region src/gaps/blob.ts
844
+ // src/gaps/blob.ts
789
845
  /**
790
846
  * The bytes of one Git blob, by its sha. The blob of a symlink holds the link target.
791
847
  * Gap: `forges` reads files by path only, and GitHub follows a symlink path to its target.
@@ -810,8 +866,7 @@ function decodeBase64Blob(value) {
810
866
  return;
811
867
  }
812
868
  }
813
- //#endregion
814
- //#region src/gaps/github.ts
869
+ // src/gaps/github.ts
815
870
  /** Narrow a provider to GitHub, or throw `FORGE_R0006` for a GitHub-only helper. */
816
871
  function requireGitHub(provider, operation) {
817
872
  if (isGitHubProvider(provider)) return provider;
@@ -823,8 +878,7 @@ function isGitHubProvider(provider) {
823
878
  function repositoryPath$1(repo) {
824
879
  return `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
825
880
  }
826
- //#endregion
827
- //#region src/gaps/branch-rules.ts
881
+ // src/gaps/branch-rules.ts
828
882
  const mergeMethods = {
829
883
  merge: "merge",
830
884
  squash: "squash",
@@ -908,8 +962,7 @@ function planWithoutRules(error) {
908
962
  const body = "body" in error && typeof error.body === "string" ? error.body : "";
909
963
  return /Upgrade to GitHub Pro or make this repository public/i.test(`${error.message}\n${body}`);
910
964
  }
911
- //#endregion
912
- //#region src/gaps/commit-files.ts
965
+ // src/gaps/commit-files.ts
913
966
  /**
914
967
  * `provider.contents.commitFiles()` with Git file modes, and the sha of the new commit.
915
968
  * Without a `mode` or a GitHub author, the call goes to `commitFiles()`. Every write without a mode is `100644`.
@@ -926,6 +979,7 @@ async function forgeCommitFiles(provider, repo, input, options = {}) {
926
979
  const readHead = async () => sha((await provider.request("GET", `${base}/ref/${branchRef}`, { signal })).data, "object", "branch");
927
980
  const parent = input.createFrom === void 0 ? input.expectedHead ?? await readHead() : await provider.contents.resolveRef(repo, input.createFrom, { signal });
928
981
  const baseTree = sha((await provider.request("GET", `${base}/commits/${encodeURIComponent(parent)}`, { signal })).data, "tree", "commit");
982
+ const blobs = /* @__PURE__ */ new Map();
929
983
  const tree = await Promise.all(input.changes.map(async (change) => {
930
984
  if (change.content === null) return {
931
985
  mode: change.mode ?? "100644",
@@ -934,17 +988,21 @@ async function forgeCommitFiles(provider, repo, input, options = {}) {
934
988
  type: "blob"
935
989
  };
936
990
  const content = Buffer.from(change.content).toString("base64");
937
- const blob = await provider.request("POST", `${base}/blobs`, {
938
- body: {
939
- content,
940
- encoding: "base64"
941
- },
942
- signal
943
- });
991
+ let blob = blobs.get(content);
992
+ if (!blob) {
993
+ blob = provider.request("POST", `${base}/blobs`, {
994
+ body: {
995
+ content,
996
+ encoding: "base64"
997
+ },
998
+ signal
999
+ }).then((response) => sha(response.data, void 0, "blob"));
1000
+ blobs.set(content, blob);
1001
+ }
944
1002
  return {
945
1003
  mode: change.mode ?? "100644",
946
1004
  path: change.path,
947
- sha: sha(blob.data, void 0, "blob"),
1005
+ sha: await blob,
948
1006
  type: "blob"
949
1007
  };
950
1008
  }));
@@ -1010,24 +1068,24 @@ async function forgeCommitFiles(provider, repo, input, options = {}) {
1010
1068
  }
1011
1069
  return commit;
1012
1070
  }
1013
- /** The `sha` of a GitHub Git database response, or of its `key` object. */
1014
1071
  function sha(value, key, description) {
1015
1072
  const target = key && value instanceof Object && key in value ? Reflect.get(value, key) : value;
1016
1073
  const result = target instanceof Object && "sha" in target ? target.sha : void 0;
1017
1074
  if (typeof result !== "string" || !result) throw forgeResponseError(`GitHub returned a malformed ${description} response.`);
1018
1075
  return result;
1019
1076
  }
1020
- //#endregion
1021
- //#region src/gaps/git-credentials.ts
1077
+ // src/gaps/git-credentials.ts
1022
1078
  const defaultInstance = {
1023
1079
  github: "https://github.com",
1024
1080
  gitlab: "https://gitlab.com",
1025
- forgejo: "https://codeberg.org"
1081
+ forgejo: "https://codeberg.org",
1082
+ gitea: "https://gitea.com"
1026
1083
  };
1027
1084
  const tokenUsername = {
1028
1085
  github: "x-access-token",
1029
1086
  gitlab: "oauth2",
1030
- forgejo: "oauth2"
1087
+ forgejo: "oauth2",
1088
+ gitea: "oauth2"
1031
1089
  };
1032
1090
  function instanceRoot(forge, baseUrl) {
1033
1091
  if (!baseUrl) return defaultInstance[forge];
@@ -1072,8 +1130,7 @@ function forgeGitAuthHeader(credentials) {
1072
1130
  value: `AUTHORIZATION: basic ${basic}`
1073
1131
  };
1074
1132
  }
1075
- //#endregion
1076
- //#region src/gaps/merge.ts
1133
+ // src/gaps/merge.ts
1077
1134
  const pollDelays = [
1078
1135
  500,
1079
1136
  1e3,
@@ -1131,10 +1188,6 @@ async function forgeMerge(provider, thread, options = {}) {
1131
1188
  throw budget.aborted && !signal?.aborted ? timedOut(uuid) : error;
1132
1189
  }
1133
1190
  }
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
1191
  function pendingMerge(error, method, sha, customMessage) {
1139
1192
  if (!(error instanceof ForgeApiError) || error.constructor !== ForgeApiError) throw error;
1140
1193
  if (error.status === 400) throw new MergeBlockedError("Pull request cannot be merged in its current state", 400, error.body, {}, { cause: error });
@@ -1167,8 +1220,7 @@ async function sleep(ms, signal) {
1167
1220
  signal.addEventListener("abort", abort, { once: true });
1168
1221
  });
1169
1222
  }
1170
- //#endregion
1171
- //#region src/gaps/retarget.ts
1223
+ // src/gaps/retarget.ts
1172
1224
  /** Change the base branch of a GitHub pull request. */
1173
1225
  async function retargetPullRequest(provider, thread, base, options) {
1174
1226
  requireGitHub(provider, "retargetPullRequest()");
@@ -1179,5 +1231,4 @@ async function retargetPullRequest(provider, thread, base, options) {
1179
1231
  signal: options?.signal
1180
1232
  });
1181
1233
  }
1182
- //#endregion
1183
1234
  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 };