@vite-hub/forge 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/README.md +13 -2
  2. package/dist/crypto-DydCoK4e-BCG61qh5.js +123 -0
  3. package/dist/{webhooks-Bc6QhmI8-eK71_mJE.js → define-C9xZZNVR-C-oojQRP.js} +3 -1118
  4. package/dist/{definition-BQFdu9ti-WxMjcAEl.js → definition-BQFdu9ti-BZgR-gkB.js} +5 -4
  5. package/dist/{github-CHzhqYOr.js → definition-s83gxg2p-JwDgFji9.js} +27 -28
  6. package/dist/{events-BL0zcgMf-9TwyYtCt.js → events-BL0zcgMf-Exs7JLX1.js} +5 -2
  7. package/dist/{events-DDdJnmD2-BSMoOqjV.js → events-DDdJnmD2-CdPFePvp.js} +5 -3
  8. package/dist/{events-DHqSJ5KI-z2-5_1vo.js → events-DHqSJ5KI-mRtn-qQ0.js} +5 -3
  9. package/dist/{events-DXE-Ul2S-BzTkugIK.js → events-DXE-Ul2S-BEUw4sQF.js} +5 -3
  10. package/dist/{feed-B1OiHFg0-DevZZe0y.js → feed-B1OiHFg0-ppQHqkxG.js} +4 -2
  11. package/dist/{feed-DROLF1tb-CtRfA_7N.js → feed-DROLF1tb-CMAanXw8.js} +4 -2
  12. package/dist/{feed-iWegqepj-ConxMpg4.js → feed-iWegqepj-DKBLqhvD.js} +4 -2
  13. package/dist/{forgejo-4sbZukng.js → forgejo-Deckk49p.js} +2 -2
  14. package/dist/{gitea-Cj7qy2X3.js → gitea-ChQKeRrf.js} +2 -2
  15. package/dist/{gitee-CKt4pEC0-BuLWggck.js → gitee-CKt4pEC0-BuzC1PrM.js} +1 -1
  16. package/dist/{gitlab-CS0shW2u.js → gitlab-CzCikZzN.js} +5 -4
  17. package/dist/{graphql-DxRA9BGO-BBbmTmWi.js → graphql-DxRA9BGO-Cy511t8-.js} +2 -1
  18. package/dist/index.d.ts +91 -3
  19. package/dist/index.js +400 -65
  20. package/dist/kit-CrquHPqr.js +4 -0
  21. package/dist/{templates-0m5QBVIh-D1fZeoC-.js → templates-0m5QBVIh-C1DcQ_yo.js} +1 -2
  22. package/dist/utils-DEwhctg5-BM3AMnSs.js +1213 -0
  23. package/dist/webhooks-Bc6QhmI8-CgoCnwj1.js +71 -0
  24. package/package.json +2 -2
  25. package/dist/model-Biiu1CfI-CVLamGai.js +0 -288
package/dist/index.js CHANGED
@@ -1,9 +1,22 @@
1
- import { b as NotFoundError, c as repoRef, g as ForgeTimeoutError, p as ForgeApiError, u as BranchMovedError, v as MergeBlockedError, x as RateLimitedError } from "./model-Biiu1CfI-CVLamGai.js";
1
+ import { i as defineForgeProvider } from "./define-C9xZZNVR-C-oojQRP.js";
2
+ import { n as githubDefinition, t as GITHUB_PROFILE } from "./definition-s83gxg2p-JwDgFji9.js";
3
+ import { Y as repoRef, Z as BranchMovedError, et as ForgeApiError, it as MergeBlockedError, nt as ForgeTimeoutError, ot as NotFoundError, st as RateLimitedError } from "./utils-DEwhctg5-BM3AMnSs.js";
2
4
  import { AsyncLocalStorage } from "node:async_hooks";
3
5
  import { defineErrors, isRuntimeDiagnostic } from "@vite-hub/runtime";
4
6
  import { defineDiagnostics } from "nostics";
5
7
  import { createHash } from "node:crypto";
6
- import { Buffer } from "node:buffer";
8
+ import { Buffer as Buffer$1 } from "node:buffer";
9
+ // \0rolldown/runtime.js
10
+ var __defProp = Object.defineProperty;
11
+ var __exportAll = (all, no_symbols) => {
12
+ let target = {};
13
+ for (var name in all) __defProp(target, name, {
14
+ get: all[name],
15
+ enumerable: true
16
+ });
17
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
+ return target;
19
+ };
7
20
  // ../internal/src/runtime/cloudflare-env-lookup.ts
8
21
  /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
9
22
  const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
@@ -34,55 +47,101 @@ function getActiveCloudflareBinding(name) {
34
47
  */
35
48
  const forgeEnv = {
36
49
  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"] },
50
+ appId: {
51
+ names: ["VITEHUB_GITHUB_APP_ID", "FORGES_GITHUB_APP_ID"],
52
+ description: "GitHub App ID that signs in as the GitHub App with the private key."
53
+ },
54
+ baseUrl: {
55
+ names: ["VITEHUB_GITHUB_BASE_URL", "FORGES_GITHUB_BASE_URL"],
56
+ description: "GitHub API URL for GitHub Enterprise Server."
57
+ },
58
+ clientId: {
59
+ names: ["VITEHUB_GITHUB_CLIENT_ID", "FORGES_GITHUB_CLIENT_ID"],
60
+ description: "Client ID of the GitHub App that signs a person in to act as themselves."
61
+ },
62
+ clientSecret: {
63
+ names: ["VITEHUB_GITHUB_CLIENT_SECRET", "FORGES_GITHUB_CLIENT_SECRET"],
64
+ secret: true,
65
+ description: "Client secret of the GitHub App that trades a sign-in code for a user token."
66
+ },
67
+ installationId: {
68
+ names: ["VITEHUB_GITHUB_INSTALLATION_ID", "FORGES_GITHUB_INSTALLATION_ID"],
69
+ description: "GitHub App installation ID for the repositories of one owner."
70
+ },
71
+ appOwner: {
72
+ names: ["VITEHUB_GITHUB_APP_OWNER"],
73
+ description: "Repository owner of the GitHub App installation ID."
74
+ },
75
+ appInstallations: {
76
+ names: ["VITEHUB_GITHUB_APP_INSTALLATIONS"],
77
+ description: "JSON object that maps each repository owner to its GitHub App installation ID."
78
+ },
41
79
  privateKey: {
42
80
  names: ["VITEHUB_GITHUB_PRIVATE_KEY", "FORGES_GITHUB_PRIVATE_KEY"],
43
- secret: true
81
+ secret: true,
82
+ description: "GitHub App private key in PEM format that signs the GitHub App tokens."
83
+ },
84
+ privateKeyPath: {
85
+ names: ["VITEHUB_GITHUB_PRIVATE_KEY_PATH"],
86
+ description: "Path of the GitHub App private key file when the private key is not set."
44
87
  },
45
- privateKeyPath: { names: ["VITEHUB_GITHUB_PRIVATE_KEY_PATH"] },
46
88
  token: {
47
89
  names: ["VITEHUB_GITHUB_TOKEN", "FORGES_GITHUB_TOKEN"],
48
- secret: true
90
+ secret: true,
91
+ description: "GitHub access token that calls the GitHub API."
49
92
  },
50
93
  webhookSecret: {
51
94
  names: ["VITEHUB_GITHUB_WEBHOOK_SECRET", "FORGES_GITHUB_WEBHOOK_SECRET"],
52
- secret: true
95
+ secret: true,
96
+ description: "Secret that checks the signature of each GitHub webhook request."
53
97
  }
54
98
  },
55
99
  gitlab: {
56
- baseUrl: { names: ["VITEHUB_GITLAB_BASE_URL", "FORGES_GITLAB_BASE_URL"] },
100
+ baseUrl: {
101
+ names: ["VITEHUB_GITLAB_BASE_URL", "FORGES_GITLAB_BASE_URL"],
102
+ description: "GitLab URL for a self-managed GitLab instance."
103
+ },
57
104
  token: {
58
105
  names: ["VITEHUB_GITLAB_TOKEN", "FORGES_GITLAB_TOKEN"],
59
- secret: true
106
+ secret: true,
107
+ description: "GitLab access token that calls the GitLab API."
60
108
  },
61
109
  webhookSecret: {
62
110
  names: ["VITEHUB_GITLAB_WEBHOOK_SECRET", "FORGES_GITLAB_WEBHOOK_SECRET"],
63
- secret: true
111
+ secret: true,
112
+ description: "Secret that checks each GitLab webhook request."
64
113
  }
65
114
  },
66
115
  forgejo: {
67
- baseUrl: { names: ["VITEHUB_FORGEJO_BASE_URL", "FORGES_FORGEJO_BASE_URL"] },
116
+ baseUrl: {
117
+ names: ["VITEHUB_FORGEJO_BASE_URL", "FORGES_FORGEJO_BASE_URL"],
118
+ description: "URL of the Forgejo instance."
119
+ },
68
120
  token: {
69
121
  names: ["VITEHUB_FORGEJO_TOKEN", "FORGES_FORGEJO_TOKEN"],
70
- secret: true
122
+ secret: true,
123
+ description: "Forgejo access token that calls the Forgejo API."
71
124
  },
72
125
  webhookSecret: {
73
126
  names: ["VITEHUB_FORGEJO_WEBHOOK_SECRET", "FORGES_FORGEJO_WEBHOOK_SECRET"],
74
- secret: true
127
+ secret: true,
128
+ description: "Secret that checks each Forgejo webhook request."
75
129
  }
76
130
  },
77
131
  gitea: {
78
- baseUrl: { names: ["VITEHUB_GITEA_BASE_URL", "FORGES_GITEA_BASE_URL"] },
132
+ baseUrl: {
133
+ names: ["VITEHUB_GITEA_BASE_URL", "FORGES_GITEA_BASE_URL"],
134
+ description: "URL of the Gitea instance."
135
+ },
79
136
  token: {
80
137
  names: ["VITEHUB_GITEA_TOKEN", "FORGES_GITEA_TOKEN"],
81
- secret: true
138
+ secret: true,
139
+ description: "Gitea access token that calls the Gitea API."
82
140
  },
83
141
  webhookSecret: {
84
142
  names: ["VITEHUB_GITEA_WEBHOOK_SECRET", "FORGES_GITEA_WEBHOOK_SECRET"],
85
- secret: true
143
+ secret: true,
144
+ description: "Secret that checks each Gitea webhook request."
86
145
  }
87
146
  }
88
147
  };
@@ -115,6 +174,10 @@ const forgeErrors = /*#__PURE__*/ defineErrors({
115
174
  why: ({ operation, status }) => status === void 0 ? `${operation} failed.` : `${operation} failed with HTTP ${status}.`,
116
175
  fix: "Read `error.cause` for the Forge error. A 401 means that the App ID, the private key, or the token is wrong. Retry after a 5xx or a network error."
117
176
  },
177
+ FORGE_USER_AUTH_FAILED: {
178
+ why: ({ reason }) => `GitHub refused the user authorization: ${reason}`,
179
+ fix: "Send the person through the GitHub authorization again. Check that the client ID and secret belong to the GitHub App, and that the redirect URI is one of its callback URLs."
180
+ },
118
181
  FORGE_MISSING_ENV: {
119
182
  why: ({ forge, names }) => `The ${forge} Forge has no credentials. It reads ${names}.`,
120
183
  fix: "Set the variables in the host environment, or pass `env` to `useForge()`."
@@ -170,6 +233,14 @@ const forgeDiagnostics = /*#__PURE__*/ defineDiagnostics({
170
233
  ...dynamicError,
171
234
  fix: "Pass a pull request thread with a `number` and a nonempty base branch. For `forgeMerge({ bypassRules })`, also pass `method` and `sha`."
172
235
  },
236
+ FORGE_ARCHIVE_LIMIT_INVALID: {
237
+ why: "`readForgeArchive()` received an invalid `maxBytes` value.",
238
+ fix: "Pass a non-negative safe integer in bytes, or omit `maxBytes` to use the 64 MiB default."
239
+ },
240
+ FORGE_ARCHIVE_TOO_LARGE: {
241
+ why: ({ commit, limit, repo }) => `The archive of ${repo} at ${commit} is larger than ${limit} (\`maxBytes\`).`,
242
+ fix: "Pass a larger `maxBytes` to `readForgeArchive()`, or read only the files you need with `provider.contents.getFile()`."
243
+ },
173
244
  FORGE_RESPONSE_INVALID: {
174
245
  why: ({ problem }) => problem,
175
246
  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."
@@ -277,14 +348,15 @@ function conditionalFetch(fetcher, options = {}) {
277
348
  };
278
349
  }
279
350
  // src/provider.ts
280
- async function forgeProvider(connection) {
351
+ /** The `forges` options of one connection, for a provider made without the dynamic import of `forgeProvider()`. */
352
+ function forgeProviderOptions(connection) {
281
353
  const auth = connection.token ? {
282
354
  type: "token",
283
355
  token: connection.token
284
356
  } : { type: "anonymous" };
285
357
  const conditional = connection.conditionalRequests ?? connection.forge === "github";
286
358
  const fetcher = conditional ? conditionalFetch(connection.fetch ?? ((input, init) => globalThis.fetch(input, init)), conditional === true ? {} : conditional) : connection.fetch;
287
- const options = {
359
+ return {
288
360
  ...connection.baseUrl ? { baseUrl: connection.baseUrl } : {},
289
361
  ...fetcher ? { fetch: fetcher } : {},
290
362
  userAgent: connection.userAgent ?? "vitehub",
@@ -292,21 +364,24 @@ async function forgeProvider(connection) {
292
364
  ...connection.readOnly === void 0 ? {} : { readOnly: connection.readOnly },
293
365
  auth
294
366
  };
367
+ }
368
+ async function forgeProvider(connection) {
369
+ const options = forgeProviderOptions(connection);
295
370
  switch (connection.forge) {
296
371
  case "github": {
297
- const { github } = await import("./github-CHzhqYOr.js");
372
+ const { github } = await Promise.resolve().then(() => github_exports);
298
373
  return github(options);
299
374
  }
300
375
  case "gitlab": {
301
- const { gitlab } = await import("./gitlab-CS0shW2u.js");
376
+ const { gitlab } = await import("./gitlab-CzCikZzN.js");
302
377
  return gitlab(options);
303
378
  }
304
379
  case "forgejo": {
305
- const { forgejo } = await import("./forgejo-4sbZukng.js");
380
+ const { forgejo } = await import("./forgejo-Deckk49p.js");
306
381
  return forgejo(options);
307
382
  }
308
383
  case "gitea": {
309
- const { gitea } = await import("./gitea-Cj7qy2X3.js");
384
+ const { gitea } = await import("./gitea-ChQKeRrf.js");
310
385
  const { webhookSecret } = connection;
311
386
  return gitea({
312
387
  ...options,
@@ -413,7 +488,7 @@ function appProvider(input, installationId = "", refresh = false) {
413
488
  if (refresh) appProviders.delete(key);
414
489
  const cached = appProviders.get(key);
415
490
  if (cached) return cached;
416
- const pending = import("./github-CHzhqYOr.js").then(({ github }) => github({
491
+ const pending = Promise.resolve().then(() => github_exports).then(({ github }) => github({
417
492
  ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
418
493
  ...input.fetch ? { fetch: input.fetch } : {},
419
494
  userAgent: input.userAgent ?? "vitehub",
@@ -438,7 +513,7 @@ async function appIdentity(input) {
438
513
  if (!id) throw forgeResponseError("GitHub App metadata did not include an ID.");
439
514
  if (!slug) throw forgeResponseError("GitHub App response did not include a slug.");
440
515
  const login = `${slug}[bot]`;
441
- const { github } = await import("./github-CHzhqYOr.js");
516
+ const { github } = await Promise.resolve().then(() => github_exports);
442
517
  const userId = await github({
443
518
  ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
444
519
  ...input.fetch ? { fetch: input.fetch } : {},
@@ -649,6 +724,120 @@ function githubInstallationFor(routing, repository) {
649
724
  const owner = repository.split("/", 1)[0].toLowerCase();
650
725
  return (Object.hasOwn(routing.installations, owner) ? routing.installations[owner] : void 0) ?? (owner === routing.owner ? routing.installationId : void 0);
651
726
  }
727
+ // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/github/index.mjs
728
+ var github_exports = /* @__PURE__ */ __exportAll({ github: () => github });
729
+ /** Creates a GitHub provider for github.com or a GitHub Enterprise Server instance. */
730
+ const github = /* @__PURE__ */ defineForgeProvider(/* @__PURE__ */ githubDefinition(GITHUB_PROFILE));
731
+ // src/github-user.ts
732
+ function githubWebUrl(baseUrl) {
733
+ if (!baseUrl) return "https://github.com";
734
+ const url = new URL(baseUrl);
735
+ if (url.hostname === "api.github.com" || /^api\.[a-z0-9-]+\.ghe\.com$/.test(url.hostname)) url.hostname = url.hostname.slice(4);
736
+ return url.origin;
737
+ }
738
+ function expiry(seconds, now) {
739
+ return typeof seconds === "number" && seconds > 0 ? new Date(now + seconds * 1e3) : void 0;
740
+ }
741
+ /** `forge.user` of a GitHub Forge. */
742
+ function githubUser(input) {
743
+ const web = githubWebUrl(input.baseUrl);
744
+ const fetcher = input.fetch ?? ((url, init) => globalThis.fetch(url, init));
745
+ function provider(token) {
746
+ return github(forgeProviderOptions({
747
+ forge: "github",
748
+ token,
749
+ userAgent: input.userAgent,
750
+ ...input.baseUrl ? { baseUrl: input.baseUrl } : {},
751
+ ...input.fetch ? { fetch: input.fetch } : {},
752
+ ...input.conditionalRequests === false ? { conditionalRequests: false } : {}
753
+ }));
754
+ }
755
+ function failed(operation, cause, signal) {
756
+ if (signal?.aborted) throw abortError(signal);
757
+ const status = forgeErrorStatus(cause);
758
+ return forgeErrors.FORGE_REQUEST_FAILED({
759
+ cause,
760
+ operation,
761
+ ...status === void 0 ? {} : { status }
762
+ });
763
+ }
764
+ async function grant(params, signal) {
765
+ if (signal?.aborted) throw abortError(signal);
766
+ const operation = "POST /login/oauth/access_token";
767
+ const now = Date.now();
768
+ let body;
769
+ try {
770
+ const response = await fetcher(`${web}/login/oauth/access_token`, {
771
+ method: "POST",
772
+ headers: {
773
+ "accept": "application/json",
774
+ "content-type": "application/x-www-form-urlencoded",
775
+ "user-agent": input.userAgent
776
+ },
777
+ body: new URLSearchParams({
778
+ client_id: input.clientId,
779
+ client_secret: input.clientSecret,
780
+ ...params
781
+ }),
782
+ ...signal ? { signal } : {}
783
+ });
784
+ if (!response.ok) return [forgeErrors.FORGE_REQUEST_FAILED({
785
+ operation,
786
+ status: response.status
787
+ }), void 0];
788
+ body = await response.json();
789
+ } catch (cause) {
790
+ return [failed(operation, cause, signal), void 0];
791
+ }
792
+ if (typeof body.error === "string") {
793
+ const reason = typeof body.error_description === "string" ? `${body.error_description} (${body.error})` : body.error;
794
+ return [forgeErrors.FORGE_USER_AUTH_FAILED({ reason }), void 0];
795
+ }
796
+ if (typeof body.access_token !== "string" || !body.access_token) return [failed(operation, forgeResponseError("GitHub user token response did not include access_token."), signal), void 0];
797
+ const token = body.access_token;
798
+ let user;
799
+ try {
800
+ user = (await provider(token).request("GET", "/user", signal ? { signal } : {})).data;
801
+ } catch (cause) {
802
+ return [failed("GET /user", cause, signal), void 0];
803
+ }
804
+ if (typeof user.login !== "string" || typeof user.id !== "number") return [failed("GET /user", forgeResponseError("GitHub user response did not include login and id."), signal), void 0];
805
+ return [void 0, {
806
+ token,
807
+ expiresAt: expiry(body.expires_in, now),
808
+ refreshToken: typeof body.refresh_token === "string" && body.refresh_token ? body.refresh_token : void 0,
809
+ refreshTokenExpiresAt: expiry(body.refresh_token_expires_in, now),
810
+ login: user.login,
811
+ id: user.id
812
+ }];
813
+ }
814
+ return {
815
+ authorizeUrl({ redirectUri, state }) {
816
+ const url = new URL("/login/oauth/authorize", web);
817
+ url.search = new URLSearchParams({
818
+ client_id: input.clientId,
819
+ redirect_uri: redirectUri,
820
+ state
821
+ }).toString();
822
+ return url.toString();
823
+ },
824
+ exchange({ code, redirectUri, signal }) {
825
+ return grant({
826
+ code,
827
+ redirect_uri: redirectUri
828
+ }, signal);
829
+ },
830
+ refresh({ refreshToken, signal }) {
831
+ return grant({
832
+ grant_type: "refresh_token",
833
+ refresh_token: refreshToken
834
+ }, signal);
835
+ },
836
+ provider({ token }) {
837
+ return provider(token);
838
+ }
839
+ };
840
+ }
652
841
  // src/use-forge.ts
653
842
  function hostEnv(name) {
654
843
  return getActiveCloudflareBinding(name) ?? globalThis.process?.env?.[name];
@@ -681,6 +870,31 @@ function readGitHubApp(env) {
681
870
  privateKeyPath
682
871
  };
683
872
  }
873
+ function readGitHubUser(env) {
874
+ const { github } = forgeEnv;
875
+ const clientId = readForgeEnv(github.clientId, env);
876
+ const clientSecret = readForgeEnv(github.clientSecret, env);
877
+ if (!clientId || !clientSecret) return void 0;
878
+ return {
879
+ clientId,
880
+ clientSecret
881
+ };
882
+ }
883
+ async function readAppPrivateKey(config) {
884
+ const name = primaryName(forgeEnv.github.privateKeyPath);
885
+ const privateKey = await readGitHubAppPrivateKey(config.privateKey, config.privateKeyPath).catch((cause) => {
886
+ throw forgeErrors.FORGE_INVALID_ENV({
887
+ cause,
888
+ name,
889
+ problem: `names a file that cannot be read: ${config.privateKeyPath}`
890
+ });
891
+ });
892
+ if (!privateKey) throw forgeErrors.FORGE_INVALID_ENV({
893
+ name,
894
+ problem: `names an empty file: ${config.privateKeyPath}`
895
+ });
896
+ return privateKey;
897
+ }
684
898
  function requestFailed(operation, cause, signal) {
685
899
  if (signal?.aborted) throw abortError(signal);
686
900
  const status = forgeErrorStatus(cause) ?? (isRuntimeDiagnostic(cause) ? forgeErrorStatus(cause.cause) : void 0);
@@ -690,20 +904,11 @@ function requestFailed(operation, cause, signal) {
690
904
  ...status === void 0 ? {} : { status }
691
905
  });
692
906
  }
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 = {}) {
907
+ function resolveForgeConfig(options) {
703
908
  const kind = options.forge ?? "github";
704
909
  const env = options.env ?? hostEnv;
705
- const fields = forgeEnv;
706
910
  const githubApp = kind === "github" ? readGitHubApp(env) : void 0;
911
+ const githubUserConfig = kind === "github" ? readGitHubUser(env) : void 0;
707
912
  const configuredToken = githubApp ? void 0 : readForgeEnv(forgeEnv[kind].token, env);
708
913
  const credential = githubApp ? { app: githubApp } : configuredToken ? { token: configuredToken } : void 0;
709
914
  if (!credential) {
@@ -713,31 +918,42 @@ function useForge(options = {}) {
713
918
  names
714
919
  });
715
920
  }
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;
921
+ return {
922
+ kind,
923
+ credential,
924
+ baseUrl: options.baseUrl ?? readForgeEnv(forgeEnv[kind].baseUrl, env),
925
+ webhookSecret: kind === "gitea" ? readForgeEnv(forgeEnv.gitea.webhookSecret, env) : void 0,
926
+ githubUserConfig
927
+ };
928
+ }
929
+ /**
930
+ * The Forge identity of this deployment, read from the same Server Env as Channels, Workspaces and Sources.
931
+ * GitHub uses a GitHub App when `VITEHUB_GITHUB_APP_ID` is set, and `VITEHUB_GITHUB_TOKEN` otherwise.
932
+ * Throws a config error when the env has no credentials. Runtime operations return `[error, data]`.
933
+ *
934
+ * ```ts
935
+ * const [error, provider] = await useForge().provider({ repository: "acme/web" })
936
+ * ```
937
+ */
938
+ function useForge(options = {}) {
939
+ const { kind, credential, baseUrl, webhookSecret, githubUserConfig } = resolveForgeConfig(options);
719
940
  const userAgent = options.userAgent ?? "vitehub";
941
+ const user = githubUserConfig ? githubUser({
942
+ ...githubUserConfig,
943
+ userAgent,
944
+ ...baseUrl ? { baseUrl } : {},
945
+ ...options.fetch ? { fetch: options.fetch } : {},
946
+ ...options.conditionalRequests === false ? { conditionalRequests: false } : {}
947
+ }) : void 0;
720
948
  let credentials;
721
949
  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
- });
950
+ credentials ??= readAppPrivateKey(config).then((privateKey) => githubAppCredentials({
951
+ appId: config.appId,
952
+ privateKey,
953
+ userAgent,
954
+ ...baseUrl ? { baseUrl } : {},
955
+ ...options.fetch ? { fetch: options.fetch } : {}
956
+ }));
741
957
  credentials.catch(() => {
742
958
  credentials = void 0;
743
959
  });
@@ -781,6 +997,7 @@ function useForge(options = {}) {
781
997
  kind,
782
998
  auth: "app" in credential ? "app" : "token",
783
999
  baseUrl,
1000
+ user,
784
1001
  async token(call = {}) {
785
1002
  if (call.signal?.aborted) throw abortError(call.signal);
786
1003
  if (!("app" in credential)) return [void 0, {
@@ -824,6 +1041,67 @@ function useForge(options = {}) {
824
1041
  }
825
1042
  };
826
1043
  }
1044
+ /**
1045
+ * Checks the Forge env and sends no request, for example for a Setup page. It returns `[undefined, { kind, auth, user }]`
1046
+ * when local configuration is valid, or `[error, undefined]` with a configuration error. It checks the base URL
1047
+ * and signs locally with the GitHub App private key, but does not check that the forge accepts the credentials.
1048
+ *
1049
+ * ```ts
1050
+ * const [error] = await checkForge()
1051
+ * if (error) return { configured: false, fix: error.fix }
1052
+ * ```
1053
+ */
1054
+ async function checkForge(options = {}) {
1055
+ try {
1056
+ const { kind, credential, baseUrl, githubUserConfig } = resolveForgeConfig(options);
1057
+ const user = githubUserConfig !== void 0;
1058
+ if (baseUrl) try {
1059
+ await forgeProvider({
1060
+ forge: kind,
1061
+ baseUrl,
1062
+ ...options.fetch ? { fetch: options.fetch } : {}
1063
+ });
1064
+ } catch (error) {
1065
+ if (!(error instanceof TypeError)) throw error;
1066
+ const name = options.baseUrl === void 0 ? primaryName(forgeEnv[kind].baseUrl) : "baseUrl";
1067
+ throw forgeErrors.FORGE_INVALID_ENV({
1068
+ name,
1069
+ problem: "must be a valid HTTP(S) base URL without credentials, a query, or a fragment"
1070
+ });
1071
+ }
1072
+ if (!("app" in credential)) return [void 0, {
1073
+ kind,
1074
+ auth: "token",
1075
+ user
1076
+ }];
1077
+ const { app } = credential;
1078
+ const privateKey = await readAppPrivateKey(app);
1079
+ const { signRs256Jwt } = await import("./kit-CrquHPqr.js");
1080
+ try {
1081
+ const now = Math.floor(Date.now() / 1e3);
1082
+ await signRs256Jwt(privateKey, {
1083
+ iss: app.appId,
1084
+ iat: now,
1085
+ exp: now + 60
1086
+ });
1087
+ } catch (cause) {
1088
+ const name = primaryName(app.privateKey ? forgeEnv.github.privateKey : forgeEnv.github.privateKeyPath);
1089
+ throw forgeErrors.FORGE_INVALID_ENV({
1090
+ cause,
1091
+ name,
1092
+ problem: "must supply a PEM-encoded RSA private key that can sign a GitHub App JWT"
1093
+ });
1094
+ }
1095
+ return [void 0, {
1096
+ kind,
1097
+ auth: "app",
1098
+ user
1099
+ }];
1100
+ } catch (error) {
1101
+ if (forgeErrors.FORGE_MISSING_ENV.is(error) || forgeErrors.FORGE_INVALID_ENV.is(error)) return [error, void 0];
1102
+ throw error;
1103
+ }
1104
+ }
827
1105
  // src/gaps/archive.ts
828
1106
  /**
829
1107
  * The repository tree at `ref` as a gzipped tarball stream.
@@ -831,7 +1109,10 @@ function useForge(options = {}) {
831
1109
  * (https://github.com/danielroe/forges/issues/191).
832
1110
  */
833
1111
  async function forgeArchive(provider, repo, options) {
834
- if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0002({ message: `Repository archives are not supported for ${provider.forge}.` });
1112
+ assertArchiveProvider(provider);
1113
+ return downloadForgeArchive(provider, repo, options);
1114
+ }
1115
+ async function downloadForgeArchive(provider, repo, options) {
835
1116
  const owner = encodeURIComponent(repo.owner);
836
1117
  const name = encodeURIComponent(repo.name);
837
1118
  const ref = options.ref.split("/").map(encodeURIComponent).join("/");
@@ -841,6 +1122,60 @@ async function forgeArchive(provider, repo, options) {
841
1122
  signal: options.signal
842
1123
  })).body;
843
1124
  }
1125
+ const defaultArchiveMaxBytes = 67108864;
1126
+ /**
1127
+ * The repository tree at `ref` as `tar.gz` bytes, with the commit it came from. Reads at most `maxBytes` (64 MiB by
1128
+ * default). GitHub only.
1129
+ *
1130
+ * ```ts
1131
+ * const { commit, bytes } = await readForgeArchive(provider, repo, { ref: "main", maxBytes: 32 * 1024 * 1024 })
1132
+ * ```
1133
+ */
1134
+ async function readForgeArchive(provider, repo, options) {
1135
+ assertArchiveProvider(provider);
1136
+ const maxBytes = options.maxBytes ?? defaultArchiveMaxBytes;
1137
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw forgeDiagnostics.FORGE_ARCHIVE_LIMIT_INVALID();
1138
+ 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 });
1139
+ const tooLarge = () => forgeDiagnostics.FORGE_ARCHIVE_TOO_LARGE({
1140
+ commit,
1141
+ limit: formatBytes(maxBytes),
1142
+ repo: `${repo.owner}/${repo.name}`
1143
+ });
1144
+ const reader = (await downloadForgeArchive(provider, repo, {
1145
+ ref: commit,
1146
+ signal: options.signal
1147
+ })).getReader();
1148
+ const chunks = [];
1149
+ let size = 0;
1150
+ try {
1151
+ while (true) {
1152
+ const { value, done } = await reader.read();
1153
+ if (done) break;
1154
+ size += value.byteLength;
1155
+ if (size > maxBytes) throw tooLarge();
1156
+ chunks.push(value);
1157
+ }
1158
+ } finally {
1159
+ await reader.cancel().catch(() => {});
1160
+ }
1161
+ const bytes = new Uint8Array(size);
1162
+ let offset = 0;
1163
+ for (const chunk of chunks) {
1164
+ bytes.set(chunk, offset);
1165
+ offset += chunk.byteLength;
1166
+ }
1167
+ return {
1168
+ commit,
1169
+ bytes
1170
+ };
1171
+ }
1172
+ function assertArchiveProvider(provider) {
1173
+ if (provider.forge !== "github") throw forgeDiagnostics.FORGE_R0002({ message: `Repository archives are not supported for ${provider.forge}.` });
1174
+ }
1175
+ function formatBytes(bytes) {
1176
+ const mib = bytes / 1048576;
1177
+ return Number.isInteger(mib) ? `${mib} MiB` : `${bytes} bytes`;
1178
+ }
844
1179
  // src/gaps/blob.ts
845
1180
  /**
846
1181
  * The bytes of one Git blob, by its sha. The blob of a symlink holds the link target.
@@ -860,7 +1195,7 @@ function decodeBase64Blob(value) {
860
1195
  const content = value.content.replace(/\s+/g, "");
861
1196
  if (content.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(content)) return void 0;
862
1197
  try {
863
- const bytes = Buffer.from(content, "base64");
1198
+ const bytes = Buffer$1.from(content, "base64");
864
1199
  return bytes.toString("base64") === content ? bytes : void 0;
865
1200
  } catch {
866
1201
  return;
@@ -987,7 +1322,7 @@ async function forgeCommitFiles(provider, repo, input, options = {}) {
987
1322
  sha: null,
988
1323
  type: "blob"
989
1324
  };
990
- const content = Buffer.from(change.content).toString("base64");
1325
+ const content = Buffer$1.from(change.content).toString("base64");
991
1326
  let blob = blobs.get(content);
992
1327
  if (!blob) {
993
1328
  blob = provider.request("POST", `${base}/blobs`, {
@@ -1124,7 +1459,7 @@ function forgeGitCredentials(input) {
1124
1459
  */
1125
1460
  function forgeGitAuthHeader(credentials) {
1126
1461
  if (!credentials.password) return void 0;
1127
- const basic = Buffer.from(`${credentials.username ?? ""}:${credentials.password}`).toString("base64");
1462
+ const basic = Buffer$1.from(`${credentials.username ?? ""}:${credentials.password}`).toString("base64");
1128
1463
  return {
1129
1464
  key: `http.${credentials.url}.extraheader`,
1130
1465
  value: `AUTHORIZATION: basic ${basic}`
@@ -1231,4 +1566,4 @@ async function retargetPullRequest(provider, thread, base, options) {
1231
1566
  signal: options?.signal
1232
1567
  });
1233
1568
  }
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 };
1569
+ 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,4 @@
1
+ export { i as signRs256Jwt } from "./crypto-DydCoK4e-BCG61qh5.js";
2
+ import "./utils-DEwhctg5-BM3AMnSs.js";
3
+ import "./define-C9xZZNVR-C-oojQRP.js";
4
+ import "./webhooks-Bc6QhmI8-CgoCnwj1.js";
@@ -1,5 +1,4 @@
1
- import { b as NotFoundError } from "./model-Biiu1CfI-CVLamGai.js";
2
- import { z as mapConcurrent } from "./webhooks-Bc6QhmI8-eK71_mJE.js";
1
+ import { ot as NotFoundError, v as mapConcurrent } from "./utils-DEwhctg5-BM3AMnSs.js";
3
2
  // ../../node_modules/.pnpm/forges@0.4.1/node_modules/forges/dist/templates-0m5QBVIh.mjs
4
3
  /** Where GitHub looks for a pull request template and the legacy issue template, in its order of precedence. */
5
4
  const LOCATIONS = [