@vite-hub/forge 0.6.0 → 0.7.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
@@ -29,6 +29,7 @@ await github.request("POST", "/repos/acme/web/issues", { body: { title: "Nightly
29
29
  | Call | Returns |
30
30
  | --- | --- |
31
31
  | `useForge({ forge, baseUrl, env, fetch, userAgent, conditionalRequests })` | The Forge of this deployment. `conditionalRequests: false` stops GitHub providers from revalidating repeated GETs with ETags. `forge` defaults to `"github"`. `env` defaults to the active Cloudflare bindings, then `process.env`. Throws `FORGE_MISSING_ENV` or `FORGE_INVALID_ENV` when the env cannot work. |
32
+ | `checkForge(options)` | Checks the same env with no request, for a Setup page. Returns `[undefined, { kind, auth }]`, or `[error, undefined]` with `FORGE_MISSING_ENV` or `FORGE_INVALID_ENV`. It checks the base URL and verifies that the inline or file-based GitHub App private key can sign. It does not test whether the forge accepts the credentials. |
32
33
  | `forge.kind`, `forge.auth`, `forge.baseUrl` | The Forge, `"app"` or `"token"`, and the API base. |
33
34
  | `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
35
  | `forge.provider({ repository, installation, refresh, minLifetime, signal })` | `[error, provider]`, a `forges` provider that sends `token()`. A GitHub provider has `graphql()`. |
@@ -64,11 +65,12 @@ For Gitea, `useForge()` uses `VITEHUB_GITEA_WEBHOOK_SECRET` (or `FORGES_GITEA_WE
64
65
 
65
66
  ## Public imports
66
67
 
67
- `useForge()` is the app API. The other exports are the building blocks that ViteHub packages use.
68
+ `useForge()` and `checkForge()` are the app API. The other exports are the building blocks that ViteHub packages use.
68
69
 
69
70
  | Import | Use |
70
71
  | --- | --- |
71
72
  | `useForge(options)` | The Forge identity of the app, as above. |
73
+ | `checkForge(options)` | Checks the Forge env without a request, as above. |
72
74
  | `forgeEnv` | The Server Env table above. |
73
75
  | `readForgeEnv(field, env)` | The first value set for one `forgeEnv` field, from an env record or a lookup function. |
74
76
  | `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. |
@@ -82,6 +84,8 @@ For Gitea, `useForge()` uses `VITEHUB_GITEA_WEBHOOK_SECRET` (or `FORGES_GITEA_WE
82
84
  | `readGitHubAppPrivateKey(inline, path)` | Read a PEM key from a value or a file. |
83
85
  | `githubInstallationRouting({ installationId, appOwner, appInstallations })` | Read the [installation routing](https://vitehub.dev/docs/forge/configure#installations) from Server Env values. Throws `FORGE_INVALID_ENV`. |
84
86
  | `githubInstallationFor(routing, repository)` | The configured installation for `repository`, or `undefined` when GitHub must find it. |
87
+ | `provider.contents.resolveRef(repo, ref)` | The full commit sha of a branch, tag or sha. Part of `forges`; use it to turn a branch into a commit. |
88
+ | `readForgeArchive(provider, repo, { ref, maxBytes, signal })` | `{ commit, bytes }`: the `tar.gz` of the repository tree at `ref` and the commit it came from. A branch or tag resolves to its commit first. Pass a non-negative safe integer for `maxBytes` (default 64 MiB). A larger archive rejects with `FORGE_ARCHIVE_TOO_LARGE`. GitHub only. |
85
89
  | `forgeArchive(provider, repo, { ref, signal })` | The repository tree at `ref` as a `tar.gz` stream. GitHub only. Anonymous github.com reads go to `codeload.github.com` and do not use the API limit. |
86
90
  | `forgeGitCredentials({ forge, baseUrl, token, repository })` | The Git smart HTTP remote and the basic auth pair for one repository. |
87
91
  | `forgeGitAuthHeader(credentials)` | The `http.<remote>.extraheader` entry for `GIT_CONFIG_KEY_<n>` and `GIT_CONFIG_VALUE_<n>`. It keeps the token out of process arguments. |
@@ -103,6 +107,7 @@ For Gitea, `useForge()` uses `VITEHUB_GITEA_WEBHOOK_SECRET` (or `FORGES_GITEA_WE
103
107
  | `FORGE_R0006` | A GitHub-only helper got a provider for another Forge. |
104
108
  | `FORGE_R0007` | `githubBranchRuleDetails()` got branch rules that are not complete GitHub rulesets or classic protection. |
105
109
  | `FORGE_R0009` | A GitHub-only helper got a reference that is not a numbered pull request, or an empty input. |
110
+ | `FORGE_ARCHIVE_TOO_LARGE` | `readForgeArchive()` read more than `maxBytes`. It stops the download at the limit. |
106
111
  | `FORGE_RESPONSE_INVALID` | A Forge request returned missing or invalid data. Read the error message for the specific problem. |
107
112
  | `FORGE_UNSUPPORTED` | The `forge` value of a Forge connection is not `github`, `gitlab`, `forgejo`, or `gitea`. |
108
113
 
@@ -0,0 +1,123 @@
1
+ // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/crypto-DydCoK4e.mjs
2
+ const encoder = new TextEncoder();
3
+ function toBytes(value) {
4
+ return typeof value === "string" ? encoder.encode(value) : value;
5
+ }
6
+ function toHex(buffer) {
7
+ return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
8
+ }
9
+ /** Base64 for arbitrary bytes, a byte at a time so a large buffer cannot overflow the call stack. */
10
+ function toBase64(bytes) {
11
+ let binary = "";
12
+ for (const byte of bytes) binary += String.fromCharCode(byte);
13
+ return btoa(binary);
14
+ }
15
+ function toBase64Url(input) {
16
+ return (typeof input === "string" ? btoa(input) : toBase64(input)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
17
+ }
18
+ async function hmacSha256(secret, body) {
19
+ const key = await crypto.subtle.importKey("raw", toBytes(secret), {
20
+ name: "HMAC",
21
+ hash: "SHA-256"
22
+ }, false, ["sign"]);
23
+ return crypto.subtle.sign("HMAC", key, toBytes(body));
24
+ }
25
+ /** Lowercase hex HMAC-SHA256 of `body` under `secret`. */
26
+ async function hmacSha256Hex(secret, body) {
27
+ return toHex(await hmacSha256(secret, body));
28
+ }
29
+ /**
30
+ * Constant-time comparison of two strings. The time taken depends only on the
31
+ * length of `a`, so pass the untrusted value as `a`.
32
+ */
33
+ function timingSafeEqual(a, b) {
34
+ let mismatch = a.length ^ b.length;
35
+ for (let index = 0; index < a.length; index++) mismatch |= a.charCodeAt(index) ^ b.charCodeAt(index % b.length);
36
+ return mismatch === 0;
37
+ }
38
+ function decodePem(pem) {
39
+ const pkcs1 = pem.includes("BEGIN RSA PRIVATE KEY");
40
+ const body = pem.replace(/-----(?:BEGIN|END)[^-]+-----/g, "").replace(/\s+/g, "");
41
+ const binary = atob(body);
42
+ const der = new Uint8Array(binary.length);
43
+ for (let index = 0; index < binary.length; index++) der[index] = binary.charCodeAt(index);
44
+ return {
45
+ der,
46
+ pkcs1
47
+ };
48
+ }
49
+ function derLength(length) {
50
+ if (length < 128) return [length];
51
+ const bytes = [];
52
+ let remaining = length;
53
+ while (remaining > 0) {
54
+ bytes.unshift(remaining & 255);
55
+ remaining >>= 8;
56
+ }
57
+ return [128 | bytes.length, ...bytes];
58
+ }
59
+ /**
60
+ * Wraps a PKCS#1 RSA key in a PKCS#8 `PrivateKeyInfo`. GitHub App keys are
61
+ * distributed as PKCS#1, which Web Crypto cannot import directly.
62
+ */
63
+ function pkcs1ToPkcs8(der) {
64
+ const algorithm = [
65
+ 48,
66
+ 13,
67
+ 6,
68
+ 9,
69
+ 42,
70
+ 134,
71
+ 72,
72
+ 134,
73
+ 247,
74
+ 13,
75
+ 1,
76
+ 1,
77
+ 1,
78
+ 5,
79
+ 0
80
+ ];
81
+ const octetString = [
82
+ 4,
83
+ ...derLength(der.length),
84
+ ...der
85
+ ];
86
+ const contents = [
87
+ 2,
88
+ 1,
89
+ 0,
90
+ ...algorithm,
91
+ ...octetString
92
+ ];
93
+ return new Uint8Array([
94
+ 48,
95
+ ...derLength(contents.length),
96
+ ...contents
97
+ ]);
98
+ }
99
+ /** Signs an RS256 JWT with a PEM-encoded RSA private key. */
100
+ async function signRs256Jwt(privateKeyPem, claims) {
101
+ const { der, pkcs1 } = decodePem(privateKeyPem);
102
+ const key = await crypto.subtle.importKey("pkcs8", pkcs1 ? pkcs1ToPkcs8(der) : der, {
103
+ name: "RSASSA-PKCS1-v1_5",
104
+ hash: "SHA-256"
105
+ }, false, ["sign"]);
106
+ const payload = `${toBase64Url(JSON.stringify({
107
+ alg: "RS256",
108
+ typ: "JWT"
109
+ }))}.${toBase64Url(JSON.stringify(claims))}`;
110
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, encoder.encode(payload));
111
+ return `${payload}.${toBase64Url(new Uint8Array(signature))}`;
112
+ }
113
+ /** The value of a header, whatever the casing of `name`, from a `Headers` object or a plain record. */
114
+ function headerValue(headers, name) {
115
+ if (headers instanceof Headers) return headers.get(name) ?? void 0;
116
+ const lower = name.toLowerCase();
117
+ for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === lower) return value;
118
+ }
119
+ /** A request body as text. */
120
+ function bodyText(body) {
121
+ return typeof body === "string" ? body : new TextDecoder().decode(body);
122
+ }
123
+ export { timingSafeEqual as a, signRs256Jwt as i, headerValue as n, toBase64 as o, hmacSha256Hex as r, bodyText as t };
@@ -1,4 +1,4 @@
1
- import { B as memo, F as hostOf, I as isFirstPage, J as requireIssueOrPull, K as rateLimitPart, M as getManyConcurrently, N as hasEveryLabel, O as createListing, P as hexColour, Q as summariseChecks, R as latestCommentOf, U as milestoneId, V as memoBy, X as resolveToken, Y as requireThread, a as verifyHmacSignature, at as toWarning, ct as changeBase64, d as perKind, dt as inDirectories, et as teamOrg, f as reviewState, g as verb, it as toPullStats, lt as existingFiles, mt as toFileContent, nt as toFileStatus, ot as versionAtLeast, r as nativeEventsFor, rt as toPage, s as WRITE_VERBS, t as eventKindsOf, tt as toDate, u as eventTime, ut as fromBase64, w as actorLogin, y as githubShapedWeb, z as mapConcurrent } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
1
+ import { $ as requireThread, A as createListing, E as actorLogin, F as getManyConcurrently, H as mapConcurrent, I as hasEveryLabel, K as milestoneId, L as hexColour, Q as requireIssueOrPull, R as hostOf, U as memo, V as latestCommentOf, W as memoBy, X as rateLimitPart, a as verifyHmacSignature, at as toDate, c as WRITE_VERBS, ct as toPullStats, et as resolveToken, f as eventTime, ft as changeBase64, ht as inDirectories, it as teamOrg, lt as toWarning, m as reviewState, mt as fromBase64, nt as summariseChecks, ot as toFileStatus, p as perKind, pt as existingFiles, r as nativeEventsFor, st as toPage, t as eventKindsOf, ut as versionAtLeast, v as verb, vt as toFileContent, x as githubShapedWeb, z as isFirstPage } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
2
2
  import { A as toMergeError, T as UnsupportedOperationError, b as NotFoundError, k as soleMergeMethod, m as ForgeError, n as isNamespaceRef, s as reactionContent, u as BranchMovedError } from "./model-Biiu1CfI-CVLamGai.js";
3
3
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/web-C0rMyC0A.mjs
4
4
  const RESERVED_PATHS = [
@@ -1027,7 +1027,7 @@ function forgejoWebhooks(profile) {
1027
1027
  return ({ options, origin }) => ({
1028
1028
  events: FORGEJO_WEBHOOK_EVENTS,
1029
1029
  verify: (delivery) => verifyForgejoSignature(delivery, options.webhookSecret, profile.headers),
1030
- translate: async (delivery) => (await import("./events-DXE-Ul2S-BzTkugIK.js")).translateForgejoWebhook(origin, delivery, profile.headers)
1030
+ translate: async (delivery) => (await import("./events-DXE-Ul2S-U2BH_jTW.js")).translateForgejoWebhook(origin, delivery, profile.headers)
1031
1031
  });
1032
1032
  }
1033
1033
  const YAML_FILE = /\.ya?ml$/i;
@@ -1528,7 +1528,7 @@ function setupForgejo({ options, origin, fetcher: baseFetcher, baseUrl }, profil
1528
1528
  return released(isGitea ? giteaMinimum : forgejoMinimum);
1529
1529
  }
1530
1530
  async function feedPage(path, listOptions, query) {
1531
- const { toFeedEvent } = await import("./feed-iWegqepj-ConxMpg4.js");
1531
+ const { toFeedEvent } = await import("./feed-iWegqepj-id4yPYnY.js");
1532
1532
  return list(path, listOptions, (raw) => toFeedEvent(origin, raw), { query });
1533
1533
  }
1534
1534
  async function setBlocked(scope, login, blocked, options) {
@@ -1,5 +1,6 @@
1
- import { gt as headerValue, ht as bodyText, i as refEvent, p as snapshotOfThread, tt as toDate, u as eventTime } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
2
- import { a as toRepoRef, i as toPullThread, n as toActor, r as toIssueThread, t as FORGE } from "./gitee-CKt4pEC0-BuLWggck.js";
1
+ import { n as headerValue, t as bodyText } from "./crypto-DydCoK4e-BCG61qh5.js";
2
+ import { at as toDate, f as eventTime, h as snapshotOfThread, i as refEvent } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
3
+ import { a as toRepoRef, i as toPullThread, n as toActor, r as toIssueThread, t as FORGE } from "./gitee-CKt4pEC0-dsy0hiLG.js";
3
4
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/events-BL0zcgMf.mjs
4
5
  const STATES = {
5
6
  open: "open",
@@ -1,6 +1,7 @@
1
- import { gt as headerValue, h as threadSnapshot, ht as bodyText, i as refEvent, l as eventAction, tt as toDate, u as eventTime } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
1
+ import { n as headerValue, t as bodyText } from "./crypto-DydCoK4e-BCG61qh5.js";
2
2
  import { E as WebhookVerificationError } from "./model-Biiu1CfI-CVLamGai.js";
3
- import { a as toRepoRef, i as toLabel, n as approvalId, o as toState, r as toActor, t as FORGE } from "./gitlab-CS0shW2u.js";
3
+ import { _ as threadSnapshot, at as toDate, d as eventAction, f as eventTime, i as refEvent } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
4
+ import { a as toRepoRef, i as toLabel, n as approvalId, o as toState, r as toActor, t as FORGE } from "./gitlab-AAJN-eVR.js";
4
5
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/events-DDdJnmD2.mjs
5
6
  const EVENT_HEADER = "x-gitlab-event";
6
7
  function snapshotOf(instance, raw) {
@@ -1,6 +1,7 @@
1
- import { f as reviewState, gt as headerValue, h as threadSnapshot, ht as bodyText, i as refEvent, it as toPullStats, l as eventAction, tt as toDate, u as eventTime } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
1
+ import { n as headerValue, t as bodyText } from "./crypto-DydCoK4e-BCG61qh5.js";
2
2
  import { E as WebhookVerificationError } from "./model-Biiu1CfI-CVLamGai.js";
3
- import { a as toThreadState, i as toRepoRef, n as toIssueType, r as toLabels, t as toActor } from "./github-CHzhqYOr.js";
3
+ import { _ as threadSnapshot, at as toDate, ct as toPullStats, d as eventAction, f as eventTime, i as refEvent, m as reviewState } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
4
+ import { a as toThreadState, i as toRepoRef, n as toIssueType, r as toLabels, t as toActor } from "./github-Csy_qzZc.js";
4
5
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/events-DHqSJ5KI.mjs
5
6
  const EVENT_HEADER = "x-github-event";
6
7
  const DELIVERY_HEADER = "x-github-delivery";
@@ -1,6 +1,7 @@
1
- import { f as reviewState, ht as bodyText, i as refEvent, l as eventAction, n as firstHeader, p as snapshotOfThread, tt as toDate, u as eventTime } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
1
+ import { t as bodyText } from "./crypto-DydCoK4e-BCG61qh5.js";
2
2
  import { E as WebhookVerificationError } from "./model-Biiu1CfI-CVLamGai.js";
3
- import { a as toActor, o as toRepoRef, s as toThread, t as FORGEJO_HEADERS } from "./definition-BQFdu9ti-WxMjcAEl.js";
3
+ import { at as toDate, d as eventAction, f as eventTime, h as snapshotOfThread, i as refEvent, m as reviewState, n as firstHeader } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
4
+ import { a as toActor, o as toRepoRef, s as toThread, t as FORGEJO_HEADERS } from "./definition-BQFdu9ti-BURTyX81.js";
4
5
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/events-DXE-Ul2S.mjs
5
6
  const EVENT_KINDS = {
6
7
  issue_comment: "comment",
@@ -1,5 +1,5 @@
1
- import { i as refEvent, l as eventAction, tt as toDate, u as eventTime } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
2
- import { n as approvalId, r as toActor, s as toThreadKind, t as FORGE } from "./gitlab-CS0shW2u.js";
1
+ import { at as toDate, d as eventAction, f as eventTime, i as refEvent } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
2
+ import { n as approvalId, r as toActor, s as toThreadKind, t as FORGE } from "./gitlab-AAJN-eVR.js";
3
3
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/feed-B1OiHFg0.mjs
4
4
  const FEED_STATES = {
5
5
  opened: {
@@ -1,5 +1,5 @@
1
- import { i as refEvent, l as eventAction, tt as toDate, u as eventTime } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
2
- import { a as toRepoRef, n as toActor, t as FORGE } from "./gitee-CKt4pEC0-BuLWggck.js";
1
+ import { at as toDate, d as eventAction, f as eventTime, i as refEvent } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
2
+ import { a as toRepoRef, n as toActor, t as FORGE } from "./gitee-CKt4pEC0-dsy0hiLG.js";
3
3
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/feed-DROLF1tb.mjs
4
4
  /** Summaries of the feed event types that have no shared kind. */
5
5
  const FEED_SUMMARIES = { WatchEvent: "watched the repository" };
@@ -1,5 +1,5 @@
1
- import { i as refEvent, tt as toDate, u as eventTime } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
2
- import { a as toActor, o as toRepoRef } from "./definition-BQFdu9ti-WxMjcAEl.js";
1
+ import { at as toDate, f as eventTime, i as refEvent } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
2
+ import { a as toActor, o as toRepoRef } from "./definition-BQFdu9ti-BURTyX81.js";
3
3
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/feed-iWegqepj.mjs
4
4
  /** Activity types about an issue or a pull request, whose `content` starts with its number. */
5
5
  const FEED_THREAD_OPS = {
@@ -1,5 +1,5 @@
1
- import { c as defineForgeProvider } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
2
- import { i as forgejoDefinition, n as FORGEJO_PROFILE } from "./definition-BQFdu9ti-WxMjcAEl.js";
1
+ import { u as defineForgeProvider } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
2
+ import { i as forgejoDefinition, n as FORGEJO_PROFILE } from "./definition-BQFdu9ti-BURTyX81.js";
3
3
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/forgejo/index.mjs
4
4
  /** Creates a Forgejo provider for Codeberg or any self-hosted Forgejo instance. */
5
5
  const forgejo = /* @__PURE__ */ defineForgeProvider(/* @__PURE__ */ forgejoDefinition(FORGEJO_PROFILE));
@@ -1,5 +1,5 @@
1
- import { c as defineForgeProvider } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
2
- import { c as GITEA_WEB, i as forgejoDefinition, r as GITEA_HEADERS } from "./definition-BQFdu9ti-WxMjcAEl.js";
1
+ import { u as defineForgeProvider } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
2
+ import { c as GITEA_WEB, i as forgejoDefinition, r as GITEA_HEADERS } from "./definition-BQFdu9ti-BURTyX81.js";
3
3
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/gitea/index.mjs
4
4
  /** Creates a Gitea provider for gitea.com or any self-hosted Gitea instance. */
5
5
  const gitea = /* @__PURE__ */ defineForgeProvider(/* @__PURE__ */ forgejoDefinition({
@@ -1,4 +1,4 @@
1
- import { tt as toDate } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
1
+ import { at as toDate } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
2
2
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/gitee-CKt4pEC0.mjs
3
3
  const FORGE = "gitee";
4
4
  function toActor(instance, user) {
@@ -1,5 +1,6 @@
1
- import { B as memo, C as abortable, D as createFetcher, E as checkRunState, F as hostOf, G as rateLimitOf, I as isFirstPage, J as requireIssueOrPull, K as rateLimitPart, L as iteratePages, M as getManyConcurrently, O as createListing, Q as summariseChecks, R as latestCommentOf, T as anySignal, U as milestoneId, W as phased, X as resolveToken, Y as requireThread, Z as sleep, _ as OWNER_NAME, _t as signRs256Jwt, a as verifyHmacSignature, at as toWarning, c as defineForgeProvider, ct as changeBase64, d as perKind, dt as inDirectories, et as teamOrg, f as reviewState, ft as isSha, g as verb, it as toPullStats, j as forgeIterable, k as degradesToWarning, lt as existingFiles, m as supportOnly, mt as toFileContent, nt as toFileStatus, ot as versionAtLeast, pt as splitMessage, q as rateLimitReset, r as nativeEventsFor, rt as toPage, s as WRITE_VERBS, t as eventKindsOf, tt as toDate, u as eventTime, ut as fromBase64, w as actorLogin, y as githubShapedWeb } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
1
+ import { $ as requireThread, A as createListing, B as iteratePages, D as anySignal, E as actorLogin, F as getManyConcurrently, J as phased, K as milestoneId, M as degradesToWarning, O as checkRunState, P as forgeIterable, Q as requireIssueOrPull, R as hostOf, T as abortable, U as memo, V as latestCommentOf, X as rateLimitPart, Y as rateLimitOf, Z as rateLimitReset, _t as splitMessage, a as verifyHmacSignature, at as toDate, c as WRITE_VERBS, ct as toPullStats, et as resolveToken, f as eventTime, ft as changeBase64, g as supportOnly, gt as isSha, ht as inDirectories, it as teamOrg, k as createFetcher, lt as toWarning, m as reviewState, mt as fromBase64, nt as summariseChecks, ot as toFileStatus, p as perKind, pt as existingFiles, r as nativeEventsFor, st as toPage, t as eventKindsOf, tt as sleep, u as defineForgeProvider, ut as versionAtLeast, v as verb, vt as toFileContent, x as githubShapedWeb, y as OWNER_NAME, z as isFirstPage } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
2
2
  import { A as toMergeError, O as isSecondaryRateLimit, S as ReadOnlyError, T as UnsupportedOperationError, _ as InsufficientScopeError, b as NotFoundError, f as ForbiddenError, g as ForgeTimeoutError, k as soleMergeMethod, l as AuthenticationRequiredError, m as ForgeError, n as isNamespaceRef, p as ForgeApiError, r as isResolvedThread, s as reactionContent, t as REACTION_CONTENTS, u as BranchMovedError, v as MergeBlockedError, x as RateLimitedError, y as MergeConflictError } from "./model-Biiu1CfI-CVLamGai.js";
3
+ import { i as signRs256Jwt } from "./crypto-DydCoK4e-BCG61qh5.js";
3
4
  import { t as toAuthorAssociation } from "./association-Ds6Tgs0W-CgBVH3ii.js";
4
5
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/web-C4ZtN2uk.mjs
5
6
  const RESERVED_PATHS = [
@@ -225,7 +226,7 @@ function graphqlOperations(document) {
225
226
  }
226
227
  function createGraphQLClient(fetcher, url, context) {
227
228
  return async (document, variables, options) => {
228
- const query = typeof document === "string" ? (await import("./graphql-DxRA9BGO-BBbmTmWi.js"))[document] : document.query;
229
+ const query = typeof document === "string" ? (await import("./graphql-DxRA9BGO-CiA7HWVp.js"))[document] : document.query;
229
230
  const operationName = graphqlOperations(query)[0]?.name;
230
231
  const { data, response } = await fetcher.json(url, {
231
232
  method: "POST",
@@ -1535,7 +1536,7 @@ function githubWebhooks(events) {
1535
1536
  return ({ options, origin }) => ({
1536
1537
  events,
1537
1538
  verify: (delivery) => verifyGitHubSignature(delivery, options.webhookSecret),
1538
- translate: async (delivery) => (await import("./events-DHqSJ5KI-z2-5_1vo.js")).translateGitHubWebhook(origin, delivery)
1539
+ translate: async (delivery) => (await import("./events-DHqSJ5KI-DfFbbwBb.js")).translateGitHubWebhook(origin, delivery)
1539
1540
  });
1540
1541
  }
1541
1542
  const DISCUSSION_CLOSE_REASONS = {
@@ -1665,7 +1666,7 @@ function setupGitHub(ctx, profile) {
1665
1666
  })).values()];
1666
1667
  let result;
1667
1668
  try {
1668
- const { query, variables } = (await import("./graphql-DxRA9BGO-BBbmTmWi.js")).recentDiscussionsQuery(repos);
1669
+ const { query, variables } = (await import("./graphql-DxRA9BGO-CiA7HWVp.js")).recentDiscussionsQuery(repos);
1669
1670
  result = await graphql({ query }, variables);
1670
1671
  } catch (error) {
1671
1672
  if (error instanceof InsufficientScopeError || error instanceof ForgeApiError && error.status === 200) return [toWarning("discussion_unresolved", error)];
@@ -1747,7 +1748,7 @@ function setupGitHub(ctx, profile) {
1747
1748
  number: Number(ref.number)
1748
1749
  }, options)).repository?.discussion;
1749
1750
  if (!discussion) throw new NotFoundError(`Discussion ${ref.number} not found`, 404, "", context);
1750
- return (await import("./graphql-DxRA9BGO-BBbmTmWi.js")).toDiscussionThread(ref, discussion);
1751
+ return (await import("./graphql-DxRA9BGO-CiA7HWVp.js")).toDiscussionThread(ref, discussion);
1751
1752
  }
1752
1753
  async function discussionCommentPage(ref, listOptions) {
1753
1754
  const comments = (await graphql("DISCUSSION_COMMENTS", {
@@ -1828,7 +1829,7 @@ function setupGitHub(ctx, profile) {
1828
1829
  ref
1829
1830
  });
1830
1831
  if (!batchable.length) return results;
1831
- const g = await import("./graphql-DxRA9BGO-BBbmTmWi.js");
1832
+ const g = await import("./graphql-DxRA9BGO-CiA7HWVp.js");
1832
1833
  for (let start = 0; start < batchable.length; start += GRAPHQL_BATCH) {
1833
1834
  const chunk = batchable.slice(start, start + GRAPHQL_BATCH);
1834
1835
  const { query, variables } = g.threadsBatchQuery(chunk.map((item) => item.ref));
@@ -1890,7 +1891,7 @@ function setupGitHub(ctx, profile) {
1890
1891
  async function sponsorableMany(logins, options) {
1891
1892
  const results = Array.from({ length: logins.length });
1892
1893
  if (!logins.length) return results;
1893
- const g = await import("./graphql-DxRA9BGO-BBbmTmWi.js");
1894
+ const g = await import("./graphql-DxRA9BGO-CiA7HWVp.js");
1894
1895
  const url = graphqlUrl(baseUrl);
1895
1896
  for (let start = 0; start < logins.length; start += SPONSORABLE_BATCH) {
1896
1897
  const chunk = logins.slice(start, start + SPONSORABLE_BATCH);
@@ -1984,7 +1985,7 @@ function setupGitHub(ctx, profile) {
1984
1985
  field: query.sort === "created" || !query.sort ? "CREATED_AT" : "UPDATED_AT",
1985
1986
  direction: direction.toUpperCase()
1986
1987
  }, query);
1987
- const { toDiscussionThread } = await import("./graphql-DxRA9BGO-BBbmTmWi.js");
1988
+ const { toDiscussionThread } = await import("./graphql-DxRA9BGO-CiA7HWVp.js");
1988
1989
  const discussions = data.repository?.discussions;
1989
1990
  return {
1990
1991
  items: (discussions?.nodes ?? []).map((node) => toDiscussionThread({
@@ -2095,7 +2096,7 @@ function setupGitHub(ctx, profile) {
2095
2096
  async function commentsPage(thread, listOptions = {}) {
2096
2097
  const ref = requireThread(thread, context);
2097
2098
  if (ref.kind === "discussion") {
2098
- const [page, { toDiscussionComment }] = await Promise.all([discussionCommentPage(ref, listOptions), import("./graphql-DxRA9BGO-BBbmTmWi.js")]);
2099
+ const [page, { toDiscussionComment }] = await Promise.all([discussionCommentPage(ref, listOptions), import("./graphql-DxRA9BGO-CiA7HWVp.js")]);
2099
2100
  return {
2100
2101
  ...page,
2101
2102
  items: page.items.map(({ comment }) => toDiscussionComment(ref, comment))
@@ -2126,7 +2127,7 @@ function setupGitHub(ctx, profile) {
2126
2127
  id,
2127
2128
  reason: reason?.toUpperCase() ?? null
2128
2129
  }, options_)).closeDiscussion : (await graphql("REOPEN_DISCUSSION", { id }, options_)).reopenDiscussion;
2129
- return (await import("./graphql-DxRA9BGO-BBbmTmWi.js")).toDiscussionThread(ref, data.discussion);
2130
+ return (await import("./graphql-DxRA9BGO-CiA7HWVp.js")).toDiscussionThread(ref, data.discussion);
2130
2131
  }
2131
2132
  const reason = options_.reasonRaw ?? options_.reason;
2132
2133
  const { data } = await fetcher.json(threadPath(ref), {
@@ -2380,7 +2381,7 @@ function setupGitHub(ctx, profile) {
2380
2381
  number: Number(ref.number),
2381
2382
  first: Math.min(listOptions.perPage ?? 50, 100),
2382
2383
  after: listOptions.cursor?.token ?? null
2383
- }, listOptions), import("./graphql-DxRA9BGO-BBbmTmWi.js")]);
2384
+ }, listOptions), import("./graphql-DxRA9BGO-CiA7HWVp.js")]);
2384
2385
  const pull = data.repository?.pullRequest;
2385
2386
  if (!pull) throw new NotFoundError(`Pull request ${ref.number} not found`, 404, "", context);
2386
2387
  const { nodes, pageInfo } = pull.reviewThreads;
@@ -2407,7 +2408,7 @@ function setupGitHub(ctx, profile) {
2407
2408
  if (thread.kind === "discussion") {
2408
2409
  const data = await graphql("GET_DISCUSSION_COMMENT", { id: ref.id }, options);
2409
2410
  if (!data.node?.id) throw new NotFoundError(`Comment ${ref.id} not found`, 404, "", context);
2410
- return (await import("./graphql-DxRA9BGO-BBbmTmWi.js")).toDiscussionComment(thread, data.node);
2411
+ return (await import("./graphql-DxRA9BGO-CiA7HWVp.js")).toDiscussionComment(thread, data.node);
2411
2412
  }
2412
2413
  const { data } = await fetcher.json(commentPath(ref), { signal: options?.signal });
2413
2414
  return toComment(thread, data);
@@ -2464,7 +2465,7 @@ function setupGitHub(ctx, profile) {
2464
2465
  number: Number(ref.number),
2465
2466
  first: Math.min(listOptions.perPage ?? 50, 100),
2466
2467
  after: listOptions.cursor?.token ?? null
2467
- }, listOptions), import("./graphql-DxRA9BGO-BBbmTmWi.js")]);
2468
+ }, listOptions), import("./graphql-DxRA9BGO-CiA7HWVp.js")]);
2468
2469
  const references = data.repository?.thread?.references;
2469
2470
  if (!references) throw new NotFoundError(`Thread ${ref.number} not found`, 404, "", context);
2470
2471
  return {
@@ -2786,7 +2787,7 @@ function setupGitHub(ctx, profile) {
2786
2787
  signal: listOptions.signal
2787
2788
  });
2788
2789
  const poll = recordPoll(path, listOptions.cursor, result.response);
2789
- const { toFeedEvents } = await import("./events-DHqSJ5KI-z2-5_1vo.js");
2790
+ const { toFeedEvents } = await import("./events-DHqSJ5KI-DfFbbwBb.js");
2790
2791
  const page = toPage(result, (raw) => toFeedEvents(context, raw));
2791
2792
  return {
2792
2793
  ...page,
@@ -2881,7 +2882,7 @@ function setupGitHub(ctx, profile) {
2881
2882
  }
2882
2883
  async function templates(repo, options = {}) {
2883
2884
  const signal = options.signal;
2884
- return (await import("./templates-0m5QBVIh-D1fZeoC-.js")).readTemplates(repo, options.kind ? [options.kind] : ["issue", "pull_request"], {
2885
+ return (await import("./templates-0m5QBVIh-Bop0TOo9.js")).readTemplates(repo, options.kind ? [options.kind] : ["issue", "pull_request"], {
2885
2886
  list: async (ref, path) => {
2886
2887
  const { data } = await fetcher.json(`${repoPath(ref)}/contents${path ? `/${path.split("/").map(encodeURIComponent).join("/")}` : ""}`, { signal });
2887
2888
  return Array.isArray(data) ? data : [];
@@ -3003,7 +3004,7 @@ function setupGitHub(ctx, profile) {
3003
3004
  expectedHeadOid: head,
3004
3005
  message: splitMessage(input.message),
3005
3006
  fileChanges
3006
- } }, options), import("./graphql-DxRA9BGO-BBbmTmWi.js")]);
3007
+ } }, options), import("./graphql-DxRA9BGO-CiA7HWVp.js")]);
3007
3008
  return toGraphQLCommit(repo, data.createCommitOnBranch.commit);
3008
3009
  } catch (error) {
3009
3010
  if (input.createFrom !== void 0) await swapBranch(repo, input.branch, head, ZERO_OID).catch(() => {});
@@ -3171,7 +3172,7 @@ function setupGitHub(ctx, profile) {
3171
3172
  const [data, { toGraphQLActor, GRAPHQL_REACTIONS }] = await Promise.all([graphql("NODE_REACTIONS", {
3172
3173
  id,
3173
3174
  after: listOptions.cursor?.token ?? null
3174
- }, listOptions), import("./graphql-DxRA9BGO-BBbmTmWi.js")]);
3175
+ }, listOptions), import("./graphql-DxRA9BGO-CiA7HWVp.js")]);
3175
3176
  const reactions = data.node?.reactions;
3176
3177
  return {
3177
3178
  items: (reactions?.nodes ?? []).flatMap((raw) => {
@@ -3209,7 +3210,7 @@ function setupGitHub(ctx, profile) {
3209
3210
  if (thread.kind === "discussion") {
3210
3211
  await graphql("ADD_REACTION", {
3211
3212
  id: "thread" in target ? target.id : await nodeId(thread, options),
3212
- content: (await import("./graphql-DxRA9BGO-BBbmTmWi.js")).REACTION_CONTENT[reaction]
3213
+ content: (await import("./graphql-DxRA9BGO-CiA7HWVp.js")).REACTION_CONTENT[reaction]
3213
3214
  }, options);
3214
3215
  return;
3215
3216
  }
@@ -3224,7 +3225,7 @@ function setupGitHub(ctx, profile) {
3224
3225
  if (thread.kind === "discussion") {
3225
3226
  await graphql("REMOVE_REACTION", {
3226
3227
  id: "thread" in target ? target.id : await nodeId(thread, options),
3227
- content: (await import("./graphql-DxRA9BGO-BBbmTmWi.js")).REACTION_CONTENT[reaction]
3228
+ content: (await import("./graphql-DxRA9BGO-CiA7HWVp.js")).REACTION_CONTENT[reaction]
3228
3229
  }, options);
3229
3230
  return;
3230
3231
  }
@@ -3691,7 +3692,7 @@ function setupGitHub(ctx, profile) {
3691
3692
  eventsPage: verb(true, async (thread, listOptions = {}) => {
3692
3693
  const ref = requireThread(thread, context);
3693
3694
  if (ref.kind === "discussion") {
3694
- const [page, { toDiscussionCommentEvent }] = await Promise.all([discussionCommentPage(ref, listOptions), import("./graphql-DxRA9BGO-BBbmTmWi.js")]);
3695
+ const [page, { toDiscussionCommentEvent }] = await Promise.all([discussionCommentPage(ref, listOptions), import("./graphql-DxRA9BGO-CiA7HWVp.js")]);
3695
3696
  return {
3696
3697
  ...page,
3697
3698
  items: page.items.map(({ comment, isReply }) => toDiscussionCommentEvent(ref, comment, isReply))
@@ -3762,7 +3763,7 @@ function setupGitHub(ctx, profile) {
3762
3763
  id: await discussionId(ref, options),
3763
3764
  body
3764
3765
  }, options);
3765
- return (await import("./graphql-DxRA9BGO-BBbmTmWi.js")).toDiscussionComment(ref, data.addDiscussionComment.comment);
3766
+ return (await import("./graphql-DxRA9BGO-CiA7HWVp.js")).toDiscussionComment(ref, data.addDiscussionComment.comment);
3766
3767
  }
3767
3768
  const { data } = await fetcher.json(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/comments`, {
3768
3769
  method: "POST",
@@ -3782,7 +3783,7 @@ function setupGitHub(ctx, profile) {
3782
3783
  id: ref.id,
3783
3784
  body
3784
3785
  }, options);
3785
- return (await import("./graphql-DxRA9BGO-BBbmTmWi.js")).toDiscussionComment(thread, data.updateDiscussionComment.comment);
3786
+ return (await import("./graphql-DxRA9BGO-CiA7HWVp.js")).toDiscussionComment(thread, data.updateDiscussionComment.comment);
3786
3787
  }
3787
3788
  const { data } = await fetcher.json(commentPath(ref), {
3788
3789
  method: "PATCH",
@@ -3884,7 +3885,7 @@ function setupGitHub(ctx, profile) {
3884
3885
  title: input.title,
3885
3886
  body: input.body
3886
3887
  }, options);
3887
- return (await import("./graphql-DxRA9BGO-BBbmTmWi.js")).toDiscussionThread(ref, data.updateDiscussion.discussion);
3888
+ return (await import("./graphql-DxRA9BGO-CiA7HWVp.js")).toDiscussionThread(ref, data.updateDiscussion.discussion);
3888
3889
  }
3889
3890
  const target = requireIssueOrPull(ref, context, "update");
3890
3891
  const json = {
@@ -1,4 +1,4 @@
1
- import { $ as syntheticReview, A as firstPageEtag, B as memo, H as mergeCommitMessage, I as isFirstPage, J as requireIssueOrPull, K as rateLimitPart, L as iteratePages, M as getManyConcurrently, O as createListing, P as hexColour, S as webUrlFor, U as milestoneId, V as memoBy, W as phased, X as resolveToken, Y as requireThread, at as toWarning, b as lineOf, c as defineForgeProvider, ct as changeBase64, d as perKind, et as teamOrg, g as verb, k as degradesToWarning, lt as existingFiles, mt as toFileContent, o as verifySharedToken, ot as versionAtLeast, r as nativeEventsFor, rt as toPage, s as WRITE_VERBS, st as withEtag, t as eventKindsOf, tt as toDate, u as eventTime, ut as fromBase64, v as bareSha, x as rangeOf, z as mapConcurrent } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
1
+ import { $ as requireThread, A as createListing, B as iteratePages, C as rangeOf, F as getManyConcurrently, G as mergeCommitMessage, H as mapConcurrent, J as phased, K as milestoneId, L as hexColour, M as degradesToWarning, N as firstPageEtag, Q as requireIssueOrPull, S as lineOf, U as memo, W as memoBy, X as rateLimitPart, at as toDate, b as bareSha, c as WRITE_VERBS, dt as withEtag, et as resolveToken, f as eventTime, ft as changeBase64, it as teamOrg, lt as toWarning, mt as fromBase64, o as verifySharedToken, p as perKind, pt as existingFiles, r as nativeEventsFor, rt as syntheticReview, st as toPage, t as eventKindsOf, u as defineForgeProvider, ut as versionAtLeast, v as verb, vt as toFileContent, w as webUrlFor, z as isFirstPage } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
2
2
  import { A as toMergeError, C as TokenRevokedError, T as UnsupportedOperationError, _ as InsufficientScopeError, b as NotFoundError, f as ForbiddenError, k as soleMergeMethod, l as AuthenticationRequiredError, n as isNamespaceRef, p as ForgeApiError, s as reactionContent, u as BranchMovedError, w as UnresolvedThreadError } from "./model-Biiu1CfI-CVLamGai.js";
3
3
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/web-DpJoUDx4.mjs
4
4
  const SECTIONS = {
@@ -1083,7 +1083,7 @@ async function verifyGitLabToken(delivery, secret) {
1083
1083
  const gitlabWebhooks = ({ options, instance }) => ({
1084
1084
  events: GITLAB_WEBHOOK_EVENTS,
1085
1085
  verify: (delivery) => verifyGitLabToken(delivery, options.webhookSecret),
1086
- translate: async (delivery) => (await import("./events-DDdJnmD2-BSMoOqjV.js")).translateGitLabWebhook(instance, delivery)
1086
+ translate: async (delivery) => (await import("./events-DDdJnmD2-BhNdO8U_.js")).translateGitLabWebhook(instance, delivery)
1087
1087
  });
1088
1088
  const PROJECT_ORDER = {
1089
1089
  created: "created_at",
@@ -1645,7 +1645,7 @@ const gitlab = /* @__PURE__ */ defineForgeProvider({
1645
1645
  });
1646
1646
  const warnings = [];
1647
1647
  if (!repo) await resolveProjects([...new Set((result.data ?? []).flatMap((raw) => typeof raw.project_id === "number" ? [raw.project_id] : []))].filter((id) => !projectRefs.has(id)), listOptions.signal, warnings);
1648
- const { toFeedEvent } = await import("./feed-B1OiHFg0-DevZZe0y.js");
1648
+ const { toFeedEvent } = await import("./feed-B1OiHFg0-a2dzl1Va.js");
1649
1649
  return toPage(result, (raw) => toFeedEvent(instance, raw, repo ?? (typeof raw.project_id === "number" ? projectRefs.get(raw.project_id) : void 0)), warnings);
1650
1650
  }
1651
1651
  async function setSubscribed(thread, subscribed, options) {
@@ -1,4 +1,4 @@
1
- import { it as toPullStats, tt as toDate, u as eventTime } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
1
+ import { at as toDate, ct as toPullStats, f as eventTime } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
2
2
  import { t as toAuthorAssociation } from "./association-Ds6Tgs0W-CgBVH3ii.js";
3
3
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/graphql-DxRA9BGO.mjs
4
4
  const ACTOR_FIELDS = `__typename login avatarUrl url ... on User { databaseId name } ... on Bot { databaseId }`;
package/dist/index.d.ts CHANGED
@@ -3797,10 +3797,12 @@ interface ForgeEnvField {
3797
3797
  /** Host variable names in lookup order. The `VITEHUB_` name comes first, then the `forges` name. */
3798
3798
  names: readonly [string, ...string[]];
3799
3799
  secret?: true;
3800
+ /** What the value unlocks, in one sentence. Server Env shows it next to the declaration. */
3801
+ description: string;
3800
3802
  }
3801
3803
  /** Server Env fields of each Forge. */
3802
3804
  type ForgeEnv = {
3803
- github: Record<"appId" | "installationId" | "appOwner" | "appInstallations" | "privateKey" | "privateKeyPath" | "token" | "webhookSecret", ForgeEnvField>;
3805
+ github: Record<"appId" | "baseUrl" | "installationId" | "appOwner" | "appInstallations" | "privateKey" | "privateKeyPath" | "token" | "webhookSecret", ForgeEnvField>;
3804
3806
  gitlab: Record<"baseUrl" | "token" | "webhookSecret", ForgeEnvField>;
3805
3807
  forgejo: Record<"baseUrl" | "token" | "webhookSecret", ForgeEnvField>;
3806
3808
  gitea: Record<"baseUrl" | "token" | "webhookSecret", ForgeEnvField>;
@@ -3865,7 +3867,7 @@ interface UseForgeOptions<TKind extends ForgeKind = "github"> {
3865
3867
  forge?: TKind;
3866
3868
  /**
3867
3869
  * GitHub: the API base, for GitHub Enterprise Server. GitLab, Forgejo and Gitea: the instance root.
3868
- * Default for GitLab, Forgejo and Gitea: `VITEHUB_GITLAB_BASE_URL`, `VITEHUB_FORGEJO_BASE_URL` or `VITEHUB_GITEA_BASE_URL`.
3870
+ * Default: `VITEHUB_GITHUB_BASE_URL`, `VITEHUB_GITLAB_BASE_URL`, `VITEHUB_FORGEJO_BASE_URL` or `VITEHUB_GITEA_BASE_URL`.
3869
3871
  */
3870
3872
  baseUrl?: string;
3871
3873
  /** Default: the bindings of the active Cloudflare request, then `process.env`. */
@@ -3941,6 +3943,24 @@ interface Forge$1<TKind extends ForgeKind = ForgeKind> {
3941
3943
  * ```
3942
3944
  */
3943
3945
  export declare function useForge<TKind extends ForgeKind = "github">(options?: UseForgeOptions<TKind>): Forge$1<TKind>;
3946
+ /** What `checkForge()` found: the Forge and how it signs in. */
3947
+ interface ForgeCheck<TKind extends ForgeKind = ForgeKind> {
3948
+ kind: TKind;
3949
+ auth: "app" | "token";
3950
+ }
3951
+ /** Codes that `checkForge()` returns. */
3952
+ type ForgeCheckErrorCode = "FORGE_MISSING_ENV" | "FORGE_INVALID_ENV";
3953
+ /**
3954
+ * Checks the Forge env and sends no request, for example for a Setup page. It returns `[undefined, { kind, auth }]`
3955
+ * when local configuration is valid, or `[error, undefined]` with a configuration error. It checks the base URL
3956
+ * and signs locally with the GitHub App private key, but does not check that the forge accepts the credentials.
3957
+ *
3958
+ * ```ts
3959
+ * const [error] = await checkForge()
3960
+ * if (error) return { configured: false, fix: error.fix }
3961
+ * ```
3962
+ */
3963
+ export declare function checkForge<TKind extends ForgeKind = "github">(options?: UseForgeOptions<TKind>): Promise<Result<ForgeCheck<TKind>, ForgeCheckErrorCode>>;
3944
3964
  interface ForgeArchiveOptions {
3945
3965
  /** Branch, tag or commit sha. */
3946
3966
  ref: string;
@@ -3954,6 +3974,28 @@ interface ForgeArchiveOptions {
3954
3974
  * (https://github.com/danielroe/forges/issues/191).
3955
3975
  */
3956
3976
  export declare function forgeArchive(provider: ForgeProvider, repo: RepoRef, options: ForgeArchiveOptions): Promise<ReadableStream<Uint8Array>>;
3977
+ interface ReadForgeArchiveOptions {
3978
+ /** Branch, tag or commit sha. A branch or tag resolves to its commit first, so `commit` names the archived tree. */
3979
+ ref: string;
3980
+ /** The largest archive to read, compressed. Pass a non-negative safe integer. Default: 64 MiB. */
3981
+ maxBytes?: number;
3982
+ signal?: AbortSignal;
3983
+ }
3984
+ interface ForgeArchive {
3985
+ /** The full commit sha of the archived tree. */
3986
+ commit: string;
3987
+ /** The `tar.gz` bytes. */
3988
+ bytes: Uint8Array<ArrayBuffer>;
3989
+ }
3990
+ /**
3991
+ * The repository tree at `ref` as `tar.gz` bytes, with the commit it came from. Reads at most `maxBytes` (64 MiB by
3992
+ * default). GitHub only.
3993
+ *
3994
+ * ```ts
3995
+ * const { commit, bytes } = await readForgeArchive(provider, repo, { ref: "main", maxBytes: 32 * 1024 * 1024 })
3996
+ * ```
3997
+ */
3998
+ export declare function readForgeArchive(provider: ForgeProvider, repo: RepoRef, options: ReadForgeArchiveOptions): Promise<ForgeArchive>;
3957
3999
  /**
3958
4000
  * The bytes of one Git blob, by its sha. The blob of a symlink holds the link target.
3959
4001
  * Gap: `forges` reads files by path only, and GitHub follows a symlink path to its target.
@@ -4143,4 +4185,4 @@ export declare function githubInstallationRouting(env: GitHubInstallationEnv): G
4143
4185
  * reach the repository.
4144
4186
  */
4145
4187
  export declare function githubInstallationFor(routing: GitHubInstallationRouting, repository: string | undefined): number | undefined;
4146
- export { type BaseOptions, BranchMovedError, type BranchRules, type Check, type CiRun, type CiRunRef, type Commit, type Forge$1 as Forge, ForgeApiError, type ForgeAppIdentity, type ForgeArchiveOptions, type ForgeCachedResponse, type ForgeCallOptions, type ForgeCommitFilesInput, type ForgeConditionalRequests, type ForgeConnection, type ForgeEnv, type ForgeEnvField, type ForgeEnvSource, type ForgeErrorCode, type ForgeFileChange, type ForgeFileMode, type ForgeGitCredentials, type ForgeGitCredentialsInput, type ForgeKind, type ForgeMemoryCacheOptions, type ForgeMergeOptions, type ForgeProvider, type ForgeProviderOf, type ForgeResponseCache, ForgeTimeoutError, type ForgeToken, type ForgeTokenErrorCode, type GitHubAppCredentials, type GitHubAppDelivery, type GitHubAppInput, type GitHubAppRepository, type GitHubBranchRuleDetails, type GitHubInstallationEnv, type GitHubInstallationRouting, type GitHubProvider, MergeBlockedError, type MergeMethod, type MergeOptions, type MergeResult, NotFoundError, type Page, RateLimitedError, type RepoRef, type RequiredCheck, type Thread, type ThreadRef, type TreeEntry, type UseForgeOptions, repoRef };
4188
+ export { type BaseOptions, BranchMovedError, type BranchRules, type Check, type CiRun, type CiRunRef, type Commit, type Forge$1 as Forge, ForgeApiError, type ForgeAppIdentity, type ForgeArchive, type ForgeArchiveOptions, type ForgeCachedResponse, type ForgeCallOptions, type ForgeCheck, type ForgeCheckErrorCode, type ForgeCommitFilesInput, type ForgeConditionalRequests, type ForgeConnection, type ForgeEnv, type ForgeEnvField, type ForgeEnvSource, type ForgeErrorCode, type ForgeFileChange, type ForgeFileMode, type ForgeGitCredentials, type ForgeGitCredentialsInput, type ForgeKind, type ForgeMemoryCacheOptions, type ForgeMergeOptions, type ForgeProvider, type ForgeProviderOf, type ForgeResponseCache, ForgeTimeoutError, type ForgeToken, type ForgeTokenErrorCode, type GitHubAppCredentials, type GitHubAppDelivery, type GitHubAppInput, type GitHubAppRepository, type GitHubBranchRuleDetails, type GitHubInstallationEnv, type GitHubInstallationRouting, type GitHubProvider, MergeBlockedError, type MergeMethod, type MergeOptions, type MergeResult, NotFoundError, type Page, RateLimitedError, type ReadForgeArchiveOptions, type RepoRef, type RequiredCheck, type Thread, type ThreadRef, type TreeEntry, type UseForgeOptions, repoRef };
package/dist/index.js CHANGED
@@ -34,55 +34,92 @@ function getActiveCloudflareBinding(name) {
34
34
  */
35
35
  const forgeEnv = {
36
36
  github: {
37
- appId: { names: ["VITEHUB_GITHUB_APP_ID", "FORGES_GITHUB_APP_ID"] },
38
- installationId: { names: ["VITEHUB_GITHUB_INSTALLATION_ID", "FORGES_GITHUB_INSTALLATION_ID"] },
39
- appOwner: { names: ["VITEHUB_GITHUB_APP_OWNER"] },
40
- appInstallations: { names: ["VITEHUB_GITHUB_APP_INSTALLATIONS"] },
37
+ appId: {
38
+ names: ["VITEHUB_GITHUB_APP_ID", "FORGES_GITHUB_APP_ID"],
39
+ description: "GitHub App ID that signs in as the GitHub App with the private key."
40
+ },
41
+ baseUrl: {
42
+ names: ["VITEHUB_GITHUB_BASE_URL", "FORGES_GITHUB_BASE_URL"],
43
+ description: "GitHub API URL for GitHub Enterprise Server."
44
+ },
45
+ installationId: {
46
+ names: ["VITEHUB_GITHUB_INSTALLATION_ID", "FORGES_GITHUB_INSTALLATION_ID"],
47
+ description: "GitHub App installation ID for the repositories of one owner."
48
+ },
49
+ appOwner: {
50
+ names: ["VITEHUB_GITHUB_APP_OWNER"],
51
+ description: "Repository owner of the GitHub App installation ID."
52
+ },
53
+ appInstallations: {
54
+ names: ["VITEHUB_GITHUB_APP_INSTALLATIONS"],
55
+ description: "JSON object that maps each repository owner to its GitHub App installation ID."
56
+ },
41
57
  privateKey: {
42
58
  names: ["VITEHUB_GITHUB_PRIVATE_KEY", "FORGES_GITHUB_PRIVATE_KEY"],
43
- secret: true
59
+ secret: true,
60
+ description: "GitHub App private key in PEM format that signs the GitHub App tokens."
61
+ },
62
+ privateKeyPath: {
63
+ names: ["VITEHUB_GITHUB_PRIVATE_KEY_PATH"],
64
+ description: "Path of the GitHub App private key file when the private key is not set."
44
65
  },
45
- privateKeyPath: { names: ["VITEHUB_GITHUB_PRIVATE_KEY_PATH"] },
46
66
  token: {
47
67
  names: ["VITEHUB_GITHUB_TOKEN", "FORGES_GITHUB_TOKEN"],
48
- secret: true
68
+ secret: true,
69
+ description: "GitHub access token that calls the GitHub API."
49
70
  },
50
71
  webhookSecret: {
51
72
  names: ["VITEHUB_GITHUB_WEBHOOK_SECRET", "FORGES_GITHUB_WEBHOOK_SECRET"],
52
- secret: true
73
+ secret: true,
74
+ description: "Secret that checks the signature of each GitHub webhook request."
53
75
  }
54
76
  },
55
77
  gitlab: {
56
- baseUrl: { names: ["VITEHUB_GITLAB_BASE_URL", "FORGES_GITLAB_BASE_URL"] },
78
+ baseUrl: {
79
+ names: ["VITEHUB_GITLAB_BASE_URL", "FORGES_GITLAB_BASE_URL"],
80
+ description: "GitLab URL for a self-managed GitLab instance."
81
+ },
57
82
  token: {
58
83
  names: ["VITEHUB_GITLAB_TOKEN", "FORGES_GITLAB_TOKEN"],
59
- secret: true
84
+ secret: true,
85
+ description: "GitLab access token that calls the GitLab API."
60
86
  },
61
87
  webhookSecret: {
62
88
  names: ["VITEHUB_GITLAB_WEBHOOK_SECRET", "FORGES_GITLAB_WEBHOOK_SECRET"],
63
- secret: true
89
+ secret: true,
90
+ description: "Secret that checks each GitLab webhook request."
64
91
  }
65
92
  },
66
93
  forgejo: {
67
- baseUrl: { names: ["VITEHUB_FORGEJO_BASE_URL", "FORGES_FORGEJO_BASE_URL"] },
94
+ baseUrl: {
95
+ names: ["VITEHUB_FORGEJO_BASE_URL", "FORGES_FORGEJO_BASE_URL"],
96
+ description: "URL of the Forgejo instance."
97
+ },
68
98
  token: {
69
99
  names: ["VITEHUB_FORGEJO_TOKEN", "FORGES_FORGEJO_TOKEN"],
70
- secret: true
100
+ secret: true,
101
+ description: "Forgejo access token that calls the Forgejo API."
71
102
  },
72
103
  webhookSecret: {
73
104
  names: ["VITEHUB_FORGEJO_WEBHOOK_SECRET", "FORGES_FORGEJO_WEBHOOK_SECRET"],
74
- secret: true
105
+ secret: true,
106
+ description: "Secret that checks each Forgejo webhook request."
75
107
  }
76
108
  },
77
109
  gitea: {
78
- baseUrl: { names: ["VITEHUB_GITEA_BASE_URL", "FORGES_GITEA_BASE_URL"] },
110
+ baseUrl: {
111
+ names: ["VITEHUB_GITEA_BASE_URL", "FORGES_GITEA_BASE_URL"],
112
+ description: "URL of the Gitea instance."
113
+ },
79
114
  token: {
80
115
  names: ["VITEHUB_GITEA_TOKEN", "FORGES_GITEA_TOKEN"],
81
- secret: true
116
+ secret: true,
117
+ description: "Gitea access token that calls the Gitea API."
82
118
  },
83
119
  webhookSecret: {
84
120
  names: ["VITEHUB_GITEA_WEBHOOK_SECRET", "FORGES_GITEA_WEBHOOK_SECRET"],
85
- secret: true
121
+ secret: true,
122
+ description: "Secret that checks each Gitea webhook request."
86
123
  }
87
124
  }
88
125
  };
@@ -170,6 +207,14 @@ const forgeDiagnostics = /*#__PURE__*/ defineDiagnostics({
170
207
  ...dynamicError,
171
208
  fix: "Pass a pull request thread with a `number` and a nonempty base branch. For `forgeMerge({ bypassRules })`, also pass `method` and `sha`."
172
209
  },
210
+ FORGE_ARCHIVE_LIMIT_INVALID: {
211
+ why: "`readForgeArchive()` received an invalid `maxBytes` value.",
212
+ fix: "Pass a non-negative safe integer in bytes, or omit `maxBytes` to use the 64 MiB default."
213
+ },
214
+ FORGE_ARCHIVE_TOO_LARGE: {
215
+ why: ({ commit, limit, repo }) => `The archive of ${repo} at ${commit} is larger than ${limit} (\`maxBytes\`).`,
216
+ fix: "Pass a larger `maxBytes` to `readForgeArchive()`, or read only the files you need with `provider.contents.getFile()`."
217
+ },
173
218
  FORGE_RESPONSE_INVALID: {
174
219
  why: ({ problem }) => problem,
175
220
  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."
@@ -294,19 +339,19 @@ async function forgeProvider(connection) {
294
339
  };
295
340
  switch (connection.forge) {
296
341
  case "github": {
297
- const { github } = await import("./github-CHzhqYOr.js");
342
+ const { github } = await import("./github-Csy_qzZc.js");
298
343
  return github(options);
299
344
  }
300
345
  case "gitlab": {
301
- const { gitlab } = await import("./gitlab-CS0shW2u.js");
346
+ const { gitlab } = await import("./gitlab-AAJN-eVR.js");
302
347
  return gitlab(options);
303
348
  }
304
349
  case "forgejo": {
305
- const { forgejo } = await import("./forgejo-4sbZukng.js");
350
+ const { forgejo } = await import("./forgejo-aZiaqKRW.js");
306
351
  return forgejo(options);
307
352
  }
308
353
  case "gitea": {
309
- const { gitea } = await import("./gitea-Cj7qy2X3.js");
354
+ const { gitea } = await import("./gitea-CCZ3fS7H.js");
310
355
  const { webhookSecret } = connection;
311
356
  return gitea({
312
357
  ...options,
@@ -413,7 +458,7 @@ function appProvider(input, installationId = "", refresh = false) {
413
458
  if (refresh) appProviders.delete(key);
414
459
  const cached = appProviders.get(key);
415
460
  if (cached) return cached;
416
- const pending = import("./github-CHzhqYOr.js").then(({ github }) => github({
461
+ const pending = import("./github-Csy_qzZc.js").then(({ github }) => github({
417
462
  ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
418
463
  ...input.fetch ? { fetch: input.fetch } : {},
419
464
  userAgent: input.userAgent ?? "vitehub",
@@ -438,7 +483,7 @@ async function appIdentity(input) {
438
483
  if (!id) throw forgeResponseError("GitHub App metadata did not include an ID.");
439
484
  if (!slug) throw forgeResponseError("GitHub App response did not include a slug.");
440
485
  const login = `${slug}[bot]`;
441
- const { github } = await import("./github-CHzhqYOr.js");
486
+ const { github } = await import("./github-Csy_qzZc.js");
442
487
  const userId = await github({
443
488
  ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
444
489
  ...input.fetch ? { fetch: input.fetch } : {},
@@ -681,6 +726,21 @@ function readGitHubApp(env) {
681
726
  privateKeyPath
682
727
  };
683
728
  }
729
+ async function readAppPrivateKey(config) {
730
+ const name = primaryName(forgeEnv.github.privateKeyPath);
731
+ const privateKey = await readGitHubAppPrivateKey(config.privateKey, config.privateKeyPath).catch((cause) => {
732
+ throw forgeErrors.FORGE_INVALID_ENV({
733
+ cause,
734
+ name,
735
+ problem: `names a file that cannot be read: ${config.privateKeyPath}`
736
+ });
737
+ });
738
+ if (!privateKey) throw forgeErrors.FORGE_INVALID_ENV({
739
+ name,
740
+ problem: `names an empty file: ${config.privateKeyPath}`
741
+ });
742
+ return privateKey;
743
+ }
684
744
  function requestFailed(operation, cause, signal) {
685
745
  if (signal?.aborted) throw abortError(signal);
686
746
  const status = forgeErrorStatus(cause) ?? (isRuntimeDiagnostic(cause) ? forgeErrorStatus(cause.cause) : void 0);
@@ -690,19 +750,9 @@ function requestFailed(operation, cause, signal) {
690
750
  ...status === void 0 ? {} : { status }
691
751
  });
692
752
  }
693
- /**
694
- * The Forge identity of this deployment, read from the same Server Env as Channels, Workspaces and Sources.
695
- * GitHub uses a GitHub App when `VITEHUB_GITHUB_APP_ID` is set, and `VITEHUB_GITHUB_TOKEN` otherwise.
696
- * Throws a config error when the env has no credentials. Runtime operations return `[error, data]`.
697
- *
698
- * ```ts
699
- * const [error, provider] = await useForge().provider({ repository: "acme/web" })
700
- * ```
701
- */
702
- function useForge(options = {}) {
753
+ function resolveForgeConfig(options) {
703
754
  const kind = options.forge ?? "github";
704
755
  const env = options.env ?? hostEnv;
705
- const fields = forgeEnv;
706
756
  const githubApp = kind === "github" ? readGitHubApp(env) : void 0;
707
757
  const configuredToken = githubApp ? void 0 : readForgeEnv(forgeEnv[kind].token, env);
708
758
  const credential = githubApp ? { app: githubApp } : configuredToken ? { token: configuredToken } : void 0;
@@ -713,31 +763,34 @@ function useForge(options = {}) {
713
763
  names
714
764
  });
715
765
  }
716
- const baseField = fields[kind].baseUrl;
717
- const baseUrl = options.baseUrl ?? (baseField ? readForgeEnv(baseField, env) : void 0);
718
- const webhookSecret = kind === "gitea" ? readForgeEnv(forgeEnv.gitea.webhookSecret, env) : void 0;
766
+ return {
767
+ kind,
768
+ credential,
769
+ baseUrl: options.baseUrl ?? readForgeEnv(forgeEnv[kind].baseUrl, env),
770
+ webhookSecret: kind === "gitea" ? readForgeEnv(forgeEnv.gitea.webhookSecret, env) : void 0
771
+ };
772
+ }
773
+ /**
774
+ * The Forge identity of this deployment, read from the same Server Env as Channels, Workspaces and Sources.
775
+ * GitHub uses a GitHub App when `VITEHUB_GITHUB_APP_ID` is set, and `VITEHUB_GITHUB_TOKEN` otherwise.
776
+ * Throws a config error when the env has no credentials. Runtime operations return `[error, data]`.
777
+ *
778
+ * ```ts
779
+ * const [error, provider] = await useForge().provider({ repository: "acme/web" })
780
+ * ```
781
+ */
782
+ function useForge(options = {}) {
783
+ const { kind, credential, baseUrl, webhookSecret } = resolveForgeConfig(options);
719
784
  const userAgent = options.userAgent ?? "vitehub";
720
785
  let credentials;
721
786
  function appCredentials(config) {
722
- credentials ??= readGitHubAppPrivateKey(config.privateKey, config.privateKeyPath).then((privateKey) => {
723
- if (!privateKey) throw forgeErrors.FORGE_INVALID_ENV({
724
- name: primaryName(forgeEnv.github.privateKeyPath),
725
- problem: `names an empty file: ${config.privateKeyPath}`
726
- });
727
- return githubAppCredentials({
728
- appId: config.appId,
729
- privateKey,
730
- userAgent,
731
- ...baseUrl ? { baseUrl } : {},
732
- ...options.fetch ? { fetch: options.fetch } : {}
733
- });
734
- }, (cause) => {
735
- throw forgeErrors.FORGE_INVALID_ENV({
736
- cause,
737
- name: primaryName(forgeEnv.github.privateKeyPath),
738
- problem: `names a file that cannot be read: ${config.privateKeyPath}`
739
- });
740
- });
787
+ credentials ??= readAppPrivateKey(config).then((privateKey) => githubAppCredentials({
788
+ appId: config.appId,
789
+ privateKey,
790
+ userAgent,
791
+ ...baseUrl ? { baseUrl } : {},
792
+ ...options.fetch ? { fetch: options.fetch } : {}
793
+ }));
741
794
  credentials.catch(() => {
742
795
  credentials = void 0;
743
796
  });
@@ -824,6 +877,64 @@ function useForge(options = {}) {
824
877
  }
825
878
  };
826
879
  }
880
+ /**
881
+ * Checks the Forge env and sends no request, for example for a Setup page. It returns `[undefined, { kind, auth }]`
882
+ * when local configuration is valid, or `[error, undefined]` with a configuration error. It checks the base URL
883
+ * and signs locally with the GitHub App private key, but does not check that the forge accepts the credentials.
884
+ *
885
+ * ```ts
886
+ * const [error] = await checkForge()
887
+ * if (error) return { configured: false, fix: error.fix }
888
+ * ```
889
+ */
890
+ async function checkForge(options = {}) {
891
+ try {
892
+ const { kind, credential, baseUrl } = resolveForgeConfig(options);
893
+ if (baseUrl) try {
894
+ await forgeProvider({
895
+ forge: kind,
896
+ baseUrl,
897
+ ...options.fetch ? { fetch: options.fetch } : {}
898
+ });
899
+ } catch (error) {
900
+ if (!(error instanceof TypeError)) throw error;
901
+ const name = options.baseUrl === void 0 ? primaryName(forgeEnv[kind].baseUrl) : "baseUrl";
902
+ throw forgeErrors.FORGE_INVALID_ENV({
903
+ name,
904
+ problem: "must be a valid HTTP(S) base URL without credentials, a query, or a fragment"
905
+ });
906
+ }
907
+ if (!("app" in credential)) return [void 0, {
908
+ kind,
909
+ auth: "token"
910
+ }];
911
+ const { app } = credential;
912
+ const privateKey = await readAppPrivateKey(app);
913
+ const { signRs256Jwt } = await import("./kit-UEdJKGws.js");
914
+ try {
915
+ const now = Math.floor(Date.now() / 1e3);
916
+ await signRs256Jwt(privateKey, {
917
+ iss: app.appId,
918
+ iat: now,
919
+ exp: now + 60
920
+ });
921
+ } catch (cause) {
922
+ const name = primaryName(app.privateKey ? forgeEnv.github.privateKey : forgeEnv.github.privateKeyPath);
923
+ throw forgeErrors.FORGE_INVALID_ENV({
924
+ cause,
925
+ name,
926
+ problem: "must supply a PEM-encoded RSA private key that can sign a GitHub App JWT"
927
+ });
928
+ }
929
+ return [void 0, {
930
+ kind,
931
+ auth: "app"
932
+ }];
933
+ } catch (error) {
934
+ if (forgeErrors.FORGE_MISSING_ENV.is(error) || forgeErrors.FORGE_INVALID_ENV.is(error)) return [error, void 0];
935
+ throw error;
936
+ }
937
+ }
827
938
  // src/gaps/archive.ts
828
939
  /**
829
940
  * The repository tree at `ref` as a gzipped tarball stream.
@@ -831,7 +942,10 @@ function useForge(options = {}) {
831
942
  * (https://github.com/danielroe/forges/issues/191).
832
943
  */
833
944
  async function forgeArchive(provider, repo, options) {
834
- if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0002({ message: `Repository archives are not supported for ${provider.forge}.` });
945
+ assertArchiveProvider(provider);
946
+ return downloadForgeArchive(provider, repo, options);
947
+ }
948
+ async function downloadForgeArchive(provider, repo, options) {
835
949
  const owner = encodeURIComponent(repo.owner);
836
950
  const name = encodeURIComponent(repo.name);
837
951
  const ref = options.ref.split("/").map(encodeURIComponent).join("/");
@@ -841,6 +955,60 @@ async function forgeArchive(provider, repo, options) {
841
955
  signal: options.signal
842
956
  })).body;
843
957
  }
958
+ const defaultArchiveMaxBytes = 67108864;
959
+ /**
960
+ * The repository tree at `ref` as `tar.gz` bytes, with the commit it came from. Reads at most `maxBytes` (64 MiB by
961
+ * default). GitHub only.
962
+ *
963
+ * ```ts
964
+ * const { commit, bytes } = await readForgeArchive(provider, repo, { ref: "main", maxBytes: 32 * 1024 * 1024 })
965
+ * ```
966
+ */
967
+ async function readForgeArchive(provider, repo, options) {
968
+ assertArchiveProvider(provider);
969
+ const maxBytes = options.maxBytes ?? defaultArchiveMaxBytes;
970
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw forgeDiagnostics.FORGE_ARCHIVE_LIMIT_INVALID();
971
+ const commit = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(options.ref) ? options.ref : await provider.contents.resolveRef(repo, options.ref, { signal: options.signal });
972
+ const tooLarge = () => forgeDiagnostics.FORGE_ARCHIVE_TOO_LARGE({
973
+ commit,
974
+ limit: formatBytes(maxBytes),
975
+ repo: `${repo.owner}/${repo.name}`
976
+ });
977
+ const reader = (await downloadForgeArchive(provider, repo, {
978
+ ref: commit,
979
+ signal: options.signal
980
+ })).getReader();
981
+ const chunks = [];
982
+ let size = 0;
983
+ try {
984
+ while (true) {
985
+ const { value, done } = await reader.read();
986
+ if (done) break;
987
+ size += value.byteLength;
988
+ if (size > maxBytes) throw tooLarge();
989
+ chunks.push(value);
990
+ }
991
+ } finally {
992
+ await reader.cancel().catch(() => {});
993
+ }
994
+ const bytes = new Uint8Array(size);
995
+ let offset = 0;
996
+ for (const chunk of chunks) {
997
+ bytes.set(chunk, offset);
998
+ offset += chunk.byteLength;
999
+ }
1000
+ return {
1001
+ commit,
1002
+ bytes
1003
+ };
1004
+ }
1005
+ function assertArchiveProvider(provider) {
1006
+ if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0002({ message: `Repository archives are not supported for ${provider.forge}.` });
1007
+ }
1008
+ function formatBytes(bytes) {
1009
+ const mib = bytes / 1048576;
1010
+ return Number.isInteger(mib) ? `${mib} MiB` : `${bytes} bytes`;
1011
+ }
844
1012
  // src/gaps/blob.ts
845
1013
  /**
846
1014
  * The bytes of one Git blob, by its sha. The blob of a symlink holds the link target.
@@ -1231,4 +1399,4 @@ async function retargetPullRequest(provider, thread, base, options) {
1231
1399
  signal: options?.signal
1232
1400
  });
1233
1401
  }
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 };
1402
+ export { BranchMovedError, ForgeApiError, ForgeTimeoutError, MergeBlockedError, NotFoundError, RateLimitedError, abortError, checkForge, conditionalFetch, forgeArchive, forgeBlob, forgeBranchRules, forgeCommitFiles, forgeEnv, forgeErrorStatus, forgeGitAuthHeader, forgeGitCredentials, forgeMemoryCache, forgeMerge, forgeProvider, forgeResponseError, githubAppCredentials, githubBranchRuleDetails, githubInstallationFor, githubInstallationRouting, isForgeResponseError, readForgeArchive, readForgeEnv, readGitHubAppPrivateKey, repoRef, retargetPullRequest, useForge, withSignal };
@@ -0,0 +1,3 @@
1
+ export { i as signRs256Jwt } from "./crypto-DydCoK4e-BCG61qh5.js";
2
+ import "./model-Biiu1CfI-CVLamGai.js";
3
+ import "./webhooks-Bc6QhmI8-CvF2iFBp.js";
@@ -1,5 +1,5 @@
1
1
  import { b as NotFoundError } from "./model-Biiu1CfI-CVLamGai.js";
2
- import { z as mapConcurrent } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
2
+ import { H as mapConcurrent } from "./webhooks-Bc6QhmI8-CvF2iFBp.js";
3
3
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/templates-0m5QBVIh.mjs
4
4
  /** Where GitHub looks for a pull request template and the legacy issue template, in its order of precedence. */
5
5
  const LOCATIONS = [
@@ -1,126 +1,5 @@
1
+ import { a as timingSafeEqual, n as headerValue, o as toBase64, r as hmacSha256Hex } from "./crypto-DydCoK4e-BCG61qh5.js";
1
2
  import { C as TokenRevokedError, D as forbiddenReason, E as WebhookVerificationError, O as isSecondaryRateLimit, S as ReadOnlyError, T as UnsupportedOperationError, _ as InsufficientScopeError, a as namespaceRef, b as NotFoundError, d as ContentNotTextError, f as ForbiddenError, g as ForgeTimeoutError, h as ForgeNetworkError, i as isUnsupported, l as AuthenticationRequiredError, m as ForgeError, n as isNamespaceRef, o as normaliseRepoName, p as ForgeApiError, r as isResolvedThread, w as UnresolvedThreadError, x as RateLimitedError } from "./model-Biiu1CfI-CVLamGai.js";
2
- // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/crypto-DydCoK4e.mjs
3
- const encoder = new TextEncoder();
4
- function toBytes(value) {
5
- return typeof value === "string" ? encoder.encode(value) : value;
6
- }
7
- function toHex(buffer) {
8
- return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
9
- }
10
- /** Base64 for arbitrary bytes, a byte at a time so a large buffer cannot overflow the call stack. */
11
- function toBase64(bytes) {
12
- let binary = "";
13
- for (const byte of bytes) binary += String.fromCharCode(byte);
14
- return btoa(binary);
15
- }
16
- function toBase64Url(input) {
17
- return (typeof input === "string" ? btoa(input) : toBase64(input)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
18
- }
19
- async function hmacSha256(secret, body) {
20
- const key = await crypto.subtle.importKey("raw", toBytes(secret), {
21
- name: "HMAC",
22
- hash: "SHA-256"
23
- }, false, ["sign"]);
24
- return crypto.subtle.sign("HMAC", key, toBytes(body));
25
- }
26
- /** Lowercase hex HMAC-SHA256 of `body` under `secret`. */
27
- async function hmacSha256Hex(secret, body) {
28
- return toHex(await hmacSha256(secret, body));
29
- }
30
- /**
31
- * Constant-time comparison of two strings. The time taken depends only on the
32
- * length of `a`, so pass the untrusted value as `a`.
33
- */
34
- function timingSafeEqual(a, b) {
35
- let mismatch = a.length ^ b.length;
36
- for (let index = 0; index < a.length; index++) mismatch |= a.charCodeAt(index) ^ b.charCodeAt(index % b.length);
37
- return mismatch === 0;
38
- }
39
- function decodePem(pem) {
40
- const pkcs1 = pem.includes("BEGIN RSA PRIVATE KEY");
41
- const body = pem.replace(/-----(?:BEGIN|END)[^-]+-----/g, "").replace(/\s+/g, "");
42
- const binary = atob(body);
43
- const der = new Uint8Array(binary.length);
44
- for (let index = 0; index < binary.length; index++) der[index] = binary.charCodeAt(index);
45
- return {
46
- der,
47
- pkcs1
48
- };
49
- }
50
- function derLength(length) {
51
- if (length < 128) return [length];
52
- const bytes = [];
53
- let remaining = length;
54
- while (remaining > 0) {
55
- bytes.unshift(remaining & 255);
56
- remaining >>= 8;
57
- }
58
- return [128 | bytes.length, ...bytes];
59
- }
60
- /**
61
- * Wraps a PKCS#1 RSA key in a PKCS#8 `PrivateKeyInfo`. GitHub App keys are
62
- * distributed as PKCS#1, which Web Crypto cannot import directly.
63
- */
64
- function pkcs1ToPkcs8(der) {
65
- const algorithm = [
66
- 48,
67
- 13,
68
- 6,
69
- 9,
70
- 42,
71
- 134,
72
- 72,
73
- 134,
74
- 247,
75
- 13,
76
- 1,
77
- 1,
78
- 1,
79
- 5,
80
- 0
81
- ];
82
- const octetString = [
83
- 4,
84
- ...derLength(der.length),
85
- ...der
86
- ];
87
- const contents = [
88
- 2,
89
- 1,
90
- 0,
91
- ...algorithm,
92
- ...octetString
93
- ];
94
- return new Uint8Array([
95
- 48,
96
- ...derLength(contents.length),
97
- ...contents
98
- ]);
99
- }
100
- /** Signs an RS256 JWT with a PEM-encoded RSA private key. */
101
- async function signRs256Jwt(privateKeyPem, claims) {
102
- const { der, pkcs1 } = decodePem(privateKeyPem);
103
- const key = await crypto.subtle.importKey("pkcs8", pkcs1 ? pkcs1ToPkcs8(der) : der, {
104
- name: "RSASSA-PKCS1-v1_5",
105
- hash: "SHA-256"
106
- }, false, ["sign"]);
107
- const payload = `${toBase64Url(JSON.stringify({
108
- alg: "RS256",
109
- typ: "JWT"
110
- }))}.${toBase64Url(JSON.stringify(claims))}`;
111
- const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, encoder.encode(payload));
112
- return `${payload}.${toBase64Url(new Uint8Array(signature))}`;
113
- }
114
- /** The value of a header, whatever the casing of `name`, from a `Headers` object or a plain record. */
115
- function headerValue(headers, name) {
116
- if (headers instanceof Headers) return headers.get(name) ?? void 0;
117
- const lower = name.toLowerCase();
118
- for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === lower) return value;
119
- }
120
- /** A request body as text. */
121
- function bodyText(body) {
122
- return typeof body === "string" ? body : new TextDecoder().decode(body);
123
- }
124
3
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/contents-NHE4zdZf.mjs
125
4
  /** Decodes base64, tolerating the newlines GitHub and Gitea wrap it in. */
126
5
  function fromBase64(value) {
@@ -2823,4 +2702,4 @@ function eventKindsOf(map, nativeEvents) {
2823
2702
  for (const [kind, names] of Object.entries(map)) if (nativeEvents.includes("*") || names.some((name) => nativeEvents.includes(name))) kinds.add(kind);
2824
2703
  return [...kinds];
2825
2704
  }
2826
- export { syntheticReview as $, firstPageEtag as A, memo as B, abortable as C, createFetcher as D, checkRunState as E, hostOf as F, rateLimitOf as G, mergeCommitMessage as H, isFirstPage as I, requireIssueOrPull as J, rateLimitPart as K, iteratePages as L, getManyConcurrently as M, hasEveryLabel as N, createListing as O, hexColour as P, summariseChecks as Q, latestCommentOf as R, webUrlFor as S, anySignal as T, milestoneId as U, memoBy as V, phased as W, resolveToken as X, requireThread as Y, sleep as Z, OWNER_NAME as _, signRs256Jwt as _t, verifyHmacSignature as a, toWarning as at, lineOf as b, defineForgeProvider as c, changeBase64 as ct, perKind as d, inDirectories as dt, teamOrg as et, reviewState as f, isSha as ft, verb as g, headerValue as gt, threadSnapshot as h, bodyText as ht, refEvent as i, toPullStats as it, forgeIterable as j, degradesToWarning as k, eventAction as l, existingFiles as lt, supportOnly as m, toFileContent as mt, firstHeader as n, toFileStatus as nt, verifySharedToken as o, versionAtLeast as ot, snapshotOfThread as p, splitMessage as pt, rateLimitReset as q, nativeEventsFor as r, toPage as rt, WRITE_VERBS as s, withEtag as st, eventKindsOf as t, toDate as tt, eventTime as u, fromBase64 as ut, bareSha as v, actorLogin as w, rangeOf as x, githubShapedWeb as y, mapConcurrent as z };
2705
+ export { requireThread as $, createListing as A, iteratePages as B, rangeOf as C, anySignal as D, actorLogin as E, getManyConcurrently as F, mergeCommitMessage as G, mapConcurrent as H, hasEveryLabel as I, phased as J, milestoneId as K, hexColour as L, degradesToWarning as M, firstPageEtag as N, checkRunState as O, forgeIterable as P, requireIssueOrPull as Q, hostOf as R, lineOf as S, abortable as T, memo as U, latestCommentOf as V, memoBy as W, rateLimitPart as X, rateLimitOf as Y, rateLimitReset as Z, threadSnapshot as _, splitMessage as _t, verifyHmacSignature as a, toDate as at, bareSha as b, WRITE_VERBS as c, toPullStats as ct, eventAction as d, withEtag as dt, resolveToken as et, eventTime as f, changeBase64 as ft, supportOnly as g, isSha as gt, snapshotOfThread as h, inDirectories as ht, refEvent as i, teamOrg as it, createRequest as j, createFetcher as k, completeEvent as l, toWarning as lt, reviewState as m, fromBase64 as mt, firstHeader as n, summariseChecks as nt, verifySharedToken as o, toFileStatus as ot, perKind as p, existingFiles as pt, parseLinkHeader as q, nativeEventsFor as r, syntheticReview as rt, CAPABILITY_TABLE as s, toPage as st, eventKindsOf as t, sleep as tt, defineForgeProvider as u, versionAtLeast as ut, verb as v, toFileContent as vt, webUrlFor as w, githubShapedWeb as x, OWNER_NAME as y, isFirstPage as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/forge",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
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",
@@ -47,7 +47,7 @@
47
47
  "./package.json": "./package.json"
48
48
  },
49
49
  "dependencies": {
50
- "@vite-hub/runtime": "0.6.0",
50
+ "@vite-hub/runtime": "0.7.0",
51
51
  "nostics": "1.4.0"
52
52
  },
53
53
  "devDependencies": {