@deepseek-ai/dsh-experimental-forge-github 0.0.0-stage → 0.2.2-alpha.3
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 +21 -0
- package/README.i18n.yaml +37 -0
- package/README.md +108 -2
- package/README.zh.md +109 -0
- package/lib/index.js +1083 -0
- package/lib/types/gh.d.ts +43 -0
- package/lib/types/graphql.d.ts +75 -0
- package/lib/types/index.d.ts +19 -0
- package/lib/types/provider.d.ts +53 -0
- package/lib/types/review.d.ts +13 -0
- package/lib/types/urls.d.ts +44 -0
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +45 -3
package/lib/index.js
ADDED
|
@@ -0,0 +1,1083 @@
|
|
|
1
|
+
import z from "@deepseek-ai/schemastery";
|
|
2
|
+
import { MAX_TIMER_DELAY_MS } from "@deepseek-ai/dsh-timeout";
|
|
3
|
+
import { scrubbedParentEnv } from "@deepseek-ai/dsh-subprocess";
|
|
4
|
+
import { execa } from "execa";
|
|
5
|
+
import { changeRequestKey } from "@deepseek-ai/dsh-experimental-forge";
|
|
6
|
+
import { z as z$1 } from "zod";
|
|
7
|
+
//#region lib/types/gh.js
|
|
8
|
+
/** Runs the GitHub CLI on the host with a scrubbed, non-interactive environment. */
|
|
9
|
+
/** Thrown when the `gh` executable cannot start, for example because it is not installed. */
|
|
10
|
+
var GhUnavailableError = class extends Error {
|
|
11
|
+
name = "GhUnavailableError";
|
|
12
|
+
};
|
|
13
|
+
/** Thrown when one invocation outlives `timeoutMs`; the process is killed. */
|
|
14
|
+
var GhTimeoutError = class extends Error {
|
|
15
|
+
name = "GhTimeoutError";
|
|
16
|
+
};
|
|
17
|
+
/** Thrown when an output stream exceeds `maxOutputBytes`; the process is killed. */
|
|
18
|
+
var GhOutputLimitError = class extends Error {
|
|
19
|
+
name = "GhOutputLimitError";
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Build a runner for `gh` on the host. The child inherits the scrubbed parent
|
|
23
|
+
* environment, so variables whose names contain KEY, PASSWORD, SECRET, or
|
|
24
|
+
* TOKEN never reach it and `gh` authenticates from its own credential store.
|
|
25
|
+
* Prompts, update notices, pagers, and colors are disabled.
|
|
26
|
+
* @param config - executable and limits.
|
|
27
|
+
* @returns the runner.
|
|
28
|
+
*/
|
|
29
|
+
function ghRunner(config) {
|
|
30
|
+
return async (args, signal, input) => {
|
|
31
|
+
const result = await execa(config.ghCommand, args, {
|
|
32
|
+
env: {
|
|
33
|
+
...scrubbedParentEnv(),
|
|
34
|
+
GH_PROMPT_DISABLED: "1",
|
|
35
|
+
GH_NO_UPDATE_NOTIFIER: "1",
|
|
36
|
+
GH_PAGER: "",
|
|
37
|
+
NO_COLOR: "1",
|
|
38
|
+
CLICOLOR: "0"
|
|
39
|
+
},
|
|
40
|
+
extendEnv: false,
|
|
41
|
+
...input === void 0 ? { stdin: "ignore" } : { input },
|
|
42
|
+
reject: false,
|
|
43
|
+
timeout: config.timeoutMs,
|
|
44
|
+
cancelSignal: signal,
|
|
45
|
+
maxBuffer: config.maxOutputBytes
|
|
46
|
+
});
|
|
47
|
+
const command = ["gh", ...args.slice(0, 1)].join(" ");
|
|
48
|
+
if (result.isCanceled) throw signal.reason;
|
|
49
|
+
if (result.timedOut) throw new GhTimeoutError(`${command} timed out after ${config.timeoutMs}ms`);
|
|
50
|
+
if (result.isMaxBuffer) throw new GhOutputLimitError(`${command} output exceeds maxOutputBytes`);
|
|
51
|
+
if (result.exitCode === void 0) throw new GhUnavailableError(`gh could not start: ${String(result.shortMessage)}`);
|
|
52
|
+
return {
|
|
53
|
+
exitCode: result.exitCode,
|
|
54
|
+
stdout: result.stdout,
|
|
55
|
+
stderr: result.stderr
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region lib/types/urls.js
|
|
61
|
+
/** GitHub remote URL and pull request URL parsing, and validation of the parts inlined into requests. */
|
|
62
|
+
/** Characters GitHub permits in owner and repository names. */
|
|
63
|
+
const SEGMENT = /^[A-Za-z0-9_.-]+$/;
|
|
64
|
+
/**
|
|
65
|
+
* Check one owner or repository name segment.
|
|
66
|
+
* @param value - candidate segment.
|
|
67
|
+
* @returns whether GitHub permits the segment and it is not a dot path.
|
|
68
|
+
*/
|
|
69
|
+
function isSegment(value) {
|
|
70
|
+
return SEGMENT.test(value) && value !== "." && value !== "..";
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Validate a pull request before its owner, name, and number are inlined into
|
|
74
|
+
* a GraphQL document, a `gh` argument, or an API path.
|
|
75
|
+
* @param ref - pull request on a GitHub host.
|
|
76
|
+
* @returns its repository.
|
|
77
|
+
* @throws when the owner or name is not a permitted segment or the number is not a positive integer.
|
|
78
|
+
*/
|
|
79
|
+
function checkedRepository(ref) {
|
|
80
|
+
const { owner, name } = ref.repository;
|
|
81
|
+
if (!isSegment(owner) || !isSegment(name)) throw new Error(`forge-github: invalid repository ${JSON.stringify(`${owner}/${name}`)}`);
|
|
82
|
+
if (!Number.isSafeInteger(ref.number) || ref.number <= 0) throw new Error(`forge-github: invalid pull request number ${ref.number}`);
|
|
83
|
+
return ref.repository;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Parse a Git remote URL. Accepts `http(s)://[user@]host[:port]/owner/name`,
|
|
87
|
+
* `ssh://[user@]host[:port]/owner/name`, `git://host/owner/name`, and the
|
|
88
|
+
* scp-like `[user@]host:owner/name`, each with an optional `.git` suffix or
|
|
89
|
+
* trailing slash. HTTP(S) ports belong to the host identity; SSH and Git
|
|
90
|
+
* transport ports do not.
|
|
91
|
+
* @param url - fetch or push URL as Git reports it.
|
|
92
|
+
* @returns the location, or undefined for other URL shapes.
|
|
93
|
+
*/
|
|
94
|
+
function parseRemoteUrl(url) {
|
|
95
|
+
const trimmed = url.trim();
|
|
96
|
+
const scheme = /^https?:\/\/(?:[^@/]+@)?([^/:]+(?::\d+)?)\/(.+)$/i.exec(trimmed) ?? /^(?:ssh|git):\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/i.exec(trimmed);
|
|
97
|
+
const scp = scheme === null ? /^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.+)$/.exec(trimmed) : null;
|
|
98
|
+
const match = scheme ?? scp;
|
|
99
|
+
if (match === null) return void 0;
|
|
100
|
+
const [, host = "", path = ""] = match;
|
|
101
|
+
const parts = path.replace(/\/+$/, "").replace(/\.git$/i, "").split("/");
|
|
102
|
+
if (parts.length !== 2) return void 0;
|
|
103
|
+
const [owner = "", name = ""] = parts;
|
|
104
|
+
if (!isSegment(owner) || !isSegment(name)) return void 0;
|
|
105
|
+
return {
|
|
106
|
+
host: host.toLowerCase(),
|
|
107
|
+
owner,
|
|
108
|
+
name
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Parse a pull request web URL such as `https://github.com/owner/name/pull/12/files`.
|
|
113
|
+
* @param url - web URL of a pull request.
|
|
114
|
+
* @returns the location and number, or undefined for other URLs.
|
|
115
|
+
*/
|
|
116
|
+
function parsePullRequestUrl(url) {
|
|
117
|
+
const match = /^https?:\/\/([^/]+)\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[/?#].*)?$/i.exec(url.trim());
|
|
118
|
+
if (match === null) return void 0;
|
|
119
|
+
const [, host = "", owner = "", name = "", digits = ""] = match;
|
|
120
|
+
const number = Number(digits);
|
|
121
|
+
if (!isSegment(owner) || !isSegment(name) || !Number.isSafeInteger(number) || number <= 0) return void 0;
|
|
122
|
+
return {
|
|
123
|
+
host: host.toLowerCase(),
|
|
124
|
+
owner,
|
|
125
|
+
name,
|
|
126
|
+
number
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
//#endregion
|
|
130
|
+
//#region lib/types/graphql.js
|
|
131
|
+
/** GitHub GraphQL documents and their mapping into provider-neutral results. */
|
|
132
|
+
const CHECK_FIELDS = `pageInfo { hasNextPage endCursor }
|
|
133
|
+
nodes {
|
|
134
|
+
__typename
|
|
135
|
+
... on CheckRun {
|
|
136
|
+
id databaseId name status conclusion detailsUrl startedAt completedAt
|
|
137
|
+
checkSuite { app { id } workflowRun { event workflow { id name } } }
|
|
138
|
+
}
|
|
139
|
+
... on StatusContext { context state targetUrl createdAt }
|
|
140
|
+
}`;
|
|
141
|
+
const PULL_REQUEST_FIELDS = `number url title state isDraft updatedAt closedAt
|
|
142
|
+
author { login }
|
|
143
|
+
headRefName headRefOid baseRefName additions deletions mergeable mergeStateStatus reviewDecision
|
|
144
|
+
reviewThreads(first: 100) { nodes { isResolved } }
|
|
145
|
+
commits(last: 1) { nodes { commit { statusCheckRollup { id state contexts(first: 100) {
|
|
146
|
+
${CHECK_FIELDS}
|
|
147
|
+
} } } } }`;
|
|
148
|
+
/** Continue reading the same commit's rollup even if the pull request head moves. */
|
|
149
|
+
const CHECKS_QUERY = `query($id: ID!, $cursor: String!) {
|
|
150
|
+
node(id: $id) { ... on StatusCheckRollup { contexts(first: 100, after: $cursor) { ${CHECK_FIELDS} } } }
|
|
151
|
+
}`;
|
|
152
|
+
const REPOSITORY_FIELDS = "squashMergeAllowed mergeCommitAllowed rebaseMergeAllowed viewerPermission viewerDefaultMergeMethod";
|
|
153
|
+
/** Head-branch lookup; variables `owner`, `name`, and `branch` are passed as strings. */
|
|
154
|
+
const HEAD_QUERY = `query($owner: String!, $name: String!, $branch: String!) {
|
|
155
|
+
repository(owner: $owner, name: $name) {
|
|
156
|
+
defaultBranchRef { name }
|
|
157
|
+
pullRequests(headRefName: $branch, states: OPEN, first: 20, orderBy: { field: CREATED_AT, direction: DESC }) { nodes { number isCrossRepository } }
|
|
158
|
+
}
|
|
159
|
+
}`;
|
|
160
|
+
const checkRunSchema = z$1.object({
|
|
161
|
+
__typename: z$1.literal("CheckRun"),
|
|
162
|
+
id: z$1.string(),
|
|
163
|
+
databaseId: z$1.number().int().nonnegative().nullable(),
|
|
164
|
+
name: z$1.string(),
|
|
165
|
+
status: z$1.string(),
|
|
166
|
+
conclusion: z$1.string().nullable(),
|
|
167
|
+
detailsUrl: z$1.string().nullable(),
|
|
168
|
+
startedAt: z$1.string().nullable(),
|
|
169
|
+
completedAt: z$1.string().nullable(),
|
|
170
|
+
checkSuite: z$1.object({
|
|
171
|
+
app: z$1.object({ id: z$1.string() }).nullable(),
|
|
172
|
+
workflowRun: z$1.object({
|
|
173
|
+
event: z$1.string(),
|
|
174
|
+
workflow: z$1.object({
|
|
175
|
+
id: z$1.string(),
|
|
176
|
+
name: z$1.string()
|
|
177
|
+
})
|
|
178
|
+
}).nullable()
|
|
179
|
+
}).nullable()
|
|
180
|
+
});
|
|
181
|
+
const statusContextSchema = z$1.object({
|
|
182
|
+
__typename: z$1.literal("StatusContext"),
|
|
183
|
+
context: z$1.string(),
|
|
184
|
+
createdAt: z$1.iso.datetime(),
|
|
185
|
+
state: z$1.string(),
|
|
186
|
+
targetUrl: z$1.string().nullable()
|
|
187
|
+
});
|
|
188
|
+
const checkPageSchema = z$1.object({
|
|
189
|
+
pageInfo: z$1.object({
|
|
190
|
+
hasNextPage: z$1.boolean(),
|
|
191
|
+
endCursor: z$1.string().nullable()
|
|
192
|
+
}),
|
|
193
|
+
nodes: z$1.array(z$1.unknown())
|
|
194
|
+
});
|
|
195
|
+
const pullRequestSchema = z$1.object({
|
|
196
|
+
url: z$1.string(),
|
|
197
|
+
title: z$1.string(),
|
|
198
|
+
state: z$1.enum([
|
|
199
|
+
"OPEN",
|
|
200
|
+
"CLOSED",
|
|
201
|
+
"MERGED"
|
|
202
|
+
]),
|
|
203
|
+
isDraft: z$1.boolean(),
|
|
204
|
+
updatedAt: z$1.string(),
|
|
205
|
+
closedAt: z$1.string().nullable(),
|
|
206
|
+
author: z$1.object({ login: z$1.string() }).nullable(),
|
|
207
|
+
headRefName: z$1.string(),
|
|
208
|
+
headRefOid: z$1.string(),
|
|
209
|
+
baseRefName: z$1.string(),
|
|
210
|
+
additions: z$1.number().int().nonnegative(),
|
|
211
|
+
deletions: z$1.number().int().nonnegative(),
|
|
212
|
+
mergeable: z$1.string(),
|
|
213
|
+
mergeStateStatus: z$1.string(),
|
|
214
|
+
reviewDecision: z$1.string().nullable(),
|
|
215
|
+
reviewThreads: z$1.object({ nodes: z$1.array(z$1.object({ isResolved: z$1.boolean() })) }),
|
|
216
|
+
commits: z$1.object({ nodes: z$1.array(z$1.object({ commit: z$1.object({ statusCheckRollup: z$1.object({
|
|
217
|
+
id: z$1.string().transform((value) => value),
|
|
218
|
+
state: z$1.string(),
|
|
219
|
+
contexts: checkPageSchema
|
|
220
|
+
}).nullable() }) })) })
|
|
221
|
+
});
|
|
222
|
+
const repositorySchema = z$1.object({
|
|
223
|
+
squashMergeAllowed: z$1.boolean(),
|
|
224
|
+
mergeCommitAllowed: z$1.boolean(),
|
|
225
|
+
rebaseMergeAllowed: z$1.boolean(),
|
|
226
|
+
viewerPermission: z$1.string().nullable(),
|
|
227
|
+
viewerDefaultMergeMethod: z$1.string()
|
|
228
|
+
});
|
|
229
|
+
const responseSchema = z$1.object({
|
|
230
|
+
data: z$1.record(z$1.string(), z$1.record(z$1.string(), z$1.unknown()).nullable()).nullable().optional(),
|
|
231
|
+
errors: z$1.array(z$1.object({
|
|
232
|
+
type: z$1.string().optional(),
|
|
233
|
+
path: z$1.array(z$1.union([z$1.string(), z$1.number()])).optional(),
|
|
234
|
+
message: z$1.string()
|
|
235
|
+
})).optional()
|
|
236
|
+
}).refine(hasGraphqlFields);
|
|
237
|
+
/**
|
|
238
|
+
* Distinguish GraphQL response fields from HTTP error bodies.
|
|
239
|
+
* @param body - parsed JSON returned by GitHub.
|
|
240
|
+
* @returns whether the object carries GraphQL data or errors; field validation remains with the query mapper.
|
|
241
|
+
*/
|
|
242
|
+
function hasGraphqlFields(body) {
|
|
243
|
+
return typeof body === "object" && body !== null && ("data" in body || "errors" in body);
|
|
244
|
+
}
|
|
245
|
+
const headSchema = z$1.object({ data: z$1.object({ repository: z$1.object({
|
|
246
|
+
defaultBranchRef: z$1.object({ name: z$1.string() }).nullable(),
|
|
247
|
+
pullRequests: z$1.object({ nodes: z$1.array(z$1.object({
|
|
248
|
+
number: z$1.number(),
|
|
249
|
+
isCrossRepository: z$1.boolean()
|
|
250
|
+
})) })
|
|
251
|
+
}).nullable() }) });
|
|
252
|
+
/** GitHub merge states in which the merge button works: mergeable, with passing or non-required failing checks. */
|
|
253
|
+
const MERGEABLE_NOW = new Set([
|
|
254
|
+
"CLEAN",
|
|
255
|
+
"HAS_HOOKS",
|
|
256
|
+
"UNSTABLE"
|
|
257
|
+
]);
|
|
258
|
+
/** Repository permissions that may merge. */
|
|
259
|
+
const MERGERS = new Set([
|
|
260
|
+
"ADMIN",
|
|
261
|
+
"MAINTAIN",
|
|
262
|
+
"WRITE"
|
|
263
|
+
]);
|
|
264
|
+
/** Merge methods in menu order, with the repository setting that allows each and GitHub's name for it. */
|
|
265
|
+
const METHODS = [
|
|
266
|
+
{
|
|
267
|
+
method: "squash",
|
|
268
|
+
allowed: "squashMergeAllowed",
|
|
269
|
+
name: "SQUASH"
|
|
270
|
+
},
|
|
271
|
+
{
|
|
272
|
+
method: "merge",
|
|
273
|
+
allowed: "mergeCommitAllowed",
|
|
274
|
+
name: "MERGE"
|
|
275
|
+
},
|
|
276
|
+
{
|
|
277
|
+
method: "rebase",
|
|
278
|
+
allowed: "rebaseMergeAllowed",
|
|
279
|
+
name: "REBASE"
|
|
280
|
+
}
|
|
281
|
+
];
|
|
282
|
+
/**
|
|
283
|
+
* Build one query that reads every change request in `refs`, grouping them by
|
|
284
|
+
* repository. Owners, names, and numbers are validated before they are inlined.
|
|
285
|
+
* @param refs - change requests on one host.
|
|
286
|
+
* @returns the document and its alias targets.
|
|
287
|
+
* @throws when an owner, name, or number cannot be inlined safely.
|
|
288
|
+
*/
|
|
289
|
+
function snapshotQuery(refs) {
|
|
290
|
+
const repositories = /* @__PURE__ */ new Map();
|
|
291
|
+
for (const ref of refs) {
|
|
292
|
+
const { owner, name } = checkedRepository(ref);
|
|
293
|
+
const id = `${owner}/${name}`.toLowerCase();
|
|
294
|
+
let entry = repositories.get(id);
|
|
295
|
+
if (entry === void 0) {
|
|
296
|
+
entry = {
|
|
297
|
+
repository: ref.repository,
|
|
298
|
+
numbers: /* @__PURE__ */ new Map()
|
|
299
|
+
};
|
|
300
|
+
repositories.set(id, entry);
|
|
301
|
+
}
|
|
302
|
+
if (!entry.numbers.has(ref.number)) entry.numbers.set(ref.number, ref);
|
|
303
|
+
}
|
|
304
|
+
const targets = /* @__PURE__ */ new Map();
|
|
305
|
+
const fields = [];
|
|
306
|
+
for (const [r, { repository, numbers }] of [...repositories.values()].entries()) {
|
|
307
|
+
const pulls = [];
|
|
308
|
+
for (const [p, [number, ref]] of [...numbers].entries()) {
|
|
309
|
+
pulls.push(`p${p}: pullRequest(number: ${number}) { ...ChangeRequestFields }`);
|
|
310
|
+
targets.set(`r${r}.p${p}`, ref);
|
|
311
|
+
}
|
|
312
|
+
const owner = JSON.stringify(repository.owner);
|
|
313
|
+
fields.push(`r${r}: repository(owner: ${owner}, name: ${JSON.stringify(repository.name)}) { ${REPOSITORY_FIELDS} ${pulls.join(" ")} }`);
|
|
314
|
+
}
|
|
315
|
+
return {
|
|
316
|
+
document: `query { ${fields.join(" ")} }\nfragment ChangeRequestFields on PullRequest { ${PULL_REQUEST_FIELDS} }`,
|
|
317
|
+
targets
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Map a snapshot response, including GitHub's partial-error form, into one
|
|
322
|
+
* result per alias target. Path-scoped errors apply to their repository or
|
|
323
|
+
* pull request; errors without a path apply to every unresolved target. A
|
|
324
|
+
* repository without readable merge settings offers no merge. Polling returns
|
|
325
|
+
* the first check page; an explicit detail read can complete its pagination.
|
|
326
|
+
* @param body - parsed JSON printed by `gh api graphql`.
|
|
327
|
+
* @param query - the query that produced the response.
|
|
328
|
+
* @param readChecks - optional detail reader for the same commit; omission returns the first page with its truncation flag.
|
|
329
|
+
* @returns a snapshot with its check truncation flag, or a failure, for every target.
|
|
330
|
+
*/
|
|
331
|
+
async function mapSnapshotResponse(body, query, readChecks) {
|
|
332
|
+
const results = /* @__PURE__ */ new Map();
|
|
333
|
+
const parsed = responseSchema.safeParse(body);
|
|
334
|
+
const repositories = new Set([...query.targets.keys()].map((alias) => alias.split(".")[0]));
|
|
335
|
+
for (const [alias, ref] of query.targets) {
|
|
336
|
+
const key = changeRequestKey(ref);
|
|
337
|
+
if (!parsed.success) {
|
|
338
|
+
results.set(key, {
|
|
339
|
+
code: "unavailable",
|
|
340
|
+
message: "unexpected GitHub response"
|
|
341
|
+
});
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
const [repositoryAlias = "", pullAlias = ""] = alias.split(".");
|
|
345
|
+
const errors = parsed.data.errors ?? [];
|
|
346
|
+
const error = errors.find((entry) => entry.path?.[0] === repositoryAlias && (entry.path.length === 1 || entry.path[1] === pullAlias)) ?? errors.find((entry) => entry.path === void 0 || !repositories.has(String(entry.path[0])));
|
|
347
|
+
const raw = parsed.data.data?.[repositoryAlias]?.[pullAlias];
|
|
348
|
+
const node = pullRequestSchema.safeParse(raw);
|
|
349
|
+
const settings = repositorySchema.safeParse(parsed.data.data?.[repositoryAlias]);
|
|
350
|
+
if (node.success) {
|
|
351
|
+
const rollup = node.data.commits.nodes[0]?.commit.statusCheckRollup;
|
|
352
|
+
if (rollup !== void 0 && rollup !== null) {
|
|
353
|
+
const cursors = /* @__PURE__ */ new Set();
|
|
354
|
+
while (readChecks !== void 0 && rollup.contexts.pageInfo.hasNextPage) {
|
|
355
|
+
const cursor = rollup.contexts.pageInfo.endCursor;
|
|
356
|
+
if (cursor === null || cursors.has(cursor)) {
|
|
357
|
+
results.set(key, {
|
|
358
|
+
code: "unavailable",
|
|
359
|
+
message: "GitHub check pagination did not advance"
|
|
360
|
+
});
|
|
361
|
+
break;
|
|
362
|
+
}
|
|
363
|
+
cursors.add(cursor);
|
|
364
|
+
const next = await readChecks(rollup.id, cursor);
|
|
365
|
+
if (!next.ok) {
|
|
366
|
+
results.set(key, next.failure);
|
|
367
|
+
break;
|
|
368
|
+
}
|
|
369
|
+
rollup.contexts.nodes.push(...next.page.nodes);
|
|
370
|
+
rollup.contexts.pageInfo = next.page.pageInfo;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (!results.has(key)) results.set(key, toSnapshot(ref, node.data, settings.success ? settings.data : void 0));
|
|
374
|
+
} else if (error !== void 0) results.set(key, {
|
|
375
|
+
code: error.type === "NOT_FOUND" ? "not-found" : "unavailable",
|
|
376
|
+
message: error.message
|
|
377
|
+
});
|
|
378
|
+
else if (raw === null || raw === void 0) results.set(key, {
|
|
379
|
+
code: "not-found",
|
|
380
|
+
message: "pull request not found"
|
|
381
|
+
});
|
|
382
|
+
else results.set(key, {
|
|
383
|
+
code: "unavailable",
|
|
384
|
+
message: "unexpected pull request fields"
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
return results;
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Validate a continuation response before adding its checks to the snapshot.
|
|
391
|
+
* @param body - parsed GraphQL response for a rollup node.
|
|
392
|
+
* @returns the complete page or a failure; partial-error pages are not accepted.
|
|
393
|
+
*/
|
|
394
|
+
function mapCheckPageResponse(body) {
|
|
395
|
+
const parsed = z$1.object({
|
|
396
|
+
data: z$1.object({ node: z$1.object({ contexts: checkPageSchema }).nullable() }).nullable().optional(),
|
|
397
|
+
errors: z$1.array(z$1.object({ message: z$1.string() })).optional()
|
|
398
|
+
}).safeParse(body);
|
|
399
|
+
if (parsed.success && !parsed.data.errors?.length && parsed.data.data?.node != null) return {
|
|
400
|
+
ok: true,
|
|
401
|
+
page: parsed.data.data.node.contexts
|
|
402
|
+
};
|
|
403
|
+
return {
|
|
404
|
+
ok: false,
|
|
405
|
+
failure: {
|
|
406
|
+
code: "unavailable",
|
|
407
|
+
message: parsed.success ? parsed.data.errors?.[0]?.message ?? "GitHub check page is unavailable" : "unexpected GitHub check page"
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Map a head-branch lookup of {@link HEAD_QUERY}, which selects open pull requests, into change requests.
|
|
413
|
+
* @param body - parsed JSON printed by `gh api graphql`.
|
|
414
|
+
* @param repository - repository that was queried.
|
|
415
|
+
* @param branch - head branch that was queried.
|
|
416
|
+
* @returns open non-fork change requests for `branch`, or none when it is the default branch.
|
|
417
|
+
* @throws when the response is malformed or the repository is not visible.
|
|
418
|
+
*/
|
|
419
|
+
function mapHeadResponse(body, repository, branch) {
|
|
420
|
+
const parsed = headSchema.safeParse(body);
|
|
421
|
+
if (!parsed.success) throw new Error("forge-github: unexpected GitHub response to the head branch lookup");
|
|
422
|
+
const found = parsed.data.data.repository;
|
|
423
|
+
if (found === null) throw new Error(`forge-github: repository ${repository.owner}/${repository.name} is not visible`);
|
|
424
|
+
if (found.defaultBranchRef?.name === branch) return [];
|
|
425
|
+
return found.pullRequests.nodes.filter((node) => !node.isCrossRepository).map((node) => ({
|
|
426
|
+
repository,
|
|
427
|
+
number: node.number
|
|
428
|
+
}));
|
|
429
|
+
}
|
|
430
|
+
function toSnapshot(ref, node, settings) {
|
|
431
|
+
const rollup = node.commits.nodes[0]?.commit.statusCheckRollup ?? null;
|
|
432
|
+
const latest = /* @__PURE__ */ new Map();
|
|
433
|
+
let unknownContext = false;
|
|
434
|
+
const retain = (key, order, check) => {
|
|
435
|
+
const previous = latest.get(key);
|
|
436
|
+
if (previous === void 0 || order > previous.order) latest.set(key, {
|
|
437
|
+
order,
|
|
438
|
+
check
|
|
439
|
+
});
|
|
440
|
+
};
|
|
441
|
+
for (const context of rollup?.contexts.nodes ?? []) {
|
|
442
|
+
const run = checkRunSchema.safeParse(context);
|
|
443
|
+
if (run.success) {
|
|
444
|
+
const suite = run.data.checkSuite;
|
|
445
|
+
const workflow = suite?.workflowRun;
|
|
446
|
+
retain(run.data.databaseId === null ? JSON.stringify(["unranked-run", run.data.id]) : JSON.stringify([
|
|
447
|
+
"run",
|
|
448
|
+
run.data.name,
|
|
449
|
+
suite?.app?.id,
|
|
450
|
+
workflow?.workflow.id,
|
|
451
|
+
workflow?.event
|
|
452
|
+
]), run.data.databaseId ?? 0, {
|
|
453
|
+
name: run.data.name,
|
|
454
|
+
state: checkRunState(run.data.status, run.data.conclusion),
|
|
455
|
+
url: run.data.detailsUrl,
|
|
456
|
+
workflow: run.data.checkSuite?.workflowRun?.workflow.name ?? null,
|
|
457
|
+
startedAt: run.data.startedAt,
|
|
458
|
+
completedAt: run.data.completedAt
|
|
459
|
+
});
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
const status = statusContextSchema.safeParse(context);
|
|
463
|
+
if (status.success) retain(JSON.stringify(["status", status.data.context]), Date.parse(status.data.createdAt), {
|
|
464
|
+
name: status.data.context,
|
|
465
|
+
state: statusContextState(status.data.state),
|
|
466
|
+
url: status.data.targetUrl,
|
|
467
|
+
workflow: null,
|
|
468
|
+
startedAt: null,
|
|
469
|
+
completedAt: null
|
|
470
|
+
});
|
|
471
|
+
else if (typeof context === "object" && context !== null && "__typename" in context && (context.__typename === "CheckRun" || context.__typename === "StatusContext")) return {
|
|
472
|
+
code: "unavailable",
|
|
473
|
+
message: "unexpected GitHub check fields"
|
|
474
|
+
};
|
|
475
|
+
else unknownContext = true;
|
|
476
|
+
}
|
|
477
|
+
const checks = [...latest.values()].map((value) => value.check);
|
|
478
|
+
const summary = rollup?.contexts.pageInfo.hasNextPage || unknownContext || checks.length === 0 ? checksRollup(rollup?.state) : checks.some((check) => check.state === "failure" || check.state === "cancelled") ? "failure" : checks.some((check) => check.state === "pending") ? "pending" : "success";
|
|
479
|
+
return {
|
|
480
|
+
ref,
|
|
481
|
+
url: node.url,
|
|
482
|
+
title: node.title,
|
|
483
|
+
state: changeRequestState(node.state),
|
|
484
|
+
draft: node.isDraft,
|
|
485
|
+
author: node.author?.login ?? null,
|
|
486
|
+
headBranch: node.headRefName,
|
|
487
|
+
headSha: node.headRefOid,
|
|
488
|
+
baseBranch: node.baseRefName,
|
|
489
|
+
additions: node.additions,
|
|
490
|
+
deletions: node.deletions,
|
|
491
|
+
mergeability: mergeability(node.mergeable),
|
|
492
|
+
mergeReady: settings !== void 0 && MERGERS.has(settings.viewerPermission ?? "") && node.state === "OPEN" && !node.isDraft && MERGEABLE_NOW.has(node.mergeStateStatus),
|
|
493
|
+
mergeMethods: settings === void 0 ? [] : mergeMethods(settings),
|
|
494
|
+
reviewDecision: reviewDecision(node.reviewDecision),
|
|
495
|
+
checks,
|
|
496
|
+
checksRollup: summary,
|
|
497
|
+
checksTruncated: rollup?.contexts.pageInfo.hasNextPage ?? false,
|
|
498
|
+
unresolvedThreads: node.reviewThreads.nodes.filter((thread) => !thread.isResolved).length,
|
|
499
|
+
updatedAt: node.updatedAt,
|
|
500
|
+
closedAt: node.closedAt
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
/** The methods the repository allows, the viewer's default first. */
|
|
504
|
+
function mergeMethods(settings) {
|
|
505
|
+
const allowed = METHODS.filter((entry) => settings[entry.allowed]);
|
|
506
|
+
const usual = allowed.filter((entry) => entry.name === settings.viewerDefaultMergeMethod);
|
|
507
|
+
return [...usual, ...allowed.filter((entry) => !usual.includes(entry))].map((entry) => entry.method);
|
|
508
|
+
}
|
|
509
|
+
function changeRequestState(state) {
|
|
510
|
+
switch (state) {
|
|
511
|
+
case "OPEN": return "open";
|
|
512
|
+
case "CLOSED": return "closed";
|
|
513
|
+
case "MERGED": return "merged";
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
/** GitHub enum values outside the documented set read as the most conservative state. */
|
|
517
|
+
function checkRunState(status, conclusion) {
|
|
518
|
+
if (status !== "COMPLETED") return "pending";
|
|
519
|
+
switch (conclusion) {
|
|
520
|
+
case "SUCCESS": return "success";
|
|
521
|
+
case "ACTION_REQUIRED":
|
|
522
|
+
case "FAILURE":
|
|
523
|
+
case "TIMED_OUT":
|
|
524
|
+
case "STARTUP_FAILURE": return "failure";
|
|
525
|
+
case "CANCELLED": return "cancelled";
|
|
526
|
+
case "SKIPPED": return "skipped";
|
|
527
|
+
case "NEUTRAL": return "neutral";
|
|
528
|
+
default: return "pending";
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
function statusContextState(state) {
|
|
532
|
+
switch (state) {
|
|
533
|
+
case "SUCCESS": return "success";
|
|
534
|
+
case "FAILURE":
|
|
535
|
+
case "ERROR": return "failure";
|
|
536
|
+
default: return "pending";
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
function checksRollup(state) {
|
|
540
|
+
switch (state) {
|
|
541
|
+
case void 0: return "none";
|
|
542
|
+
case "SUCCESS": return "success";
|
|
543
|
+
case "FAILURE":
|
|
544
|
+
case "ERROR": return "failure";
|
|
545
|
+
default: return "pending";
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
function mergeability(value) {
|
|
549
|
+
switch (value) {
|
|
550
|
+
case "MERGEABLE": return "mergeable";
|
|
551
|
+
case "CONFLICTING": return "conflicting";
|
|
552
|
+
default: return "unknown";
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
function reviewDecision(value) {
|
|
556
|
+
switch (value) {
|
|
557
|
+
case "APPROVED": return "approved";
|
|
558
|
+
case "CHANGES_REQUESTED": return "changes-requested";
|
|
559
|
+
case "REVIEW_REQUIRED": return "review-required";
|
|
560
|
+
default: return "none";
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
//#endregion
|
|
564
|
+
//#region lib/types/review.js
|
|
565
|
+
/** GitHub review writes with commit checks and explicit treatment of uncertain outcomes. */
|
|
566
|
+
const pull = z$1.object({
|
|
567
|
+
head: z$1.object({ sha: z$1.string() }),
|
|
568
|
+
state: z$1.string()
|
|
569
|
+
});
|
|
570
|
+
const receipt = z$1.object({ html_url: z$1.url() });
|
|
571
|
+
const EVENTS = {
|
|
572
|
+
comment: "COMMENT",
|
|
573
|
+
approve: "APPROVE",
|
|
574
|
+
"request-changes": "REQUEST_CHANGES"
|
|
575
|
+
};
|
|
576
|
+
function inline(comment) {
|
|
577
|
+
const side = comment.side === "L" ? "LEFT" : "RIGHT";
|
|
578
|
+
return {
|
|
579
|
+
path: comment.path,
|
|
580
|
+
side,
|
|
581
|
+
line: comment.endLine,
|
|
582
|
+
body: comment.body,
|
|
583
|
+
...comment.startLine === comment.endLine ? {} : {
|
|
584
|
+
start_line: comment.startLine,
|
|
585
|
+
start_side: side
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
function failed(output, write) {
|
|
590
|
+
const known = /\(HTTP (?:400|401|403|404|409|422)\)/.test(output.stderr);
|
|
591
|
+
return {
|
|
592
|
+
ok: false,
|
|
593
|
+
code: write && !known ? "unknown" : "failed",
|
|
594
|
+
message: output.stderr.trim() || output.stdout.trim() || "GitHub request failed"
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Send one review mutation using JSON on stdin, never shell or argument interpolation.
|
|
599
|
+
* @param gh - bounded, cancellable GitHub CLI runner.
|
|
600
|
+
* @param ref - validated pull request address.
|
|
601
|
+
* @param request - frozen commit and comment ranges.
|
|
602
|
+
* @param signal - cancellation of preflight and mutation.
|
|
603
|
+
* @returns a confirmed receipt, refusal, stale commit, or uncertain outcome; never retries a write.
|
|
604
|
+
*/
|
|
605
|
+
async function submitGitHubReview(gh, ref, request, signal) {
|
|
606
|
+
const { host, owner, name } = checkedRepository(ref);
|
|
607
|
+
const endpoint = `repos/${owner}/${name}/pulls/${ref.number}`;
|
|
608
|
+
let writing = false;
|
|
609
|
+
try {
|
|
610
|
+
const read = await gh([
|
|
611
|
+
"api",
|
|
612
|
+
"--hostname",
|
|
613
|
+
host,
|
|
614
|
+
endpoint
|
|
615
|
+
], signal);
|
|
616
|
+
if (read.exitCode !== 0) return failed(read, false);
|
|
617
|
+
const current = pull.parse(JSON.parse(read.stdout));
|
|
618
|
+
if (current.head.sha !== request.headSha) return {
|
|
619
|
+
ok: false,
|
|
620
|
+
code: "stale",
|
|
621
|
+
message: "The pull request head has changed"
|
|
622
|
+
};
|
|
623
|
+
if (current.state !== "open") return {
|
|
624
|
+
ok: false,
|
|
625
|
+
code: "failed",
|
|
626
|
+
message: "The pull request is not open"
|
|
627
|
+
};
|
|
628
|
+
signal.throwIfAborted();
|
|
629
|
+
const body = request.kind === "comment" ? {
|
|
630
|
+
commit_id: request.headSha,
|
|
631
|
+
...inline(request.comment)
|
|
632
|
+
} : {
|
|
633
|
+
commit_id: request.headSha,
|
|
634
|
+
event: EVENTS[request.event],
|
|
635
|
+
body: request.body,
|
|
636
|
+
comments: request.comments.map(inline)
|
|
637
|
+
};
|
|
638
|
+
writing = true;
|
|
639
|
+
const output = await gh([
|
|
640
|
+
"api",
|
|
641
|
+
"--hostname",
|
|
642
|
+
host,
|
|
643
|
+
"--method",
|
|
644
|
+
"POST",
|
|
645
|
+
`${endpoint}/${request.kind === "comment" ? "comments" : "reviews"}`,
|
|
646
|
+
"--input",
|
|
647
|
+
"-"
|
|
648
|
+
], signal, JSON.stringify(body));
|
|
649
|
+
if (output.exitCode !== 0) return failed(output, true);
|
|
650
|
+
const result = receipt.parse(JSON.parse(output.stdout));
|
|
651
|
+
const url = new URL(result.html_url);
|
|
652
|
+
if (url.protocol !== "https:" || url.host !== host) throw new Error("GitHub returned an invalid review URL");
|
|
653
|
+
return {
|
|
654
|
+
ok: true,
|
|
655
|
+
url: result.html_url
|
|
656
|
+
};
|
|
657
|
+
} catch (error) {
|
|
658
|
+
if (!writing && signal.aborted) throw signal.reason;
|
|
659
|
+
return {
|
|
660
|
+
ok: false,
|
|
661
|
+
code: writing && !(error instanceof GhUnavailableError) ? "unknown" : "failed",
|
|
662
|
+
message: error instanceof Error ? error.message : String(error)
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
//#endregion
|
|
667
|
+
//#region lib/types/provider.js
|
|
668
|
+
/** GitHub implementation of the forge provider contract. */
|
|
669
|
+
const AUTHENTICATION = /gh auth login|authentication|bad credentials|HTTP 401/i;
|
|
670
|
+
/** Status code `gh api` appends to the message of a failed request. */
|
|
671
|
+
const HTTP_STATUS = /\(HTTP (\d{3})\)/;
|
|
672
|
+
/**
|
|
673
|
+
* GitHub's error code for an answer over its size limits, such as a diff over
|
|
674
|
+
* 300 files: `gh pr diff` prints it after the field, and `gh api` returns it in the JSON error body.
|
|
675
|
+
*/
|
|
676
|
+
const TOO_LARGE = /\btoo_large\b/;
|
|
677
|
+
/** A full SHA-1 or SHA-256 object name. */
|
|
678
|
+
const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
|
|
679
|
+
/** Reads GitHub and GitHub Enterprise pull requests through a `gh` runner. */
|
|
680
|
+
var GitHubProvider = class {
|
|
681
|
+
gh;
|
|
682
|
+
maxOutputBytes;
|
|
683
|
+
forge = "github";
|
|
684
|
+
hosts;
|
|
685
|
+
async submitReview(ref, request, signal) {
|
|
686
|
+
const failure = this.hostFailure(ref.repository.host);
|
|
687
|
+
if (failure !== void 0) return {
|
|
688
|
+
ok: false,
|
|
689
|
+
code: "failed",
|
|
690
|
+
message: failure.message
|
|
691
|
+
};
|
|
692
|
+
return await submitGitHubReview(this.gh, ref, request, signal);
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* @param gh - runner that executes `gh` on the host.
|
|
696
|
+
* @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts.
|
|
697
|
+
* @param maxOutputBytes - maximum combined JSON bytes retained by an explicit check read.
|
|
698
|
+
*/
|
|
699
|
+
constructor(gh, hosts, maxOutputBytes) {
|
|
700
|
+
this.gh = gh;
|
|
701
|
+
this.maxOutputBytes = maxOutputBytes;
|
|
702
|
+
this.hosts = new Set(hosts.map((host) => host.toLowerCase()));
|
|
703
|
+
}
|
|
704
|
+
repositoryFromRemote(url) {
|
|
705
|
+
const location = parseRemoteUrl(url);
|
|
706
|
+
if (location === void 0 || !this.hosts.has(location.host)) return void 0;
|
|
707
|
+
return {
|
|
708
|
+
forge: this.forge,
|
|
709
|
+
...location
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
changeRequestFromUrl(url) {
|
|
713
|
+
const parsed = parsePullRequestUrl(url);
|
|
714
|
+
if (parsed === void 0 || !this.hosts.has(parsed.host)) return void 0;
|
|
715
|
+
return {
|
|
716
|
+
repository: {
|
|
717
|
+
forge: this.forge,
|
|
718
|
+
host: parsed.host,
|
|
719
|
+
owner: parsed.owner,
|
|
720
|
+
name: parsed.name
|
|
721
|
+
},
|
|
722
|
+
number: parsed.number
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
changeRequestUrl(ref) {
|
|
726
|
+
const { host, owner, name } = ref.repository;
|
|
727
|
+
return `https://${host}/${owner}/${name}/pull/${ref.number}`;
|
|
728
|
+
}
|
|
729
|
+
async fetch(refs, signal) {
|
|
730
|
+
const byHost = /* @__PURE__ */ new Map();
|
|
731
|
+
const results = /* @__PURE__ */ new Map();
|
|
732
|
+
for (const ref of refs) {
|
|
733
|
+
const failure = this.hostFailure(ref.repository.host);
|
|
734
|
+
if (failure !== void 0) {
|
|
735
|
+
results.set(changeRequestKey(ref), failure);
|
|
736
|
+
continue;
|
|
737
|
+
}
|
|
738
|
+
const group = byHost.get(ref.repository.host);
|
|
739
|
+
if (group === void 0) byHost.set(ref.repository.host, [ref]);
|
|
740
|
+
else group.push(ref);
|
|
741
|
+
}
|
|
742
|
+
for (const [host, group] of byHost) for (const [key, result] of await this.fetchHost(host, group, signal)) results.set(key, result);
|
|
743
|
+
return results;
|
|
744
|
+
}
|
|
745
|
+
async fetchChecks(ref, signal) {
|
|
746
|
+
const failure = this.hostFailure(ref.repository.host);
|
|
747
|
+
if (failure !== void 0) return failure;
|
|
748
|
+
try {
|
|
749
|
+
return (await this.fetchHost(ref.repository.host, [ref], signal, true)).get(changeRequestKey(ref));
|
|
750
|
+
} catch (error) {
|
|
751
|
+
if (signal.aborted) throw signal.reason;
|
|
752
|
+
if (error instanceof GhUnavailableError || error instanceof GhTimeoutError || error instanceof GhOutputLimitError) return {
|
|
753
|
+
code: error instanceof GhOutputLimitError ? "too-large" : "unavailable",
|
|
754
|
+
message: error.message
|
|
755
|
+
};
|
|
756
|
+
throw error;
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
async findByHead(repository, branch, signal) {
|
|
760
|
+
const failure = this.hostFailure(repository.host);
|
|
761
|
+
if (failure !== void 0) throw new Error(failure.message);
|
|
762
|
+
const output = await this.gh([
|
|
763
|
+
"api",
|
|
764
|
+
"graphql",
|
|
765
|
+
"--hostname",
|
|
766
|
+
repository.host,
|
|
767
|
+
"-f",
|
|
768
|
+
`query=${HEAD_QUERY}`,
|
|
769
|
+
"-f",
|
|
770
|
+
`owner=${repository.owner}`,
|
|
771
|
+
"-f",
|
|
772
|
+
`name=${repository.name}`,
|
|
773
|
+
"-f",
|
|
774
|
+
`branch=${branch}`
|
|
775
|
+
], signal);
|
|
776
|
+
const body = parseJson(output.stdout);
|
|
777
|
+
if (!hasGraphqlFields(body)) throw new Error(`forge-github: head branch lookup failed: ${responseFailure(output, body).message}`);
|
|
778
|
+
return mapHeadResponse(body, repository, branch);
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Mark a draft pull request ready for review with `gh pr ready`; one that
|
|
782
|
+
* is already ready stays ready.
|
|
783
|
+
*/
|
|
784
|
+
async markReady(ref, signal) {
|
|
785
|
+
const { host, owner, name } = checkedRepository(ref);
|
|
786
|
+
const failure = this.hostFailure(host);
|
|
787
|
+
if (failure !== void 0) return {
|
|
788
|
+
code: "failed",
|
|
789
|
+
message: failure.message
|
|
790
|
+
};
|
|
791
|
+
return await this.act([
|
|
792
|
+
"pr",
|
|
793
|
+
"ready",
|
|
794
|
+
String(ref.number),
|
|
795
|
+
"--repo",
|
|
796
|
+
`${host}/${owner}/${name}`
|
|
797
|
+
], signal);
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Merge a pull request through the REST merge endpoint with the expected
|
|
801
|
+
* head commit, so GitHub refuses with 409 once new commits arrived. Unlike
|
|
802
|
+
* `gh pr merge`, it never enables auto-merge, never joins a merge queue, and
|
|
803
|
+
* never deletes the head branch.
|
|
804
|
+
*/
|
|
805
|
+
async merge(ref, request, signal) {
|
|
806
|
+
const { host, owner, name } = checkedRepository(ref);
|
|
807
|
+
const failure = this.hostFailure(host);
|
|
808
|
+
if (failure !== void 0) return {
|
|
809
|
+
code: "failed",
|
|
810
|
+
message: failure.message
|
|
811
|
+
};
|
|
812
|
+
if (!COMMIT.test(request.headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(request.headSha)}`);
|
|
813
|
+
return await this.act([
|
|
814
|
+
"api",
|
|
815
|
+
"--hostname",
|
|
816
|
+
host,
|
|
817
|
+
"--method",
|
|
818
|
+
"PUT",
|
|
819
|
+
`repos/${owner}/${name}/pulls/${ref.number}/merge`,
|
|
820
|
+
"-f",
|
|
821
|
+
`merge_method=${request.method}`,
|
|
822
|
+
"-f",
|
|
823
|
+
`sha=${request.headSha}`
|
|
824
|
+
], signal);
|
|
825
|
+
}
|
|
826
|
+
/** Read the pull request's diff with `gh pr diff`, which GitHub computes against the merge base. */
|
|
827
|
+
async diff(ref, signal) {
|
|
828
|
+
const { host, owner, name } = checkedRepository(ref);
|
|
829
|
+
const failure = this.hostFailure(host);
|
|
830
|
+
if (failure !== void 0) return failure;
|
|
831
|
+
return await this.read([
|
|
832
|
+
"pr",
|
|
833
|
+
"diff",
|
|
834
|
+
String(ref.number),
|
|
835
|
+
"--repo",
|
|
836
|
+
`${host}/${owner}/${name}`,
|
|
837
|
+
"--color",
|
|
838
|
+
"never"
|
|
839
|
+
], signal);
|
|
840
|
+
}
|
|
841
|
+
/** Read one file at a commit through the contents API in its raw form. */
|
|
842
|
+
async fileText(ref, commit, path, signal) {
|
|
843
|
+
const { host, owner, name } = checkedRepository(ref);
|
|
844
|
+
const failure = this.hostFailure(host);
|
|
845
|
+
if (failure !== void 0) return failure;
|
|
846
|
+
if (!COMMIT.test(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`);
|
|
847
|
+
return await this.read([
|
|
848
|
+
"api",
|
|
849
|
+
"--hostname",
|
|
850
|
+
host,
|
|
851
|
+
"-H",
|
|
852
|
+
"Accept: application/vnd.github.raw+json",
|
|
853
|
+
`repos/${owner}/${name}/contents/${encodedPath(path)}?ref=${commit}`
|
|
854
|
+
], signal);
|
|
855
|
+
}
|
|
856
|
+
fileUrl(ref, commit, path) {
|
|
857
|
+
const { host, owner, name } = ref.repository;
|
|
858
|
+
return `https://${host}/${owner}/${name}/blob/${commit}/${encodedPath(path)}`;
|
|
859
|
+
}
|
|
860
|
+
async readiness(host, signal) {
|
|
861
|
+
const failure = this.hostFailure(host);
|
|
862
|
+
if (failure !== void 0) return {
|
|
863
|
+
state: "unavailable",
|
|
864
|
+
message: failure.message
|
|
865
|
+
};
|
|
866
|
+
try {
|
|
867
|
+
const output = await this.gh([
|
|
868
|
+
"auth",
|
|
869
|
+
"status",
|
|
870
|
+
"--hostname",
|
|
871
|
+
host
|
|
872
|
+
], signal);
|
|
873
|
+
if (output.exitCode === 0) return {
|
|
874
|
+
state: "ready",
|
|
875
|
+
message: null
|
|
876
|
+
};
|
|
877
|
+
return {
|
|
878
|
+
state: "unauthenticated",
|
|
879
|
+
message: firstLine(output.stderr) ?? firstLine(output.stdout) ?? `gh is not signed in to ${host}`
|
|
880
|
+
};
|
|
881
|
+
} catch (error) {
|
|
882
|
+
if (error instanceof GhUnavailableError) return {
|
|
883
|
+
state: "unavailable",
|
|
884
|
+
message: error.message
|
|
885
|
+
};
|
|
886
|
+
throw error;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Run one reading `gh` command, returning its output. A refusal, a `gh` that
|
|
891
|
+
* cannot start, output over `maxOutputBytes`, and a run past `timeoutMs` become failures.
|
|
892
|
+
*/
|
|
893
|
+
async read(args, signal) {
|
|
894
|
+
let output;
|
|
895
|
+
try {
|
|
896
|
+
output = await this.attempt(args, signal);
|
|
897
|
+
} catch (error) {
|
|
898
|
+
if (error instanceof GhOutputLimitError) return {
|
|
899
|
+
code: "too-large",
|
|
900
|
+
message: error.message
|
|
901
|
+
};
|
|
902
|
+
if (error instanceof GhTimeoutError) return {
|
|
903
|
+
code: "unavailable",
|
|
904
|
+
message: error.message
|
|
905
|
+
};
|
|
906
|
+
throw error;
|
|
907
|
+
}
|
|
908
|
+
if (output instanceof GhUnavailableError) return {
|
|
909
|
+
code: "unavailable",
|
|
910
|
+
message: output.message
|
|
911
|
+
};
|
|
912
|
+
if (output.exitCode === 0) return output.stdout;
|
|
913
|
+
const { message, status } = refusal(output);
|
|
914
|
+
if (AUTHENTICATION.test(output.stderr)) return {
|
|
915
|
+
code: "unauthenticated",
|
|
916
|
+
message
|
|
917
|
+
};
|
|
918
|
+
if (TOO_LARGE.test(output.stderr) || TOO_LARGE.test(output.stdout)) return {
|
|
919
|
+
code: "too-large",
|
|
920
|
+
message
|
|
921
|
+
};
|
|
922
|
+
return {
|
|
923
|
+
code: status === "404" || /could not resolve to a pullrequest/i.test(output.stderr) ? "not-found" : "unavailable",
|
|
924
|
+
message
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
/** Run one changing `gh` command; a refusal or a `gh` that cannot start becomes a failure. */
|
|
928
|
+
async act(args, signal) {
|
|
929
|
+
const output = await this.attempt(args, signal);
|
|
930
|
+
if (output instanceof GhUnavailableError) return {
|
|
931
|
+
code: "failed",
|
|
932
|
+
message: output.message
|
|
933
|
+
};
|
|
934
|
+
if (output.exitCode === 0) return void 0;
|
|
935
|
+
const { message, status } = refusal(output);
|
|
936
|
+
if (status === "409") return {
|
|
937
|
+
code: "stale",
|
|
938
|
+
message
|
|
939
|
+
};
|
|
940
|
+
if (AUTHENTICATION.test(output.stderr)) return {
|
|
941
|
+
code: "unauthenticated",
|
|
942
|
+
message
|
|
943
|
+
};
|
|
944
|
+
return {
|
|
945
|
+
code: "failed",
|
|
946
|
+
message
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
/** Run one `gh` command; a `gh` that cannot start resolves to its error, and every other rejection passes on. */
|
|
950
|
+
async attempt(args, signal) {
|
|
951
|
+
try {
|
|
952
|
+
return await this.gh(args, signal);
|
|
953
|
+
} catch (error) {
|
|
954
|
+
if (error instanceof GhUnavailableError) return error;
|
|
955
|
+
throw error;
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
hostFailure(host) {
|
|
959
|
+
return this.hosts.has(host.toLowerCase()) ? void 0 : {
|
|
960
|
+
code: "unavailable",
|
|
961
|
+
message: `forge-github: host ${JSON.stringify(host)} is not configured`
|
|
962
|
+
};
|
|
963
|
+
}
|
|
964
|
+
async fetchHost(host, refs, signal, completeChecks = false) {
|
|
965
|
+
const query = snapshotQuery(refs);
|
|
966
|
+
const output = await this.gh([
|
|
967
|
+
"api",
|
|
968
|
+
"graphql",
|
|
969
|
+
"--hostname",
|
|
970
|
+
host,
|
|
971
|
+
"-f",
|
|
972
|
+
`query=${query.document}`
|
|
973
|
+
], signal);
|
|
974
|
+
const body = parseJson(output.stdout);
|
|
975
|
+
if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query);
|
|
976
|
+
let bytes = Buffer.byteLength(output.stdout);
|
|
977
|
+
const tooLarge = {
|
|
978
|
+
code: "too-large",
|
|
979
|
+
message: "GitHub check details exceed the output size limit"
|
|
980
|
+
};
|
|
981
|
+
if (bytes > this.maxOutputBytes) return new Map([...query.targets.values()].map((ref) => [changeRequestKey(ref), tooLarge]));
|
|
982
|
+
if (hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, async (id, cursor) => {
|
|
983
|
+
signal.throwIfAborted();
|
|
984
|
+
let page;
|
|
985
|
+
try {
|
|
986
|
+
page = await this.gh([
|
|
987
|
+
"api",
|
|
988
|
+
"graphql",
|
|
989
|
+
"--hostname",
|
|
990
|
+
host,
|
|
991
|
+
"-f",
|
|
992
|
+
`query=${CHECKS_QUERY}`,
|
|
993
|
+
"-f",
|
|
994
|
+
`id=${id}`,
|
|
995
|
+
"-f",
|
|
996
|
+
`cursor=${cursor}`
|
|
997
|
+
], signal);
|
|
998
|
+
} catch (error) {
|
|
999
|
+
if (signal.aborted) throw signal.reason;
|
|
1000
|
+
if (error instanceof GhUnavailableError || error instanceof GhTimeoutError || error instanceof GhOutputLimitError) return {
|
|
1001
|
+
ok: false,
|
|
1002
|
+
failure: {
|
|
1003
|
+
code: error instanceof GhOutputLimitError ? "too-large" : "unavailable",
|
|
1004
|
+
message: error.message
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
throw error;
|
|
1008
|
+
}
|
|
1009
|
+
bytes += Buffer.byteLength(page.stdout);
|
|
1010
|
+
if (bytes > this.maxOutputBytes) return {
|
|
1011
|
+
ok: false,
|
|
1012
|
+
failure: tooLarge
|
|
1013
|
+
};
|
|
1014
|
+
const value = parseJson(page.stdout);
|
|
1015
|
+
return hasGraphqlFields(value) ? mapCheckPageResponse(value) : {
|
|
1016
|
+
ok: false,
|
|
1017
|
+
failure: responseFailure(page, value)
|
|
1018
|
+
};
|
|
1019
|
+
});
|
|
1020
|
+
const failure = responseFailure(output, body);
|
|
1021
|
+
return new Map([...query.targets.values()].map((ref) => [changeRequestKey(ref), failure]));
|
|
1022
|
+
}
|
|
1023
|
+
};
|
|
1024
|
+
/** Why `gh` refused: GitHub's message, else its first diagnostic line, with the HTTP status it names. */
|
|
1025
|
+
function refusal(output) {
|
|
1026
|
+
return {
|
|
1027
|
+
message: hostMessage(output.stdout) ?? firstLine(output.stderr) ?? `gh exited with ${output.exitCode}`,
|
|
1028
|
+
status: HTTP_STATUS.exec(output.stderr)?.[1]
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
1031
|
+
/** The `message` of the JSON error body `gh api` prints for a failed request. */
|
|
1032
|
+
function hostMessage(stdout) {
|
|
1033
|
+
const body = parseJson(stdout);
|
|
1034
|
+
if (typeof body !== "object" || body === null || !("message" in body) || typeof body.message !== "string") return void 0;
|
|
1035
|
+
return body.message.trim().length > 0 ? body.message : void 0;
|
|
1036
|
+
}
|
|
1037
|
+
/** A repository path with each segment percent-encoded, for an API path or a web URL. */
|
|
1038
|
+
function encodedPath(path) {
|
|
1039
|
+
return path.split("/").map((segment) => encodeURIComponent(segment)).join("/");
|
|
1040
|
+
}
|
|
1041
|
+
function responseFailure(output, body) {
|
|
1042
|
+
const detail = typeof body === "object" && body !== null && "message" in body && typeof body.message === "string" ? firstLine(body.message) : void 0;
|
|
1043
|
+
const message = firstLine(output.stderr) ?? detail ?? (output.exitCode === 0 ? "unexpected GitHub response" : `gh exited with ${output.exitCode}`);
|
|
1044
|
+
return {
|
|
1045
|
+
code: AUTHENTICATION.test(message) ? "unauthenticated" : "unavailable",
|
|
1046
|
+
message
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
function parseJson(text) {
|
|
1050
|
+
let value;
|
|
1051
|
+
try {
|
|
1052
|
+
value = JSON.parse(text);
|
|
1053
|
+
} catch (error) {
|
|
1054
|
+
return;
|
|
1055
|
+
}
|
|
1056
|
+
return value;
|
|
1057
|
+
}
|
|
1058
|
+
function firstLine(text) {
|
|
1059
|
+
return text.split("\n").map((line) => line.trim()).find((line) => line.length > 0);
|
|
1060
|
+
}
|
|
1061
|
+
//#endregion
|
|
1062
|
+
//#region lib/types/index.js
|
|
1063
|
+
/** Registers the GitHub provider of `ctx.forge`, which reads pull requests through the GitHub CLI on the host. */
|
|
1064
|
+
const name = "forge-github";
|
|
1065
|
+
const inject = ["forge"];
|
|
1066
|
+
const Config = z.object({
|
|
1067
|
+
ghCommand: z.string().default("gh"),
|
|
1068
|
+
hosts: z.array(z.string()).default(["github.com"]),
|
|
1069
|
+
timeoutMs: z.number().default(3e4),
|
|
1070
|
+
maxOutputBytes: z.number().default(8388608)
|
|
1071
|
+
});
|
|
1072
|
+
const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i;
|
|
1073
|
+
function apply(ctx, config) {
|
|
1074
|
+
const resolved = config;
|
|
1075
|
+
if (resolved.ghCommand.trim().length === 0) throw new Error("forge-github: ghCommand must not be empty");
|
|
1076
|
+
if (resolved.hosts.length === 0) throw new Error("forge-github: hosts must list at least one host");
|
|
1077
|
+
for (const host of resolved.hosts) if (!HOST.test(host)) throw new Error(`forge-github: invalid host ${JSON.stringify(host)}`);
|
|
1078
|
+
if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0 || resolved.timeoutMs > MAX_TIMER_DELAY_MS) throw new Error(`forge-github: timeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`);
|
|
1079
|
+
if (!Number.isSafeInteger(resolved.maxOutputBytes) || resolved.maxOutputBytes <= 0) throw new Error("forge-github: maxOutputBytes must be a positive safe integer");
|
|
1080
|
+
ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved.maxOutputBytes));
|
|
1081
|
+
}
|
|
1082
|
+
//#endregion
|
|
1083
|
+
export { Config, apply, inject, name };
|