@vite-hub/forge 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # @vite-hub/forge
2
2
 
3
- [![npm version](https://comark-ui.onmax.me/badge.svg?source=npm-version&package=%40vite-hub%2Fforge&icon=npm)](https://npmx.dev/package/@vite-hub/forge)
4
- [![npm downloads](https://comark-ui.onmax.me/badge.svg?source=npm-downloads&package=%40vite-hub%2Fforge&period=month&icon=npm)](https://npmx.dev/package/@vite-hub/forge)
5
- [![license](https://comark-ui.onmax.me/badge.svg?label=license&value=Apache-2.0)](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
6
- [![docs](https://comark-ui.onmax.me/badge.svg?label=docs&value=vitehub.dev)](https://vitehub.dev/docs)
3
+ [![npm version](https://img.shields.io/npm/v/@vite-hub/forge)](https://npmx.dev/package/@vite-hub/forge)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@vite-hub/forge)](https://npmx.dev/package/@vite-hub/forge)
5
+ [![license](https://img.shields.io/static/v1?label=license&message=Apache-2.0&color=blue)](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
6
+ [![docs](https://img.shields.io/static/v1?label=docs&message=vitehub.dev&color=blue)](https://vitehub.dev/docs)
7
7
 
8
- `@vite-hub/forge` is the one Forge identity of ViteHub. Apps call `useForge()` to act as their GitHub App, or with their GitLab or Forgejo token. Channels, Capabilities, Workspaces and Sources read the same env names. It is built on [`forges`](https://forges.link). User docs: [Forge](https://vitehub.dev/docs/forge).
8
+ `@vite-hub/forge` is the one Forge identity of ViteHub. Apps call `useForge()` to act as their GitHub App, or with their GitLab, Forgejo or Gitea token. Channels, Capabilities, Workspaces and Sources read the same env names. It is built on [`forges`](https://forges.link). User docs: [Forge](https://vitehub.dev/docs/forge).
9
9
 
10
- The GitHub Channel, the `forge()` Capability, and the Workspace GitHub store mint App installation tokens through `useForge()`. GitHub Sources use only `VITEHUB_GITHUB_TOKEN` (or `FORGES_GITHUB_TOKEN`). Channels, Workspaces and Sources list `@vite-hub/forge` as an optional peer and load it only on a Forge path, so an app without a Forge does not install it. Such an app that uses a Forge Channel, the `forge()` Capability, a GitHub Store or a GitHub Source fails with `INTERNAL_FORGE_NOT_INSTALLED` until it runs `pnpm add @vite-hub/forge`.
10
+ The GitHub Channel, the `forge()` Capability, and the Workspace GitHub store mint App installation tokens through `useForge()` when using App credentials. The store prefers an explicit `token` over App credentials and falls back to the env token when no App ID is set. GitHub Sources read `VITEHUB_GITHUB_TOKEN` (or `FORGES_GITHUB_TOKEN`) when `auth` is omitted. Channels, Workspaces and Sources list `@vite-hub/forge` as an optional peer and load it only on a Forge path, so an app without a Forge does not install it. Such an app that uses a Forge Channel, the `forge()` Capability, a GitHub Store or a GitHub Source fails with `INTERNAL_FORGE_NOT_INSTALLED` until it runs `pnpm add @vite-hub/forge`.
11
11
 
12
12
  ## Use it in an app
13
13
 
@@ -32,7 +32,7 @@ await github.request("POST", "/repos/acme/web/issues", { body: { title: "Nightly
32
32
  | `forge.kind`, `forge.auth`, `forge.baseUrl` | The Forge, `"app"` or `"token"`, and the API base. |
33
33
  | `forge.token({ repository, installation, refresh, minLifetime, signal })` | `[error, { token, expiresAt }]`. With a GitHub App, an installation token for `installation`, such as `installation.id` of a webhook delivery, else for the owner of `repository` (see [Installations](https://vitehub.dev/docs/forge/configure#installations)), or for `VITEHUB_GITHUB_INSTALLATION_ID` without `repository`. Cached until `minLifetime` milliseconds (default one minute) before it expires. |
34
34
  | `forge.provider({ repository, installation, refresh, minLifetime, signal })` | `[error, provider]`, a `forges` provider that sends `token()`. A GitHub provider has `graphql()`. |
35
- | `forge.app({ signal })` | `[error, { id, slug, login }]` of the GitHub App. Throws `FORGE_NOT_APP` with a token. |
35
+ | `forge.app({ signal })` | `[error, { id, slug, login, email }]` of the GitHub App. Throws `FORGE_NOT_APP` with a token. |
36
36
 
37
37
  GitHub uses the App when `VITEHUB_GITHUB_APP_ID` is set, and `VITEHUB_GITHUB_TOKEN` otherwise. Runtime errors are `FORGE_APP_NOT_INSTALLED` and `FORGE_REQUEST_FAILED`. A cancelled call rejects with the abort reason. The codes are documented at [Forge limits and errors](https://vitehub.dev/docs/forge/limits-and-errors).
38
38
 
@@ -52,6 +52,9 @@ Each field reads its `VITEHUB_` name first, then the `FORGES_` name that the `fo
52
52
  | `github.webhookSecret` | `VITEHUB_GITHUB_WEBHOOK_SECRET`, `FORGES_GITHUB_WEBHOOK_SECRET` |
53
53
  | `gitlab.baseUrl`, `gitlab.token`, `gitlab.webhookSecret` | `VITEHUB_GITLAB_*`, `FORGES_GITLAB_*` |
54
54
  | `forgejo.baseUrl`, `forgejo.token`, `forgejo.webhookSecret` | `VITEHUB_FORGEJO_*`, `FORGES_FORGEJO_*` |
55
+ | `gitea.baseUrl`, `gitea.token`, `gitea.webhookSecret` | `VITEHUB_GITEA_*`, `FORGES_GITEA_*` |
56
+
57
+ For Gitea, `useForge()` uses `VITEHUB_GITEA_WEBHOOK_SECRET` (or `FORGES_GITEA_WEBHOOK_SECRET`) as the default secret for `provider.webhooks.verify({ headers, body })`. Pass the raw request body so the signature matches.
55
58
 
56
59
  `GH_TOKEN` and `GITHUB_TOKEN` are not read. In GitHub Actions, set `VITEHUB_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}`.
57
60
 
@@ -70,6 +73,7 @@ Each field reads its `VITEHUB_` name first, then the `FORGES_` name that the `fo
70
73
  | `readForgeEnv(field, env)` | The first value set for one `forgeEnv` field, from an env record or a lookup function. |
71
74
  | `forgeProvider(connection)` | A `forges` provider for one Forge. Return it from a public API only where that API owns the Forge credentials. A GitHub provider has `graphql()`. GitHub providers revalidate repeated GETs with `If-None-Match`, so unchanged responses come back as `304`s that GitHub doesn't charge; `conditionalRequests: false` turns it off, and `{ identity, cache }` sets who shares entries and where they live. |
72
75
  | `conditionalFetch(fetch, { identity, cache })`, `forgeMemoryCache({ maxSize, maxEntrySize })` | The `fetch` wrapper behind `conditionalRequests`, and its in-memory LRU. The default cache is shared by the process, holds up to 32 MiB of bodies, and skips bodies over 1 MiB. |
76
+ | `forgeBranchRules(provider, repo, branch, options)` | Reads branch rules with `provider.repos.branchRules()`. Returns empty rules only as a fallback when GitHub responds with a `403` asking you to upgrade or make the repository public and the branch summary confirms the branch is unprotected. Other `403` responses still reject. |
73
77
  | `githubBranchRuleDetails(rules)` | GitHub only. Required workflows, ruleset merge methods and the classic protection source from the result of `provider.repos.branchRules()`. |
74
78
  | `retargetPullRequest(provider, pull, base)` | GitHub only. Change the base branch of a pull request. |
75
79
  | `forgeMerge(provider, pull, options)` | `threads.merge()` with `bypassRules`. GitHub only with `bypassRules: true`: merge past failing branch rules, as an admin or a ruleset bypass actor. It needs `method` and `sha`. |
@@ -84,7 +88,7 @@ Each field reads its `VITEHUB_` name first, then the `FORGES_` name that the `fo
84
88
  | `forgeBlob(provider, repo, sha, { signal })` | The bytes of one blob by sha. GitHub only. |
85
89
  | `forgeCommitFiles(provider, repo, input, options)` | `contents.commitFiles()` that can also set git file modes (`100644`, `100755`, `120000`). Returns the commit sha. |
86
90
  | `BranchMovedError` | The bundled `forges` error for a branch that moved before a commit. |
87
- | `forgeErrorStatus(error)`, `isForgeResponseError(error)` | Classify Forge request failures. |
91
+ | `forgeResponseError(problem)`, `forgeErrorStatus(error)`, `isForgeResponseError(error)` | Build `FORGE_RESPONSE_INVALID` errors and classify Forge request failures. |
88
92
  | `withSignal(promise, signal)`, `abortError(signal)` | Cancellation helpers for Forge calls. |
89
93
 
90
94
  ## Diagnostics
@@ -99,6 +103,8 @@ Each field reads its `VITEHUB_` name first, then the `FORGES_` name that the `fo
99
103
  | `FORGE_R0006` | A GitHub-only helper got a provider for another Forge. |
100
104
  | `FORGE_R0007` | `githubBranchRuleDetails()` got branch rules that are not complete GitHub rulesets or classic protection. |
101
105
  | `FORGE_R0009` | A GitHub-only helper got a reference that is not a numbered pull request, or an empty input. |
106
+ | `FORGE_RESPONSE_INVALID` | A Forge request returned missing or invalid data. Read the error message for the specific problem. |
107
+ | `FORGE_UNSUPPORTED` | The `forge` value of a Forge connection is not `github`, `gitlab`, `forgejo`, or `gitea`. |
102
108
 
103
109
  ## Gaps in `forges`
104
110
 
@@ -110,6 +116,7 @@ Each field reads its `VITEHUB_` name first, then the `FORGES_` name that the `fo
110
116
  | `forgeBlob()` | `contents.getFile()` reads by path, not by blob sha. |
111
117
  | `forgeCommitFiles()` | `contents.commitFiles()` cannot set a file mode. |
112
118
  | `forgeGitCredentials()`, `forgeGitAuthHeader()` | `Repo.cloneUrls` has no transport credential. |
119
+ | `forgeBranchRules()` | `repos.branchRules()` rejects on GitHub's plan-limit `403` even when the branch is unprotected. |
113
120
  | `githubBranchRuleDetails()` | `BranchRules` has no required workflows, ruleset merge methods or classic protection source. |
114
121
  | `retargetPullRequest()` | No pull request base change. |
115
122
  | `forgeMerge()` | `threads.merge()` cannot bypass branch rules. |
@@ -78,7 +78,6 @@ async function readBuildRevision(root, env = process.env, git = (args) => readGi
78
78
  function githubRepository(remote) {
79
79
  return remote ? /^(?:(?:https?|ssh|git):\/\/[^/]+\/|(?:[^@/:]+@)?[\w.-]+:)([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/.exec(remote.trim())?.[1] : void 0;
80
80
  }
81
- /** The pull request that the CI or host builds, when it names one. */
82
81
  function pullRequestOf(env) {
83
82
  const value = env.VERCEL_GIT_PULL_REQUEST_ID || (env.PULL_REQUEST === "true" ? env.REVIEW_ID : void 0) || /^refs\/pull\/(\d+)\//.exec(env.GITHUB_REF ?? "")?.[1];
84
83
  const number = Number(value);
@@ -1,5 +1,5 @@
1
1
  import { $ as toDate, A as hexColour, B as milestoneId, C as createListing, F as latestCommentOf, G as requireIssueOrPull, I as mapConcurrent, K as requireThread, L as memo, M as isFirstPage, O as getManyConcurrently, Q as teamOrg, R as memoBy, U as rateLimitPart, X as summariseChecks, Y as soleMergeMethod, at as versionAtLeast, ct as isNamespaceRef, d as NotFoundError, et as toFileStatus, g as UnsupportedOperationError, it as toWarning, j as hostOf, k as hasEveryLabel, n as BranchMovedError, nt as toPage, o as ForgeError, pt as reactionContent, q as resolveToken, rt as toPullStats, tt as toMergeError, y as actorLogin } from "./utils-DC7MBR65-B7Vr2hFm.js";
2
- import { C as verb, S as toFileContent, T as githubShapedWeb, _ as reviewState, a as verifyHmacSignature, c as changeBase64, d as eventTime, f as existingFiles, g as perKind, l as defineForgeProvider, m as inDirectories, p as fromBase64, r as nativeEventsFor, s as WRITE_VERBS, t as eventKindsOf } from "./webhooks-Bc6QhmI8-CNgCERCq.js";
2
+ import { C as verb, S as toFileContent, T as githubShapedWeb, _ as reviewState, a as verifyHmacSignature, c as changeBase64, d as eventTime, f as existingFiles, g as perKind, m as inDirectories, p as fromBase64, r as nativeEventsFor, s as WRITE_VERBS, t as eventKindsOf } from "./webhooks-Bc6QhmI8-CNgCERCq.js";
3
3
  //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/web-khKJ7nW8.mjs
4
4
  const RESERVED_PATHS = [
5
5
  "-",
@@ -49,6 +49,7 @@ function forgejoWeb(forge, baseUrl) {
49
49
  };
50
50
  }
51
51
  const FORGEJO_WEB = /* @__PURE__ */ forgejoWeb("forgejo", "https://codeberg.org");
52
+ const GITEA_WEB = /* @__PURE__ */ forgejoWeb("gitea", "https://gitea.com");
52
53
  //#endregion
53
54
  //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/definition-0wjaAw2i.mjs
54
55
  const FORGEJO_HEADERS = {
@@ -60,6 +61,11 @@ const FORGEJO_HEADERS = {
60
61
  ],
61
62
  delivery: ["x-forgejo-delivery", "x-gitea-delivery"]
62
63
  };
64
+ const GITEA_HEADERS = {
65
+ signature: ["x-gitea-signature"],
66
+ event: ["x-gitea-event", "x-github-event"],
67
+ delivery: ["x-gitea-delivery"]
68
+ };
63
69
  /** Native Forgejo and Gitea event names per normalised kind, for hook subscriptions. */
64
70
  const FORGEJO_NATIVE_EVENTS = {
65
71
  comment: ["issue_comment", "pull_request_comment"],
@@ -1022,7 +1028,7 @@ function forgejoWebhooks(profile) {
1022
1028
  return ({ options, origin }) => ({
1023
1029
  events: FORGEJO_WEBHOOK_EVENTS,
1024
1030
  verify: (delivery) => verifyForgejoSignature(delivery, options.webhookSecret, profile.headers),
1025
- translate: async (delivery) => (await import("./events-DmSWTdpS-BdJBABfI.js")).translateForgejoWebhook(origin, delivery, profile.headers)
1031
+ translate: async (delivery) => (await import("./events-DmSWTdpS-oDiTlP1L.js")).translateForgejoWebhook(origin, delivery, profile.headers)
1026
1032
  });
1027
1033
  }
1028
1034
  const YAML_FILE = /\.ya?ml$/i;
@@ -1523,7 +1529,7 @@ function setupForgejo({ options, origin, fetcher: baseFetcher, baseUrl }, profil
1523
1529
  return released(isGitea ? giteaMinimum : forgejoMinimum);
1524
1530
  }
1525
1531
  async function feedPage(path, listOptions, query) {
1526
- const { toFeedEvent } = await import("./feed-BwdcTgZq-Bm_c8br8.js");
1532
+ const { toFeedEvent } = await import("./feed-BwdcTgZq-CbyczJHA.js");
1527
1533
  return list(path, listOptions, (raw) => toFeedEvent(origin, raw), { query });
1528
1534
  }
1529
1535
  async function setBlocked(scope, login, blocked, options) {
@@ -2317,8 +2323,4 @@ function forgejoScopesFor(verb) {
2317
2323
  return {};
2318
2324
  }
2319
2325
  //#endregion
2320
- //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/forgejo/index.mjs
2321
- /** Creates a Forgejo provider for Codeberg or any self-hosted Forgejo instance. */
2322
- const forgejo = /* @__PURE__ */ defineForgeProvider(/* @__PURE__ */ forgejoDefinition(FORGEJO_PROFILE));
2323
- //#endregion
2324
- export { forgejo, toThread as i, toActor as n, toRepoRef as r, FORGEJO_HEADERS as t };
2326
+ export { toActor as a, GITEA_WEB as c, forgejoDefinition as i, FORGEJO_PROFILE as n, toRepoRef as o, GITEA_HEADERS as r, toThread as s, FORGEJO_HEADERS as t };
@@ -1,6 +1,6 @@
1
1
  import { $ as toDate, _ as WebhookVerificationError } from "./utils-DC7MBR65-B7Vr2hFm.js";
2
2
  import { _ as reviewState, d as eventTime, i as refEvent, k as bodyText, n as firstHeader, u as eventAction, v as snapshotOfThread } from "./webhooks-Bc6QhmI8-CNgCERCq.js";
3
- import { i as toThread, n as toActor, r as toRepoRef, t as FORGEJO_HEADERS } from "./forgejo-UNPc42cY.js";
3
+ import { a as toActor, o as toRepoRef, s as toThread, t as FORGEJO_HEADERS } from "./definition-0wjaAw2i-BwSDtp9h.js";
4
4
  //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/events-DmSWTdpS.mjs
5
5
  const EVENT_KINDS = {
6
6
  issue_comment: "comment",
@@ -1,6 +1,6 @@
1
1
  import { $ as toDate } from "./utils-DC7MBR65-B7Vr2hFm.js";
2
2
  import { d as eventTime, i as refEvent } from "./webhooks-Bc6QhmI8-CNgCERCq.js";
3
- import { n as toActor, r as toRepoRef } from "./forgejo-UNPc42cY.js";
3
+ import { a as toActor, o as toRepoRef } from "./definition-0wjaAw2i-BwSDtp9h.js";
4
4
  //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/feed-BwdcTgZq.mjs
5
5
  /** Activity types about an issue or a pull request, whose `content` starts with its number. */
6
6
  const FEED_THREAD_OPS = {
@@ -0,0 +1,7 @@
1
+ import { l as defineForgeProvider } from "./webhooks-Bc6QhmI8-CNgCERCq.js";
2
+ import { i as forgejoDefinition, n as FORGEJO_PROFILE } from "./definition-0wjaAw2i-BwSDtp9h.js";
3
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/forgejo/index.mjs
4
+ /** Creates a Forgejo provider for Codeberg or any self-hosted Forgejo instance. */
5
+ const forgejo = /* @__PURE__ */ defineForgeProvider(/* @__PURE__ */ forgejoDefinition(FORGEJO_PROFILE));
6
+ //#endregion
7
+ export { forgejo };
@@ -0,0 +1,11 @@
1
+ import { l as defineForgeProvider } from "./webhooks-Bc6QhmI8-CNgCERCq.js";
2
+ import { c as GITEA_WEB, i as forgejoDefinition, r as GITEA_HEADERS } from "./definition-0wjaAw2i-BwSDtp9h.js";
3
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/gitea/index.mjs
4
+ /** Creates a Gitea provider for gitea.com or any self-hosted Gitea instance. */
5
+ const gitea = /* @__PURE__ */ defineForgeProvider(/* @__PURE__ */ forgejoDefinition({
6
+ forge: "gitea",
7
+ web: GITEA_WEB,
8
+ headers: GITEA_HEADERS
9
+ }));
10
+ //#endregion
11
+ export { gitea };
package/dist/index.d.ts CHANGED
@@ -3783,6 +3783,7 @@ type ForgeEnv = {
3783
3783
  github: Record<"appId" | "installationId" | "appOwner" | "appInstallations" | "privateKey" | "privateKeyPath" | "token" | "webhookSecret", ForgeEnvField>;
3784
3784
  gitlab: Record<"baseUrl" | "token" | "webhookSecret", ForgeEnvField>;
3785
3785
  forgejo: Record<"baseUrl" | "token" | "webhookSecret", ForgeEnvField>;
3786
+ gitea: Record<"baseUrl" | "token" | "webhookSecret", ForgeEnvField>;
3786
3787
  };
3787
3788
  /**
3788
3789
  * Server Env of each Forge, keyed by the `env.server.<forge>.<field>` path.
@@ -3801,13 +3802,15 @@ export declare function forgeErrorStatus(error: unknown): number | undefined;
3801
3802
  //#endregion
3802
3803
  //#region src/provider.d.ts
3803
3804
  /** The Forges that ViteHub supports. */
3804
- type ForgeKind = "github" | "gitlab" | "forgejo";
3805
+ type ForgeKind = "github" | "gitlab" | "forgejo" | "gitea";
3805
3806
  interface ForgeConnection {
3806
3807
  forge: ForgeKind;
3807
- /** GitHub: API base. GitLab and Forgejo: instance root. */
3808
+ /** GitHub: API base. GitLab, Forgejo and Gitea: instance root. */
3808
3809
  baseUrl?: string;
3809
3810
  /** Omitted: anonymous public reads. */
3810
3811
  token?: string;
3812
+ /** Default secret for verifying Gitea webhook deliveries. */
3813
+ webhookSecret?: string;
3811
3814
  readOnly?: boolean;
3812
3815
  fetch?: typeof fetch;
3813
3816
  /** Default "vitehub". */
@@ -3845,8 +3848,8 @@ interface UseForgeOptions<TKind extends ForgeKind = "github"> {
3845
3848
  /** Default `"github"`. */
3846
3849
  forge?: TKind;
3847
3850
  /**
3848
- * GitHub: the API base, for GitHub Enterprise Server. GitLab and Forgejo: the instance root.
3849
- * Default for GitLab and Forgejo: `VITEHUB_GITLAB_BASE_URL` or `VITEHUB_FORGEJO_BASE_URL`.
3851
+ * GitHub: the API base, for GitHub Enterprise Server. GitLab, Forgejo and Gitea: the instance root.
3852
+ * Default for GitLab, Forgejo and Gitea: `VITEHUB_GITLAB_BASE_URL`, `VITEHUB_FORGEJO_BASE_URL` or `VITEHUB_GITEA_BASE_URL`.
3850
3853
  */
3851
3854
  baseUrl?: string;
3852
3855
  /** Default: the bindings of the active Cloudflare request, then `process.env`. */
@@ -3888,6 +3891,8 @@ interface ForgeAppIdentity {
3888
3891
  id: number;
3889
3892
  slug: string;
3890
3893
  login: string;
3894
+ /** The bot's commit email, such as `41898282+my-app[bot]@users.noreply.github.com`. GitHub links these commits to the App. */
3895
+ email: string;
3891
3896
  }
3892
3897
  /** The `forges` provider of one Forge. A GitHub provider also has `graphql()`. */
3893
3898
  type ForgeProviderOf<TKind extends ForgeKind> = [TKind] extends ["github"] ? GitHubProvider : ForgeProvider;
@@ -3992,7 +3997,7 @@ export declare function forgeCommitFiles(provider: ForgeProvider, repo: RepoRef,
3992
3997
  //#region src/gaps/git-credentials.d.ts
3993
3998
  interface ForgeGitCredentialsInput {
3994
3999
  forge: ForgeKind;
3995
- /** The same `baseUrl` as `forgeProvider()`. GitHub: API base. GitLab and Forgejo: instance root. */
4000
+ /** The same `baseUrl` as `forgeProvider()`. GitHub: API base. GitLab, Forgejo and Gitea: instance root. */
3996
4001
  baseUrl?: string;
3997
4002
  /** Omitted: anonymous clone. */
3998
4003
  token?: string;
@@ -4051,11 +4056,15 @@ interface GitHubAppCredentials {
4051
4056
  }>;
4052
4057
  /** GET /repos/{repository}/installation with the app JWT. */
4053
4058
  installation(repository: string, signal?: AbortSignal): Promise<number>;
4054
- /** GET /app. */
4059
+ /**
4060
+ * GET /app, and GET /users/{login} for the bot user's noreply `email`, the commit email that GitHub links to the
4061
+ * App. Cached per App: an App's identity does not change.
4062
+ */
4055
4063
  app(signal?: AbortSignal): Promise<{
4056
4064
  id: number;
4057
4065
  slug: string;
4058
4066
  login: string;
4067
+ email: string;
4059
4068
  }>;
4060
4069
  /**
4061
4070
  * Every repository that the App's installations can access, from `GET /app/installations` and
package/dist/index.js CHANGED
@@ -75,6 +75,17 @@ const forgeEnv = {
75
75
  names: ["VITEHUB_FORGEJO_WEBHOOK_SECRET", "FORGES_FORGEJO_WEBHOOK_SECRET"],
76
76
  secret: true
77
77
  }
78
+ },
79
+ gitea: {
80
+ baseUrl: { names: ["VITEHUB_GITEA_BASE_URL", "FORGES_GITEA_BASE_URL"] },
81
+ token: {
82
+ names: ["VITEHUB_GITEA_TOKEN", "FORGES_GITEA_TOKEN"],
83
+ secret: true
84
+ },
85
+ webhookSecret: {
86
+ names: ["VITEHUB_GITEA_WEBHOOK_SECRET", "FORGES_GITEA_WEBHOOK_SECRET"],
87
+ secret: true
88
+ }
78
89
  }
79
90
  };
80
91
  /**
@@ -131,42 +142,34 @@ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(me
131
142
  const forgeDiagnostics = /*#__PURE__*/ defineDiagnostics({
132
143
  docsBase: "https://vitehub.dev/docs/forge/diagnostics",
133
144
  codes: {
134
- /** The GitHub App installation lookup failed or the App is not installed. */
135
145
  FORGE_R0001: {
136
146
  ...dynamicError,
137
147
  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
148
  },
139
- /** `forgeArchive()` was called for a Forge without archive support. */
140
149
  FORGE_R0002: {
141
150
  ...dynamicError,
142
151
  fix: "Call `forgeArchive()` with a GitHub provider, because other forges have no archive download here."
143
152
  },
144
- /** `forgeGitCredentials()` received an invalid base URL or repository. */
145
153
  FORGE_R0003: {
146
154
  ...dynamicError,
147
155
  fix: "Pass a forge base URL that starts with `https://` or `http://`, and a repository as `owner/name`."
148
156
  },
149
- /** `forgeBlob()` was called for a Forge without blob reads. */
150
157
  FORGE_R0004: {
151
158
  ...dynamicError,
152
159
  fix: "Call `forgeBlob()` with a GitHub provider, because other forges cannot read a blob by sha here."
153
160
  },
154
- /** `forgeCommitFiles()` received a file mode for a Forge without file mode writes. */
155
161
  FORGE_R0005: {
156
162
  ...dynamicError,
157
163
  fix: "Remove `mode` from the file changes, or commit them with a GitHub provider."
158
164
  },
159
- /** A GitHub-only Forge helper received a provider for another Forge. */
160
165
  FORGE_R0006: {
161
166
  ...dynamicError,
162
167
  fix: "Call the helper that the message names with a GitHub provider."
163
168
  },
164
- /** `githubBranchRuleDetails()` got branch rules that are not complete GitHub rulesets or classic protection. */
165
169
  FORGE_R0007: {
166
170
  ...dynamicError,
167
171
  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
172
  },
169
- /** A GitHub-only Forge helper received a reference that is not a numbered pull request, or an empty input. */
170
173
  FORGE_R0009: {
171
174
  ...dynamicError,
172
175
  fix: "Pass a pull request thread with a `number` and a nonempty base branch. For `forgeMerge({ bypassRules })`, also pass `method` and `sha`."
@@ -177,7 +180,7 @@ const forgeDiagnostics = /*#__PURE__*/ defineDiagnostics({
177
180
  },
178
181
  FORGE_UNSUPPORTED: {
179
182
  why: "Unsupported Forge.",
180
- fix: "Set `forge` of the Forge connection to `github`, `gitlab`, or `forgejo`."
183
+ fix: "Set `forge` of the Forge connection to `github`, `gitlab`, `forgejo`, or `gitea`."
181
184
  }
182
185
  }
183
186
  });
@@ -234,8 +237,8 @@ function conditionalFetch(fetcher, options = {}) {
234
237
  return async (input, init) => {
235
238
  const request = input instanceof Request ? input : void 0;
236
239
  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);
240
+ const { headers: inputHeaders = request?.headers } = init ?? {};
241
+ const headers = new Headers(inputHeaders);
239
242
  const authorization = headers.get("authorization");
240
243
  if (method !== "GET" || !authorization || headers.has("if-none-match") || headers.has("if-modified-since")) return await fetcher(input, init);
241
244
  const url = request?.url ?? String(input);
@@ -305,9 +308,17 @@ async function forgeProvider(connection) {
305
308
  return gitlab(options);
306
309
  }
307
310
  case "forgejo": {
308
- const { forgejo } = await import("./forgejo-UNPc42cY.js");
311
+ const { forgejo } = await import("./forgejo-DgNfNjcW.js");
309
312
  return forgejo(options);
310
313
  }
314
+ case "gitea": {
315
+ const { gitea } = await import("./gitea-Zpwj_XHC.js");
316
+ const { webhookSecret } = connection;
317
+ return gitea({
318
+ ...options,
319
+ ...webhookSecret ? { webhookSecret } : {}
320
+ });
321
+ }
311
322
  }
312
323
  throw forgeDiagnostics.FORGE_UNSUPPORTED();
313
324
  }
@@ -327,13 +338,10 @@ function abortError(signal) {
327
338
  /** Reject with the abort reason when `signal` aborts before `promise` settles. */
328
339
  async function withSignal(promise, signal) {
329
340
  if (!signal) return await promise;
330
- if (signal.aborted) {
331
- promise.catch(() => void 0);
332
- throw abortError(signal);
333
- }
334
341
  return await new Promise((resolve, reject) => {
335
342
  const abort = () => reject(abortError(signal));
336
- signal.addEventListener("abort", abort, { once: true });
343
+ if (signal.aborted) abort();
344
+ else signal.addEventListener("abort", abort, { once: true });
337
345
  promise.then((value) => {
338
346
  signal.removeEventListener("abort", abort);
339
347
  resolve(value);
@@ -353,7 +361,47 @@ function isRecord(value) {
353
361
  //#region src/github-app.ts
354
362
  const appProviders = /* @__PURE__ */ new Map();
355
363
  const installationTokens = /* @__PURE__ */ new WeakMap();
364
+ const tokenMints = /* @__PURE__ */ new WeakMap();
365
+ function tokenMint(provider, installationId) {
366
+ const shared = globalThis.navigator?.userAgent !== "Cloudflare-Workers";
367
+ const existing = shared ? tokenMints.get(provider) : void 0;
368
+ if (existing) return existing;
369
+ const controller = new AbortController();
370
+ let stopped = false;
371
+ const forget = () => {
372
+ if (tokenMints.get(provider) === mint) tokenMints.delete(provider);
373
+ };
374
+ const mint = {
375
+ waiters: 0,
376
+ minted: provider.request("POST", `/app/installations/${installationId}/access_tokens`, { signal: controller.signal }).then((response) => {
377
+ if (!response.data.token) throw forgeResponseError("GitHub App installation token response did not include token.");
378
+ const minted = {
379
+ token: response.data.token,
380
+ expiresAt: new Date(response.data.expires_at).getTime()
381
+ };
382
+ if (!stopped) installationTokens.set(provider, minted);
383
+ return minted;
384
+ }).finally(forget),
385
+ stop(reason) {
386
+ stopped = true;
387
+ forget();
388
+ controller.abort(reason);
389
+ }
390
+ };
391
+ if (shared) tokenMints.set(provider, mint);
392
+ return mint;
393
+ }
394
+ async function joinTokenMint(mint, signal) {
395
+ mint.waiters++;
396
+ try {
397
+ return await withSignal(mint.minted, signal);
398
+ } finally {
399
+ mint.waiters--;
400
+ if (!mint.waiters && signal?.aborted) mint.stop(signal.reason);
401
+ }
402
+ }
356
403
  const appProviderLimit = 128;
404
+ const appIdentities = /* @__PURE__ */ new Map();
357
405
  const fetchIds = /* @__PURE__ */ new WeakMap();
358
406
  let nextFetchId = 0;
359
407
  function fetchId(fetcher) {
@@ -368,10 +416,6 @@ function fetchId(fetcher) {
368
416
  function appProviderKey(input, installationId) {
369
417
  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
418
  }
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
419
  function appProvider(input, installationId = "", refresh = false) {
376
420
  const key = appProviderKey(input, installationId);
377
421
  if (refresh) appProviders.delete(key);
@@ -395,6 +439,29 @@ function appProvider(input, installationId = "", refresh = false) {
395
439
  function positiveId(value) {
396
440
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
397
441
  }
442
+ async function appIdentity(input) {
443
+ const response = await (await appProvider(input)).request("GET", "/app");
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
+ const login = `${slug}[bot]`;
449
+ const { github } = await import("./github-CUiEF2FK.js");
450
+ const userId = await github({
451
+ ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
452
+ ...input.fetch ? { fetch: input.fetch } : {},
453
+ userAgent: input.userAgent ?? "vitehub"
454
+ }).request("GET", `/users/${encodeURIComponent(login)}`).then((user) => positiveId(isRecord(user.data) ? user.data.id : void 0), () => void 0);
455
+ return {
456
+ verified: userId !== void 0,
457
+ identity: {
458
+ id,
459
+ slug,
460
+ login,
461
+ email: userId ? `${userId}+${login}@users.noreply.github.com` : `${login}@users.noreply.github.com`
462
+ }
463
+ };
464
+ }
398
465
  /**
399
466
  * GitHub App credentials. App providers are cached per API base, App, private key, user agent,
400
467
  * fetch function, and installation, so installation tokens are minted once and reused until they expire.
@@ -409,17 +476,11 @@ function githubAppCredentials(input) {
409
476
  token: cached.token,
410
477
  expiresAt: new Date(cached.expiresAt)
411
478
  };
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)
479
+ const minted = await joinTokenMint(tokenMint(provider, id), options.signal);
480
+ return {
481
+ token: minted.token,
482
+ expiresAt: new Date(minted.expiresAt)
417
483
  };
418
- installationTokens.set(provider, {
419
- token: details.token,
420
- expiresAt: details.expiresAt.getTime()
421
- });
422
- return details;
423
484
  },
424
485
  async installation(repository, signal) {
425
486
  const provider = await withSignal(appProvider(input), signal);
@@ -440,16 +501,21 @@ function githubAppCredentials(input) {
440
501
  }
441
502
  },
442
503
  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
- };
504
+ const key = appProviderKey(input, "");
505
+ let pending = appIdentities.get(key);
506
+ if (!pending) {
507
+ const lookup = appIdentity(input);
508
+ const evict = () => {
509
+ if (appIdentities.get(key) === lookup) appIdentities.delete(key);
510
+ };
511
+ lookup.then(({ verified }) => {
512
+ if (!verified) evict();
513
+ }, evict);
514
+ appIdentities.set(key, lookup);
515
+ pending = lookup;
516
+ if (appIdentities.size > appProviderLimit) appIdentities.delete(appIdentities.keys().next().value);
517
+ }
518
+ return (await withSignal(pending, signal)).identity;
453
519
  },
454
520
  async repositories(signal) {
455
521
  const provider = await withSignal(appProvider(input), signal);
@@ -659,6 +725,7 @@ function useForge(options = {}) {
659
725
  }
660
726
  const baseField = fields[kind].baseUrl;
661
727
  const baseUrl = options.baseUrl ?? (baseField ? readForgeEnv(baseField, env) : void 0);
728
+ const webhookSecret = kind === "gitea" ? readForgeEnv(forgeEnv.gitea.webhookSecret, env) : void 0;
662
729
  const userAgent = options.userAgent ?? "vitehub";
663
730
  let credentials;
664
731
  function appCredentials(config) {
@@ -750,6 +817,7 @@ function useForge(options = {}) {
750
817
  userAgent,
751
818
  ...options.conditionalRequests === false ? { conditionalRequests: false } : minted.identity ? { conditionalRequests: { identity: minted.identity } } : {},
752
819
  ...baseUrl ? { baseUrl } : {},
820
+ ...webhookSecret ? { webhookSecret } : {},
753
821
  ...options.fetch ? { fetch: options.fetch } : {}
754
822
  });
755
823
  if (call.signal?.aborted) throw abortError(call.signal);
@@ -926,6 +994,7 @@ async function forgeCommitFiles(provider, repo, input, options = {}) {
926
994
  const readHead = async () => sha((await provider.request("GET", `${base}/ref/${branchRef}`, { signal })).data, "object", "branch");
927
995
  const parent = input.createFrom === void 0 ? input.expectedHead ?? await readHead() : await provider.contents.resolveRef(repo, input.createFrom, { signal });
928
996
  const baseTree = sha((await provider.request("GET", `${base}/commits/${encodeURIComponent(parent)}`, { signal })).data, "tree", "commit");
997
+ const blobs = /* @__PURE__ */ new Map();
929
998
  const tree = await Promise.all(input.changes.map(async (change) => {
930
999
  if (change.content === null) return {
931
1000
  mode: change.mode ?? "100644",
@@ -934,17 +1003,21 @@ async function forgeCommitFiles(provider, repo, input, options = {}) {
934
1003
  type: "blob"
935
1004
  };
936
1005
  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
- });
1006
+ let blob = blobs.get(content);
1007
+ if (!blob) {
1008
+ blob = provider.request("POST", `${base}/blobs`, {
1009
+ body: {
1010
+ content,
1011
+ encoding: "base64"
1012
+ },
1013
+ signal
1014
+ }).then((response) => sha(response.data, void 0, "blob"));
1015
+ blobs.set(content, blob);
1016
+ }
944
1017
  return {
945
1018
  mode: change.mode ?? "100644",
946
1019
  path: change.path,
947
- sha: sha(blob.data, void 0, "blob"),
1020
+ sha: await blob,
948
1021
  type: "blob"
949
1022
  };
950
1023
  }));
@@ -1010,7 +1083,6 @@ async function forgeCommitFiles(provider, repo, input, options = {}) {
1010
1083
  }
1011
1084
  return commit;
1012
1085
  }
1013
- /** The `sha` of a GitHub Git database response, or of its `key` object. */
1014
1086
  function sha(value, key, description) {
1015
1087
  const target = key && value instanceof Object && key in value ? Reflect.get(value, key) : value;
1016
1088
  const result = target instanceof Object && "sha" in target ? target.sha : void 0;
@@ -1022,12 +1094,14 @@ function sha(value, key, description) {
1022
1094
  const defaultInstance = {
1023
1095
  github: "https://github.com",
1024
1096
  gitlab: "https://gitlab.com",
1025
- forgejo: "https://codeberg.org"
1097
+ forgejo: "https://codeberg.org",
1098
+ gitea: "https://gitea.com"
1026
1099
  };
1027
1100
  const tokenUsername = {
1028
1101
  github: "x-access-token",
1029
1102
  gitlab: "oauth2",
1030
- forgejo: "oauth2"
1103
+ forgejo: "oauth2",
1104
+ gitea: "oauth2"
1031
1105
  };
1032
1106
  function instanceRoot(forge, baseUrl) {
1033
1107
  if (!baseUrl) return defaultInstance[forge];
@@ -1131,10 +1205,6 @@ async function forgeMerge(provider, thread, options = {}) {
1131
1205
  throw budget.aborted && !signal?.aborted ? timedOut(uuid) : error;
1132
1206
  }
1133
1207
  }
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
1208
  function pendingMerge(error, method, sha, customMessage) {
1139
1209
  if (!(error instanceof ForgeApiError) || error.constructor !== ForgeApiError) throw error;
1140
1210
  if (error.status === 400) throw new MergeBlockedError("Pull request cannot be merged in its current state", 400, error.body, {}, { cause: error });
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@vite-hub/forge",
3
- "version": "0.3.1",
4
- "description": "One Forge identity for ViteHub apps: GitHub App installation tokens and GitHub, GitLab and Forgejo providers from one set of env names.",
3
+ "version": "0.5.0",
4
+ "description": "One Forge identity for ViteHub apps: GitHub App installation tokens and GitHub, GitLab, Forgejo and Gitea providers from one set of env names.",
5
5
  "keywords": [
6
6
  "forge",
7
7
  "forgejo",
8
+ "gitea",
8
9
  "github",
9
10
  "gitlab",
10
11
  "source-control",
@@ -46,7 +47,7 @@
46
47
  "./package.json": "./package.json"
47
48
  },
48
49
  "dependencies": {
49
- "@vite-hub/runtime": "0.3.1",
50
+ "@vite-hub/runtime": "0.5.0",
50
51
  "nostics": "1.4.0"
51
52
  },
52
53
  "devDependencies": {
@@ -59,7 +60,7 @@
59
60
  "vitest": "^4.1.11"
60
61
  },
61
62
  "engines": {
62
- "node": ">=22.18.0"
63
+ "node": ">=24.15.0"
63
64
  },
64
65
  "scripts": {
65
66
  "build": "vp pack",