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