@sentry/junior-github 0.302.0 → 0.304.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/dist/events-DGd7UVVs.js +2452 -0
- package/dist/index.d.ts +71 -3
- package/dist/index.js +7193 -8134
- package/dist/testing.d.ts +51 -1
- package/dist/testing.js +1 -6
- package/package.json +10 -13
- package/dist/account-links.d.ts +0 -8
- package/dist/annotations.d.ts +0 -33
- package/dist/chunk-6SOJ5TN6.js +0 -2618
- package/dist/clone-command.d.ts +0 -7
- package/dist/configured-repository.d.ts +0 -10
- package/dist/conversation-title-context.d.ts +0 -20
- package/dist/credential-support.d.ts +0 -107
- package/dist/db/database.d.ts +0 -5
- package/dist/db/schema.d.ts +0 -1412
- package/dist/default-branch.d.ts +0 -15
- package/dist/draft-readiness.d.ts +0 -31
- package/dist/egress-policy.d.ts +0 -25
- package/dist/events/comment.d.ts +0 -14
- package/dist/events/declarations.d.ts +0 -18
- package/dist/events/deployment.d.ts +0 -38
- package/dist/events/issue.d.ts +0 -42
- package/dist/events/pull-request.d.ts +0 -75
- package/dist/events/release.d.ts +0 -42
- package/dist/events/repository.d.ts +0 -23
- package/dist/events/resource-url.d.ts +0 -5
- package/dist/events/scope.d.ts +0 -13
- package/dist/git-config.d.ts +0 -52
- package/dist/github-status.d.ts +0 -16
- package/dist/graphql-documents.d.ts +0 -44
- package/dist/hooks-path-command.d.ts +0 -5
- package/dist/images.d.ts +0 -8
- package/dist/issue-outcomes/store.d.ts +0 -42
- package/dist/merge-conflict-checks/heartbeat.d.ts +0 -31
- package/dist/merge-conflict-checks/policy.d.ts +0 -74
- package/dist/merge-conflict-checks/store.d.ts +0 -44
- package/dist/merge-conflict-checks/webhooks.d.ts +0 -23
- package/dist/object-facts.d.ts +0 -29
- package/dist/permissions.d.ts +0 -6
- package/dist/plugin.d.ts +0 -45
- package/dist/pull-request-outcomes/apply.d.ts +0 -22
- package/dist/pull-request-outcomes/commit-composition.d.ts +0 -6
- package/dist/pull-request-outcomes/reconcile.d.ts +0 -42
- package/dist/pull-request-outcomes/store.d.ts +0 -120
- package/dist/pull-request-requesters/draft-reviewers.d.ts +0 -15
- package/dist/pull-request-requesters/store.d.ts +0 -41
- package/dist/pull-request-review-policy.d.ts +0 -6
- package/dist/receive-pack-policy.d.ts +0 -21
- package/dist/reply-markdown.d.ts +0 -18
- package/dist/sandbox-paths.d.ts +0 -4
- package/dist/tool-support/attribution.d.ts +0 -52
- package/dist/tool-support/github-api.d.ts +0 -51
- package/dist/tool-support/github-text.d.ts +0 -8
- package/dist/tool-support/pull-request-description.d.ts +0 -8
- package/dist/tools/clone-repository.d.ts +0 -287
- package/dist/tools/comment-on-issue.d.ts +0 -289
- package/dist/tools/comment-on-pull-request.d.ts +0 -294
- package/dist/tools/create-issue.d.ts +0 -300
- package/dist/tools/create-pull-request.d.ts +0 -322
- package/dist/tools/footer.d.ts +0 -17
- package/dist/tools/get-deployment.d.ts +0 -346
- package/dist/tools/get-issue.d.ts +0 -330
- package/dist/tools/get-pull-request.d.ts +0 -358
- package/dist/tools/get-release.d.ts +0 -325
- package/dist/tools/get-repository.d.ts +0 -308
- package/dist/tools/get-status.d.ts +0 -295
- package/dist/tools/react-to-issue.d.ts +0 -289
- package/dist/tools/resolve-pull-request-review-thread.d.ts +0 -288
- package/dist/tools/stack-pull-request.d.ts +0 -43
- package/dist/tools/submit-pull-request-review.d.ts +0 -300
- package/dist/tools/update-issue-comment.d.ts +0 -290
- package/dist/tools/update-issue.d.ts +0 -331
- package/dist/tools/update-pull-request-feedback.d.ts +0 -324
- package/dist/tools/update-pull-request.d.ts +0 -338
- package/dist/tools.d.ts +0 -13
- package/dist/webhooks/check-suite.d.ts +0 -121
- package/dist/webhooks/event-targets.d.ts +0 -44
- package/dist/webhooks/events.d.ts +0 -23
- package/dist/webhooks/fail-open-log.d.ts +0 -10
- package/dist/webhooks/handler.d.ts +0 -57
- package/dist/webhooks/installation-requests.d.ts +0 -105
- package/dist/webhooks/issue-outcome.d.ts +0 -11
- package/dist/webhooks/issue-update.d.ts +0 -8
- package/dist/webhooks/merge-conflict.d.ts +0 -53
- package/dist/webhooks/ownership.d.ts +0 -14
- package/dist/webhooks/pull-request-action.d.ts +0 -37
- package/dist/webhooks/pull-request-activity.d.ts +0 -11
- package/dist/webhooks/pull-request-match-data.d.ts +0 -31
- package/dist/webhooks/pull-request-outcome.d.ts +0 -16
- package/dist/webhooks/pull-request-people.d.ts +0 -51
- package/dist/webhooks/pull-request-preview.d.ts +0 -12
- package/dist/webhooks/pull-request-ready-reviewers.d.ts +0 -25
- package/dist/workspace-prepare.d.ts +0 -3
|
@@ -0,0 +1,2452 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { eventMatchFieldsSchema, mergeEventMatchFields } from "@sentry/junior-plugin-api";
|
|
3
|
+
import { lexer } from "marked";
|
|
4
|
+
import { createPrivateKey, createSign } from "node:crypto";
|
|
5
|
+
// src/permissions.ts
|
|
6
|
+
const LEVELS = /* @__PURE__ */ new Set([
|
|
7
|
+
"read",
|
|
8
|
+
"write",
|
|
9
|
+
"admin"
|
|
10
|
+
]);
|
|
11
|
+
const WRITE_ONLY_PERMISSIONS = /* @__PURE__ */ new Set(["profile", "workflows"]);
|
|
12
|
+
function isLevel(value) {
|
|
13
|
+
return LEVELS.has(value);
|
|
14
|
+
}
|
|
15
|
+
function normalizeScope(rawScope) {
|
|
16
|
+
return String(rawScope).trim().replace(/-/g, "_");
|
|
17
|
+
}
|
|
18
|
+
/** Validate the configured GitHub App read-token permission declaration. */
|
|
19
|
+
function normalizePermissions(permissions) {
|
|
20
|
+
if (permissions === void 0) return;
|
|
21
|
+
const entries = Object.entries(permissions);
|
|
22
|
+
if (entries.length === 0) throw new Error("githubPlugin appPermissions must contain at least one permission when provided.");
|
|
23
|
+
const request = {};
|
|
24
|
+
for (const [rawScope, rawLevel] of entries) {
|
|
25
|
+
const normalizedScope = normalizeScope(rawScope);
|
|
26
|
+
if (!normalizedScope) throw new Error("githubPlugin appPermissions contains an empty permission name.");
|
|
27
|
+
if (!/^[a-z][a-z0-9_]*$/.test(normalizedScope)) throw new Error(`githubPlugin appPermissions contains invalid permission "${rawScope}".`);
|
|
28
|
+
if (!isLevel(rawLevel)) throw new Error(`githubPlugin appPermissions.${rawScope} must be "read", "write", or "admin".`);
|
|
29
|
+
request[normalizedScope] = rawLevel;
|
|
30
|
+
}
|
|
31
|
+
return request;
|
|
32
|
+
}
|
|
33
|
+
/** Build the read-only installation-token permission body. */
|
|
34
|
+
function readGrantPermissions(permissions) {
|
|
35
|
+
const readOnly = { metadata: "read" };
|
|
36
|
+
for (const [scope, level] of Object.entries(permissions ?? {})) {
|
|
37
|
+
if (!isLevel(level)) throw new Error(`GitHub permission "${scope}" returned invalid level "${String(level)}".`);
|
|
38
|
+
if (!WRITE_ONLY_PERMISSIONS.has(scope)) readOnly[scope] = "read";
|
|
39
|
+
}
|
|
40
|
+
return readOnly;
|
|
41
|
+
}
|
|
42
|
+
// src/events/comment.ts
|
|
43
|
+
/**
|
|
44
|
+
* Filters on the GitHub user who sent the webhook: who wrote a comment or
|
|
45
|
+
* review, or who made an issue update. Resource types that merge these maps
|
|
46
|
+
* keep one description, so it names every case.
|
|
47
|
+
*/
|
|
48
|
+
function gitHubSenderMatchFields(events) {
|
|
49
|
+
return eventMatchFieldsSchema.parse({
|
|
50
|
+
senderId: {
|
|
51
|
+
kind: "number",
|
|
52
|
+
description: "immutable numeric GitHub user id of who wrote the comment or review, or made the update; prefer over logins",
|
|
53
|
+
events
|
|
54
|
+
},
|
|
55
|
+
senderLogin: {
|
|
56
|
+
kind: "string",
|
|
57
|
+
description: "GitHub login of who wrote the comment or review, or made the update; logins can be renamed",
|
|
58
|
+
events
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Filters on a GitHub comment or review: who wrote it and whether it mentions
|
|
64
|
+
* the App. Issue comments, pull request comments, reviews, and inline review
|
|
65
|
+
* comments set them, so the issue, pull request, and repository resource types
|
|
66
|
+
* share one definition.
|
|
67
|
+
*/
|
|
68
|
+
function gitHubCommentMatchFields(events) {
|
|
69
|
+
return eventMatchFieldsSchema.parse({
|
|
70
|
+
mentionsBot: {
|
|
71
|
+
kind: "boolean",
|
|
72
|
+
description: "true when the comment or review mentions this GitHub App",
|
|
73
|
+
events
|
|
74
|
+
},
|
|
75
|
+
...gitHubSenderMatchFields(events)
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
// src/events/scope.ts
|
|
79
|
+
/**
|
|
80
|
+
* `repo` in event data: lowercase `owner/repo`. GitHub ignores case in
|
|
81
|
+
* repository names, so tools accept this form.
|
|
82
|
+
*/
|
|
83
|
+
const gitHubRepoDataSchema = z.string().min(1).toLowerCase();
|
|
84
|
+
/** `commitSha` in event data: the full lowercase commit SHA. */
|
|
85
|
+
const gitHubCommitShaDataSchema = z.string().regex(/^[0-9a-f]{40}$/i).toLowerCase();
|
|
86
|
+
/** Filter on the repository of an event. */
|
|
87
|
+
function gitHubRepoMatchFields(events) {
|
|
88
|
+
return eventMatchFieldsSchema.parse({ repo: {
|
|
89
|
+
kind: "string",
|
|
90
|
+
case: "lower",
|
|
91
|
+
description: "lowercase repository as owner/repo, such as getsentry/junior",
|
|
92
|
+
events
|
|
93
|
+
} });
|
|
94
|
+
}
|
|
95
|
+
/** Filter on the commit of an event. */
|
|
96
|
+
function gitHubCommitMatchFields(events) {
|
|
97
|
+
return eventMatchFieldsSchema.parse({ commitSha: {
|
|
98
|
+
kind: "string",
|
|
99
|
+
case: "lower",
|
|
100
|
+
description: "full lowercase Git commit SHA",
|
|
101
|
+
events
|
|
102
|
+
} });
|
|
103
|
+
}
|
|
104
|
+
// src/events/issue.ts
|
|
105
|
+
const GITHUB_ISSUE_EVENTS = [
|
|
106
|
+
"issue.comment.created",
|
|
107
|
+
"issue.opened",
|
|
108
|
+
"issue.closed",
|
|
109
|
+
"issue.reopened",
|
|
110
|
+
"issue.updated"
|
|
111
|
+
];
|
|
112
|
+
const GITHUB_ISSUE_SUGGESTED_EVENTS = [
|
|
113
|
+
"issue.comment.created",
|
|
114
|
+
"issue.closed",
|
|
115
|
+
"issue.reopened",
|
|
116
|
+
"issue.updated"
|
|
117
|
+
];
|
|
118
|
+
/**
|
|
119
|
+
* The `issues` webhook actions that `issue.updated` publishes. The webhook
|
|
120
|
+
* schema and the `change` match field both use this list.
|
|
121
|
+
*/
|
|
122
|
+
const GITHUB_ISSUE_UPDATE_CHANGES = [
|
|
123
|
+
"edited",
|
|
124
|
+
"labeled",
|
|
125
|
+
"unlabeled",
|
|
126
|
+
"assigned",
|
|
127
|
+
"unassigned",
|
|
128
|
+
"milestoned",
|
|
129
|
+
"demilestoned"
|
|
130
|
+
];
|
|
131
|
+
/**
|
|
132
|
+
* Exact values GitHub sets on issue event data. Every issue event sets the
|
|
133
|
+
* repository and issue number. Comments and updates set who acted. Only
|
|
134
|
+
* updates set `change` and `label`, so an automation can run on one label
|
|
135
|
+
* that one person adds without the model deciding from untrusted text.
|
|
136
|
+
*/
|
|
137
|
+
const GITHUB_ISSUE_MATCH_FIELDS = mergeEventMatchFields(gitHubCommentMatchFields(["issue.comment.created"]), gitHubSenderMatchFields(["issue.updated"]), eventMatchFieldsSchema.parse({
|
|
138
|
+
...gitHubRepoMatchFields(GITHUB_ISSUE_EVENTS),
|
|
139
|
+
issue: {
|
|
140
|
+
kind: "number",
|
|
141
|
+
description: "issue number, such as 12",
|
|
142
|
+
events: GITHUB_ISSUE_EVENTS
|
|
143
|
+
},
|
|
144
|
+
change: {
|
|
145
|
+
kind: "string",
|
|
146
|
+
enum: [...GITHUB_ISSUE_UPDATE_CHANGES],
|
|
147
|
+
description: "what the issue update changed, such as labeled",
|
|
148
|
+
events: ["issue.updated"]
|
|
149
|
+
},
|
|
150
|
+
label: {
|
|
151
|
+
kind: "string",
|
|
152
|
+
case: "lower",
|
|
153
|
+
description: "lowercase name of the label that was added or removed, set only when change is labeled or unlabeled",
|
|
154
|
+
events: ["issue.updated"]
|
|
155
|
+
}
|
|
156
|
+
}));
|
|
157
|
+
/** The identifier shape that `gitHubIssueResource` builds. */
|
|
158
|
+
const GITHUB_ISSUE_IDENTIFIER = {
|
|
159
|
+
format: "owner/repo#number",
|
|
160
|
+
pattern: String.raw`^[^\s/:#]+\/[^\s/:#]+#\d+$`
|
|
161
|
+
};
|
|
162
|
+
/** Build the stable issue identity shared by tools and webhooks. */
|
|
163
|
+
function gitHubIssueResource(input) {
|
|
164
|
+
return {
|
|
165
|
+
label: `GitHub issue ${input.repo}#${input.number}`,
|
|
166
|
+
namespace: "github",
|
|
167
|
+
identifier: `${input.repo.toLowerCase()}#${input.number}`
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Describe an issue as a resource that a conversation can watch.
|
|
172
|
+
* Return undefined when the host cannot create Watches.
|
|
173
|
+
*/
|
|
174
|
+
function gitHubIssueSubscribable(input) {
|
|
175
|
+
if (!input.canSubscribe) return void 0;
|
|
176
|
+
return {
|
|
177
|
+
...gitHubIssueResource(input),
|
|
178
|
+
match: {
|
|
179
|
+
repo: gitHubRepoDataSchema.parse(input.repo),
|
|
180
|
+
issue: input.number
|
|
181
|
+
},
|
|
182
|
+
suggested_events: GITHUB_ISSUE_SUGGESTED_EVENTS,
|
|
183
|
+
supported_events: GITHUB_ISSUE_EVENTS,
|
|
184
|
+
type: "issue"
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
// src/events/deployment.ts
|
|
188
|
+
const GITHUB_DEPLOYMENT_EVENTS = [
|
|
189
|
+
"deployment.created",
|
|
190
|
+
"deployment.queued",
|
|
191
|
+
"deployment.pending",
|
|
192
|
+
"deployment.in_progress",
|
|
193
|
+
"deployment.succeeded",
|
|
194
|
+
"deployment.failed",
|
|
195
|
+
"deployment.error"
|
|
196
|
+
];
|
|
197
|
+
const GITHUB_DEPLOYMENT_SUGGESTED_EVENTS = [
|
|
198
|
+
"deployment.succeeded",
|
|
199
|
+
"deployment.failed",
|
|
200
|
+
"deployment.error"
|
|
201
|
+
];
|
|
202
|
+
/**
|
|
203
|
+
* Trusted deployment values that watches and event automations can match.
|
|
204
|
+
* Every deployment event sets them; the repository resource type also has
|
|
205
|
+
* events that do not.
|
|
206
|
+
*/
|
|
207
|
+
const GITHUB_DEPLOYMENT_MATCH_FIELDS = eventMatchFieldsSchema.parse({
|
|
208
|
+
...gitHubRepoMatchFields(GITHUB_DEPLOYMENT_EVENTS),
|
|
209
|
+
...gitHubCommitMatchFields(GITHUB_DEPLOYMENT_EVENTS),
|
|
210
|
+
deploymentId: {
|
|
211
|
+
kind: "number",
|
|
212
|
+
description: "numeric GitHub deployment id, such as 3001",
|
|
213
|
+
events: [...GITHUB_DEPLOYMENT_EVENTS]
|
|
214
|
+
},
|
|
215
|
+
environment: {
|
|
216
|
+
kind: "string",
|
|
217
|
+
case: "lower",
|
|
218
|
+
description: "lowercase deployment environment name, such as production",
|
|
219
|
+
events: [...GITHUB_DEPLOYMENT_EVENTS]
|
|
220
|
+
},
|
|
221
|
+
workflowId: {
|
|
222
|
+
kind: "number",
|
|
223
|
+
description: "numeric GitHub Actions workflow id when a workflow created the deployment",
|
|
224
|
+
events: [...GITHUB_DEPLOYMENT_EVENTS]
|
|
225
|
+
},
|
|
226
|
+
workflowPath: {
|
|
227
|
+
kind: "string",
|
|
228
|
+
description: "GitHub Actions workflow file, such as .github/workflows/deploy.yml, when a workflow created the deployment",
|
|
229
|
+
events: [...GITHUB_DEPLOYMENT_EVENTS]
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
/** The identifier shape that `gitHubDeploymentSourceResource` builds. */
|
|
233
|
+
const GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER = {
|
|
234
|
+
format: "deployment-source:owner/repo[:environment]:<full-commit-sha>",
|
|
235
|
+
pattern: String.raw`^deployment-source:[^\s/:#]+\/[^\s/:#]+(?::[^\s:]+)?:[0-9a-f]+$`
|
|
236
|
+
};
|
|
237
|
+
/** Build the stable deployment-source identity shared by tools and webhooks. */
|
|
238
|
+
function gitHubDeploymentSourceResource(input) {
|
|
239
|
+
const commitSha = input.commitSha.toLowerCase();
|
|
240
|
+
const environment = input.environment?.trim();
|
|
241
|
+
const repo = input.repo.toLowerCase();
|
|
242
|
+
return {
|
|
243
|
+
label: `GitHub deployment for ${repo} at ${commitSha.slice(0, 12)}`,
|
|
244
|
+
namespace: "github",
|
|
245
|
+
identifier: environment ? `deployment-source:${repo}:${encodeURIComponent(environment.toLowerCase())}:${commitSha}` : `deployment-source:${repo}:${commitSha}`
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Describe a deployment source that a conversation can watch.
|
|
250
|
+
* Return undefined when the host cannot create Watches.
|
|
251
|
+
*/
|
|
252
|
+
function gitHubDeploymentSourceSubscribable(input) {
|
|
253
|
+
if (!input.canSubscribe) return void 0;
|
|
254
|
+
const environment = input.environment?.trim().toLowerCase();
|
|
255
|
+
return {
|
|
256
|
+
...gitHubDeploymentSourceResource(input),
|
|
257
|
+
match: {
|
|
258
|
+
repo: gitHubRepoDataSchema.parse(input.repo),
|
|
259
|
+
commit_sha: gitHubCommitShaDataSchema.parse(input.commitSha),
|
|
260
|
+
...environment ? { environment } : void 0
|
|
261
|
+
},
|
|
262
|
+
suggested_events: GITHUB_DEPLOYMENT_SUGGESTED_EVENTS,
|
|
263
|
+
supported_events: [...GITHUB_DEPLOYMENT_EVENTS],
|
|
264
|
+
type: "deployment_source"
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
// src/events/pull-request.ts
|
|
268
|
+
const GITHUB_PULL_REQUEST_EVENTS = [
|
|
269
|
+
"pull_request.checks.failed",
|
|
270
|
+
"pull_request.checks.passed",
|
|
271
|
+
"pull_request.checks.recovered",
|
|
272
|
+
"pull_request.comment.created",
|
|
273
|
+
"pull_request.opened",
|
|
274
|
+
"pull_request.ready_for_review",
|
|
275
|
+
"pull_request.review.approved",
|
|
276
|
+
"pull_request.review.changes_requested",
|
|
277
|
+
"pull_request.review.commented",
|
|
278
|
+
"pull_request.review_comment.created",
|
|
279
|
+
"pull_request.merged",
|
|
280
|
+
"pull_request.closed_unmerged",
|
|
281
|
+
"pull_request.merge_conflict"
|
|
282
|
+
];
|
|
283
|
+
/**
|
|
284
|
+
* A stack merges only with a linear history, so a stacked pull request is
|
|
285
|
+
* rebased, never merged with its base. GitHub rebases the next pull request
|
|
286
|
+
* after a merge, but it stops at a conflict and sends no event for it.
|
|
287
|
+
*/
|
|
288
|
+
const STACK_CHECK = "Check if the pull request is in a stack: `gh api 'repos/OWNER/REPO/stacks?pull_request=NUMBER'`.";
|
|
289
|
+
const STACK_CONFLICT_STEPS = "run `gh stack rebase`, resolve each conflict so that both changes stay intact, stage the files, and run `gh stack rebase --continue`. Run the checks again, run `gh stack push`, and confirm that each open pull request in the stack can merge.";
|
|
290
|
+
/**
|
|
291
|
+
* Every comment on a pull request gets the same feedback status: a
|
|
292
|
+
* conversation comment, an inline review comment, and a review body. A review
|
|
293
|
+
* sets comment_id only when it has a body.
|
|
294
|
+
*/
|
|
295
|
+
const PULL_REQUEST_FEEDBACK = "When Verified details include comment_id, call github_updatePullRequestFeedback after acting on actionable feedback, with the exact repo, pull_request, comment_id, and comment_kind from Verified details, and status \"addressed\" or \"declined\".";
|
|
296
|
+
const GITHUB_PULL_REQUEST_EVENT_GUIDANCE = {
|
|
297
|
+
"pull_request.checks.failed": "Fix only failures that the pull request causes. Do not skip, disable, or weaken a check to make it pass.",
|
|
298
|
+
"pull_request.review.approved": `When the approval includes actionable feedback, address it like any other review feedback. ${PULL_REQUEST_FEEDBACK}`,
|
|
299
|
+
"pull_request.review.changes_requested": PULL_REQUEST_FEEDBACK,
|
|
300
|
+
"pull_request.review.commented": PULL_REQUEST_FEEDBACK,
|
|
301
|
+
"pull_request.comment.created": PULL_REQUEST_FEEDBACK,
|
|
302
|
+
"pull_request.review_comment.created": `${PULL_REQUEST_FEEDBACK} Then resolve the thread with github_resolvePullRequestReviewThread.`,
|
|
303
|
+
"pull_request.merge_conflict": `${STACK_CHECK} If it is, run \`gh stack checkout NUMBER\`, then ${STACK_CONFLICT_STEPS} If it is not, fetch base_branch from Verified details and merge it into the pull request branch. Do not rebase. Resolve each conflict so that both the pull request change and the base branch change stay intact. Run the checks again, push, and confirm that the pull request can merge.`
|
|
304
|
+
};
|
|
305
|
+
/** Combine provider defaults with app guidance for pull request events. */
|
|
306
|
+
function gitHubPullRequestEventGuidance(guidance) {
|
|
307
|
+
const merged = { ...GITHUB_PULL_REQUEST_EVENT_GUIDANCE };
|
|
308
|
+
for (const eventType of GITHUB_PULL_REQUEST_EVENTS) {
|
|
309
|
+
const extra = guidance?.[eventType]?.trim();
|
|
310
|
+
if (!extra) continue;
|
|
311
|
+
const base = merged[eventType];
|
|
312
|
+
merged[eventType] = base ? `${base} ${extra}` : extra;
|
|
313
|
+
}
|
|
314
|
+
return merged;
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Junior maintains the pull requests it creates. The pull request is its own
|
|
318
|
+
* work, so it answers and fixes review feedback without asking first.
|
|
319
|
+
* GitHub already tells people about reviews, approvals, merges, and closes,
|
|
320
|
+
* and the review desk shows the next action. So the Watch skips those
|
|
321
|
+
* outcomes and posts in the thread only when a person must act.
|
|
322
|
+
*/
|
|
323
|
+
const DEFAULT_PULL_REQUEST_SUBSCRIPTION = {
|
|
324
|
+
events: [
|
|
325
|
+
"pull_request.checks.failed",
|
|
326
|
+
"pull_request.comment.created",
|
|
327
|
+
"pull_request.review.changes_requested",
|
|
328
|
+
"pull_request.review.commented",
|
|
329
|
+
"pull_request.review_comment.created"
|
|
330
|
+
],
|
|
331
|
+
intent: "Maintain pull requests that you create. For actionable review feedback, failed checks, or merge conflicts, inspect the evidence, make scoped fixes, verify them, and push, without asking first. Do not merge it: a person merges it, even when a review says to ship it. Reply on GitHub to review comments and questions, in the thread where they were asked. Post in the originating thread only when a person must decide or act, such as a blocker that you cannot fix. Do not post status updates: GitHub already shows reviews, approvals, fixes, and replies."
|
|
332
|
+
};
|
|
333
|
+
/** Resolve the Watch to create after Junior creates a pull request, if any. */
|
|
334
|
+
function gitHubPullRequestSubscription(config) {
|
|
335
|
+
if (config === false) return void 0;
|
|
336
|
+
return config ?? DEFAULT_PULL_REQUEST_SUBSCRIPTION;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Junior finishes its own drafts. Passing checks start no other step, so the
|
|
340
|
+
* Watch of a draft also gets them. Marking the pull request ready sends the
|
|
341
|
+
* review request. GitHub also asks the code owners then, so a draft with code
|
|
342
|
+
* owners waits for the person who asked for it, unless they said otherwise.
|
|
343
|
+
* A repository's AGENTS.md can also ask that drafts wait for a person.
|
|
344
|
+
* Each passing suite wakes the Watch, so a suite that leaves the required
|
|
345
|
+
* checks unfinished must stay silent, or every suite posts.
|
|
346
|
+
*/
|
|
347
|
+
const DRAFT_CHECKS_RECOVERED_GUIDANCE = "If the pull request is still a draft, call github_getPullRequest and read its `checks`, `code_owners`, and `agents_md`. When `checks.required` is `passing` and no decision is open, in the pull request body or in an open review item that waits on the person who asked for it: mark it ready with github_updatePullRequest and draft false, when the person who asked for it said to mark it ready, or when `code_owners` is empty and `agents_md` does not ask for draft pull requests or say that a person marks them ready. Otherwise keep it a draft: marking it ready would ask the code owners to review, or break the AGENTS.md rule. Tell the person who asked for it in the originating thread that the checks pass and the draft waits for their review, and name why: the code owners that marking it ready asks, or the AGENTS.md rule. If you already told them for this head commit, stay silent. When it is `failing`, fix the failing checks like a failed check. When it is `pending` or `not_reported`, stay silent: a later passing suite wakes you again. `not_reported` means the required checks may not have started on the latest commit yet, not that none are required.";
|
|
348
|
+
/**
|
|
349
|
+
* Build the Watch created after Junior creates a pull request. Only a draft
|
|
350
|
+
* Watch gets passing checks, so a ready pull request is not woken by each
|
|
351
|
+
* passing check suite.
|
|
352
|
+
*/
|
|
353
|
+
function gitHubPullRequestCreateWatch(config, pullRequest) {
|
|
354
|
+
return {
|
|
355
|
+
events: [.../* @__PURE__ */ new Set([
|
|
356
|
+
...config.events,
|
|
357
|
+
"pull_request.merge_conflict",
|
|
358
|
+
...pullRequest.draft ? ["pull_request.checks.recovered"] : []
|
|
359
|
+
])],
|
|
360
|
+
...pullRequest.draft ? { guidance: { "pull_request.checks.recovered": DRAFT_CHECKS_RECOVERED_GUIDANCE } } : void 0,
|
|
361
|
+
intent: config.intent
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
const GITHUB_PULL_REQUEST_SUGGESTED_EVENTS = [
|
|
365
|
+
"pull_request.checks.failed",
|
|
366
|
+
"pull_request.comment.created",
|
|
367
|
+
"pull_request.ready_for_review",
|
|
368
|
+
"pull_request.review.changes_requested",
|
|
369
|
+
"pull_request.review.commented",
|
|
370
|
+
"pull_request.review_comment.created",
|
|
371
|
+
"pull_request.merged",
|
|
372
|
+
"pull_request.closed_unmerged",
|
|
373
|
+
"pull_request.merge_conflict"
|
|
374
|
+
];
|
|
375
|
+
/**
|
|
376
|
+
* Pull request events that a GitHub webhook payload describes. GitHub sends
|
|
377
|
+
* no webhook when a pull request gets a conflict, so the webhook reads the
|
|
378
|
+
* pull request for `pull_request.merge_conflict` instead.
|
|
379
|
+
*/
|
|
380
|
+
const GITHUB_PULL_REQUEST_PAYLOAD_EVENTS = GITHUB_PULL_REQUEST_EVENTS.filter((eventType) => eventType !== "pull_request.merge_conflict");
|
|
381
|
+
/** Pull request events that a comment or review starts. */
|
|
382
|
+
const GITHUB_PULL_REQUEST_COMMENT_EVENTS = [
|
|
383
|
+
"pull_request.comment.created",
|
|
384
|
+
"pull_request.review.approved",
|
|
385
|
+
"pull_request.review.changes_requested",
|
|
386
|
+
"pull_request.review.commented",
|
|
387
|
+
"pull_request.review_comment.created"
|
|
388
|
+
];
|
|
389
|
+
/** Pull request events that a check suite result starts. */
|
|
390
|
+
const GITHUB_PULL_REQUEST_CHECK_EVENTS = [
|
|
391
|
+
"pull_request.checks.failed",
|
|
392
|
+
"pull_request.checks.passed",
|
|
393
|
+
"pull_request.checks.recovered"
|
|
394
|
+
];
|
|
395
|
+
/**
|
|
396
|
+
* Exact values GitHub may set on pull request event data. Missing keys do not
|
|
397
|
+
* match. The opener and author values load in
|
|
398
|
+
* `webhooks/pull-request-match-data.ts` for every payload pull request event.
|
|
399
|
+
* The pull request comment webhook has no head branch. A check suite result
|
|
400
|
+
* that GitHub links to no pull request has no `pullRequest`. The webhook
|
|
401
|
+
* checks for a Watch or event automation before it reads a pull request for
|
|
402
|
+
* a conflict, so `pull_request.merge_conflict` matches only `repo` and
|
|
403
|
+
* `pullRequest`.
|
|
404
|
+
*/
|
|
405
|
+
const GITHUB_PULL_REQUEST_MATCH_FIELDS = eventMatchFieldsSchema.parse({
|
|
406
|
+
...gitHubCommentMatchFields(GITHUB_PULL_REQUEST_COMMENT_EVENTS),
|
|
407
|
+
...gitHubRepoMatchFields(GITHUB_PULL_REQUEST_EVENTS),
|
|
408
|
+
...gitHubCommitMatchFields(GITHUB_PULL_REQUEST_CHECK_EVENTS),
|
|
409
|
+
pullRequest: {
|
|
410
|
+
kind: "number",
|
|
411
|
+
description: "pull request number, such as 946",
|
|
412
|
+
events: [...GITHUB_PULL_REQUEST_EVENTS]
|
|
413
|
+
},
|
|
414
|
+
authors: {
|
|
415
|
+
kind: "string",
|
|
416
|
+
list: true,
|
|
417
|
+
description: "GitHub logins of the commit authors and Co-authored-by people, including bots such as this GitHub App",
|
|
418
|
+
events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
|
|
419
|
+
},
|
|
420
|
+
headBranch: {
|
|
421
|
+
kind: "string",
|
|
422
|
+
description: "head branch name from the webhook",
|
|
423
|
+
events: GITHUB_PULL_REQUEST_PAYLOAD_EVENTS.filter((eventType) => eventType !== "pull_request.comment.created")
|
|
424
|
+
},
|
|
425
|
+
isDraft: {
|
|
426
|
+
kind: "boolean",
|
|
427
|
+
description: "true when the pull request is a draft",
|
|
428
|
+
events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
|
|
429
|
+
},
|
|
430
|
+
openerEmail: {
|
|
431
|
+
kind: "string",
|
|
432
|
+
description: "opener email when GitHub sends it; missing on pull requests that this GitHub App opened",
|
|
433
|
+
events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
|
|
434
|
+
},
|
|
435
|
+
openerUsername: {
|
|
436
|
+
kind: "string",
|
|
437
|
+
description: "login of who opened the pull request; on pull requests that this GitHub App opened, the person who asked for it, missing until that person is saved",
|
|
438
|
+
events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
|
|
439
|
+
},
|
|
440
|
+
openerRole: {
|
|
441
|
+
kind: "string",
|
|
442
|
+
description: "opener's repository role: admin, maintain, write, triage, read, none (no access, such as most bots), or a custom role name",
|
|
443
|
+
events: [...GITHUB_PULL_REQUEST_PAYLOAD_EVENTS]
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
/** The identifier shape that `gitHubPullRequestResource` builds. */
|
|
447
|
+
const GITHUB_PULL_REQUEST_IDENTIFIER = {
|
|
448
|
+
format: "owner/repo#number",
|
|
449
|
+
pattern: String.raw`^[^\s/:#]+\/[^\s/:#]+#\d+$`
|
|
450
|
+
};
|
|
451
|
+
/** Build the stable pull request identity shared by tools and webhooks. */
|
|
452
|
+
function gitHubPullRequestResource(input) {
|
|
453
|
+
return {
|
|
454
|
+
label: `GitHub PR ${input.repo}#${input.number}`,
|
|
455
|
+
namespace: "github",
|
|
456
|
+
identifier: `${input.repo.toLowerCase()}#${input.number}`
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Describe a pull request as a resource that a conversation can watch.
|
|
461
|
+
* Return undefined when the host cannot create Watches.
|
|
462
|
+
*/
|
|
463
|
+
function gitHubPullRequestSubscribable(input) {
|
|
464
|
+
if (!input.canSubscribe) return void 0;
|
|
465
|
+
const omitted = new Set(input.omitSuggestedEvents ?? []);
|
|
466
|
+
const suggestedEvents = GITHUB_PULL_REQUEST_SUGGESTED_EVENTS.filter((eventType) => !omitted.has(eventType));
|
|
467
|
+
return {
|
|
468
|
+
...gitHubPullRequestResource(input),
|
|
469
|
+
match: {
|
|
470
|
+
repo: gitHubRepoDataSchema.parse(input.repo),
|
|
471
|
+
pull_request: input.number
|
|
472
|
+
},
|
|
473
|
+
...suggestedEvents.length > 0 ? { suggested_events: [...suggestedEvents] } : void 0,
|
|
474
|
+
supported_events: [...GITHUB_PULL_REQUEST_EVENTS],
|
|
475
|
+
type: "pull_request"
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
// src/events/release.ts
|
|
479
|
+
const GITHUB_RELEASE_EVENTS = ["release.published"];
|
|
480
|
+
/**
|
|
481
|
+
* `tag` in event data: the trimmed tag with ASCII letters in lowercase. The
|
|
482
|
+
* release-source identifier has the URI-encoded tag, and the plugin
|
|
483
|
+
* lowercases identifiers. Encoding turns other characters into `%XX`
|
|
484
|
+
* escapes, so only ASCII letters change case there. This form is the same
|
|
485
|
+
* text, so `release/1.0` is not `release%2f1.0`, and `Ü` stays `Ü`. To turn
|
|
486
|
+
* an identifier into a `tag` filter, decode its tag part.
|
|
487
|
+
*/
|
|
488
|
+
const gitHubReleaseTagDataSchema = z.string().trim().min(1).transform((tag) => tag.replace(/[A-Z]+/g, (letters) => letters.toLowerCase()));
|
|
489
|
+
/** Exact values that every release event sets. */
|
|
490
|
+
const GITHUB_RELEASE_MATCH_FIELDS = eventMatchFieldsSchema.parse({
|
|
491
|
+
...gitHubRepoMatchFields(GITHUB_RELEASE_EVENTS),
|
|
492
|
+
tag: {
|
|
493
|
+
kind: "string",
|
|
494
|
+
description: "release tag with ASCII letters in lowercase, such as v1.2.0 or release/1.0",
|
|
495
|
+
events: [...GITHUB_RELEASE_EVENTS]
|
|
496
|
+
}
|
|
497
|
+
});
|
|
498
|
+
const GITHUB_RELEASE_SUGGESTED_EVENTS = ["release.published"];
|
|
499
|
+
/** The identifier shape that `gitHubReleaseSourceResource` builds. */
|
|
500
|
+
const GITHUB_RELEASE_SOURCE_IDENTIFIER = {
|
|
501
|
+
format: "release-source:owner/repo[:tag]",
|
|
502
|
+
pattern: String.raw`^release-source:[^\s/:#]+\/[^\s/:#]+(?::[^\s:]+)?$`
|
|
503
|
+
};
|
|
504
|
+
/** Build the stable release-source identity shared by tools and webhooks. */
|
|
505
|
+
function gitHubReleaseSourceResource(input) {
|
|
506
|
+
const repo = input.repo.toLowerCase();
|
|
507
|
+
const tag = input.tag?.trim();
|
|
508
|
+
return {
|
|
509
|
+
label: `GitHub release for ${repo}`,
|
|
510
|
+
namespace: "github",
|
|
511
|
+
identifier: tag ? `release-source:${repo}:${encodeURIComponent(tag)}` : `release-source:${repo}`
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Describe a release source that a conversation can watch.
|
|
516
|
+
* Return undefined when the host cannot create Watches.
|
|
517
|
+
*/
|
|
518
|
+
function gitHubReleaseSourceSubscribable(input) {
|
|
519
|
+
if (!input.canSubscribe) return void 0;
|
|
520
|
+
const tag = input.tag?.trim();
|
|
521
|
+
return {
|
|
522
|
+
...gitHubReleaseSourceResource(input),
|
|
523
|
+
match: {
|
|
524
|
+
repo: gitHubRepoDataSchema.parse(input.repo),
|
|
525
|
+
...tag ? { tag: gitHubReleaseTagDataSchema.parse(tag) } : void 0
|
|
526
|
+
},
|
|
527
|
+
suggested_events: GITHUB_RELEASE_SUGGESTED_EVENTS,
|
|
528
|
+
supported_events: [...GITHUB_RELEASE_EVENTS],
|
|
529
|
+
type: "release_source"
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
// src/events/repository.ts
|
|
533
|
+
/** The identifier shape that `gitHubRepositoryResource` builds. */
|
|
534
|
+
const GITHUB_REPOSITORY_IDENTIFIER = {
|
|
535
|
+
format: "owner/repo",
|
|
536
|
+
pattern: String.raw`^[^\s/:#]+\/[^\s/:#]+$`
|
|
537
|
+
};
|
|
538
|
+
/** Build the stable repository identity shared by tools and webhooks. */
|
|
539
|
+
function gitHubRepositoryResource(input) {
|
|
540
|
+
return {
|
|
541
|
+
label: `GitHub repository ${input.repo}`,
|
|
542
|
+
namespace: "github",
|
|
543
|
+
identifier: input.repo.toLowerCase()
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
/** Events that a repository Watch gets: deployments, issues, and pull requests. */
|
|
547
|
+
const GITHUB_REPOSITORY_EVENTS = [
|
|
548
|
+
...GITHUB_DEPLOYMENT_EVENTS,
|
|
549
|
+
...GITHUB_ISSUE_EVENTS,
|
|
550
|
+
...GITHUB_PULL_REQUEST_EVENTS
|
|
551
|
+
];
|
|
552
|
+
/** Repository events to suggest when a conversation starts a Watch. */
|
|
553
|
+
const GITHUB_REPOSITORY_SUGGESTED_EVENTS = [
|
|
554
|
+
"issue.opened",
|
|
555
|
+
"pull_request.opened",
|
|
556
|
+
...GITHUB_ISSUE_SUGGESTED_EVENTS.filter((eventType) => eventType !== "issue.updated"),
|
|
557
|
+
...GITHUB_PULL_REQUEST_SUGGESTED_EVENTS
|
|
558
|
+
];
|
|
559
|
+
/**
|
|
560
|
+
* Describe a repository as a resource that a conversation can watch.
|
|
561
|
+
* Return undefined when the host cannot create Watches.
|
|
562
|
+
*/
|
|
563
|
+
function gitHubRepositorySubscribable(input) {
|
|
564
|
+
if (!input.canSubscribe) return void 0;
|
|
565
|
+
return {
|
|
566
|
+
...gitHubRepositoryResource(input),
|
|
567
|
+
match: { repo: gitHubRepoDataSchema.parse(input.repo) },
|
|
568
|
+
suggested_events: [...GITHUB_REPOSITORY_SUGGESTED_EVENTS],
|
|
569
|
+
supported_events: [...GITHUB_REPOSITORY_EVENTS],
|
|
570
|
+
type: "repository"
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
// src/webhooks/ownership.ts
|
|
574
|
+
const GITHUB_BOT_NOREPLY_EMAIL = /^(?<userId>[1-9]\d*)\+(?<login>[^@]+\[bot\])@users\.noreply\.github\.com$/i;
|
|
575
|
+
/** Parse the bot identity encoded in GitHub's standard noreply address. */
|
|
576
|
+
function parseGitHubBotIdentity(value) {
|
|
577
|
+
const match = GITHUB_BOT_NOREPLY_EMAIL.exec(value?.trim() ?? "");
|
|
578
|
+
const login = match?.groups?.["login"];
|
|
579
|
+
const userId = match?.groups?.["userId"];
|
|
580
|
+
if (!login || !userId) return void 0;
|
|
581
|
+
return {
|
|
582
|
+
login,
|
|
583
|
+
userId: Number(userId)
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
/** Derive the provider login encoded in a standard GitHub noreply address. */
|
|
587
|
+
function botLoginFromEmail(value) {
|
|
588
|
+
return parseGitHubBotIdentity(value)?.login;
|
|
589
|
+
}
|
|
590
|
+
/** Check whether a GitHub login is the bot encoded in the configured bot email. */
|
|
591
|
+
function isBotLogin(login, botEmail) {
|
|
592
|
+
const botLogin = botLoginFromEmail(botEmail)?.toLowerCase();
|
|
593
|
+
return Boolean(botLogin && login?.trim().toLowerCase() === botLogin);
|
|
594
|
+
}
|
|
595
|
+
/** Derive the GitHub user id encoded in a standard GitHub noreply address. */
|
|
596
|
+
function botUserIdFromEmail(value) {
|
|
597
|
+
return parseGitHubBotIdentity(value)?.userId;
|
|
598
|
+
}
|
|
599
|
+
const SKIPPED_TOKEN_TYPES = /* @__PURE__ */ new Set([
|
|
600
|
+
"blockquote",
|
|
601
|
+
"code",
|
|
602
|
+
"codespan",
|
|
603
|
+
"html"
|
|
604
|
+
]);
|
|
605
|
+
/**
|
|
606
|
+
* Collect the text of Markdown tokens outside quotes, code, and HTML. Join
|
|
607
|
+
* inline tokens with no separator, so `me@bot` stays one word.
|
|
608
|
+
*/
|
|
609
|
+
function ownTokenText(tokens, separator = "") {
|
|
610
|
+
return tokens.map((token) => {
|
|
611
|
+
if (SKIPPED_TOKEN_TYPES.has(token.type)) return " ";
|
|
612
|
+
if (token.type === "list") return token.items.map((item) => ownTokenText(item.tokens, "\n")).join("\n");
|
|
613
|
+
if (token.type === "table") {
|
|
614
|
+
const table = token;
|
|
615
|
+
return [table.header, ...table.rows].flat().map((cell) => ownTokenText(cell.tokens)).join(" ");
|
|
616
|
+
}
|
|
617
|
+
if ("tokens" in token && token.tokens) return ownTokenText(token.tokens);
|
|
618
|
+
return "text" in token ? token.text : token.raw;
|
|
619
|
+
}).join(separator);
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Keep the author's own text. A GitHub-flavored Markdown parser finds the
|
|
623
|
+
* quotes and code, the same as GitHub when it renders the comment.
|
|
624
|
+
*/
|
|
625
|
+
function ownCommentText(text) {
|
|
626
|
+
return ownTokenText(lexer(text, { gfm: true }), "\n");
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Check whether the author's own text mentions the bot encoded in the
|
|
630
|
+
* configured bot email. GitHub sends mentions only as comment text, with no
|
|
631
|
+
* structured field, so this reads the App slug: the bot login without `[bot]`.
|
|
632
|
+
* This shows only that the comment addresses the bot. It does not grant trust;
|
|
633
|
+
* match the commenter's `senderId` for that.
|
|
634
|
+
*/
|
|
635
|
+
function mentionsBotLogin(text, botEmail) {
|
|
636
|
+
const slug = botLoginFromEmail(botEmail)?.replace(/\[bot\]$/i, "");
|
|
637
|
+
if (!slug) return false;
|
|
638
|
+
const escaped = slug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
639
|
+
return new RegExp(`(?:^|[^\\w-])@${escaped}(?![\\w-])`, "i").test(ownCommentText(text));
|
|
640
|
+
}
|
|
641
|
+
// src/credential-support.ts
|
|
642
|
+
/**
|
|
643
|
+
* GitHub credential issuance and provider request support.
|
|
644
|
+
*
|
|
645
|
+
* This module owns OAuth refresh, installation tokens, credential leases, and
|
|
646
|
+
* installation and user credential parsing.
|
|
647
|
+
*/
|
|
648
|
+
const GITHUB_APP_ID_ENV = "GITHUB_APP_ID";
|
|
649
|
+
const GITHUB_APP_PRIVATE_KEY_ENV = "GITHUB_APP_PRIVATE_KEY";
|
|
650
|
+
const GITHUB_INSTALLATION_ID_ENV = "GITHUB_INSTALLATION_ID";
|
|
651
|
+
const GITHUB_AUTH_TOKEN_ENV = "GITHUB_TOKEN";
|
|
652
|
+
const GITHUB_AUTH_TOKEN_PLACEHOLDER = "ghp_host_managed_credential";
|
|
653
|
+
const MAX_LEASE_MS = 36e5;
|
|
654
|
+
const REFRESH_BUFFER_MS = 3e5;
|
|
655
|
+
const USER_REFRESH_TIMEOUT_MS = 2e4;
|
|
656
|
+
const GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES = 65536;
|
|
657
|
+
const HTTP_READ_METHODS = /* @__PURE__ */ new Set([
|
|
658
|
+
"GET",
|
|
659
|
+
"HEAD",
|
|
660
|
+
"OPTIONS"
|
|
661
|
+
]);
|
|
662
|
+
const USER_TOKEN_GRANTS = /* @__PURE__ */ new Set(["user-read", "user-write"]);
|
|
663
|
+
const CREATE_TOOL_ROUTING_GUIDANCE = "This is a tool-routing denial, not a GitHub permission failure. Do not ask the user for GitHub permissions; retry with the required tool.";
|
|
664
|
+
const USER_WRITE_REQUIREMENTS = ["requesting GitHub user permission to perform this operation"];
|
|
665
|
+
const GITHUB_CREDENTIAL_DOMAINS = ["api.github.com", "github.com"];
|
|
666
|
+
const GITHUB_ASSET_UPLOAD_CREDENTIAL_DOMAINS = [...GITHUB_CREDENTIAL_DOMAINS, "uploads.github.com"];
|
|
667
|
+
var GitHubUserRefreshRejectedError = class extends Error {
|
|
668
|
+
constructor(message) {
|
|
669
|
+
super(message);
|
|
670
|
+
this.name = "GitHubUserRefreshRejectedError";
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
/** A GitHub API response with an error status. */
|
|
674
|
+
var GitHubRequestError = class extends Error {
|
|
675
|
+
status;
|
|
676
|
+
constructor(message, status) {
|
|
677
|
+
super(message);
|
|
678
|
+
this.name = "GitHubRequestError";
|
|
679
|
+
this.status = status;
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
var GitHubPluginSetupError = class extends Error {
|
|
683
|
+
constructor(message) {
|
|
684
|
+
super(message);
|
|
685
|
+
this.name = "GitHubPluginSetupError";
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
/** Return whether a provider value is a JSON object. */
|
|
689
|
+
function isRecord(value) {
|
|
690
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
691
|
+
}
|
|
692
|
+
/** Read a non-empty GitHub plugin environment value. */
|
|
693
|
+
function readEnv(name) {
|
|
694
|
+
const value = process.env[name];
|
|
695
|
+
if (typeof value !== "string") return;
|
|
696
|
+
const trimmed = value.trim();
|
|
697
|
+
return trimmed ? trimmed : void 0;
|
|
698
|
+
}
|
|
699
|
+
/** Read a required GitHub plugin environment value. */
|
|
700
|
+
function requireEnv(name) {
|
|
701
|
+
const value = readEnv(name);
|
|
702
|
+
if (!value) throw new GitHubPluginSetupError(`Missing ${name}`);
|
|
703
|
+
return value;
|
|
704
|
+
}
|
|
705
|
+
/** Normalize configured GitHub OAuth scopes. */
|
|
706
|
+
function normalizeScopeList(scopes) {
|
|
707
|
+
return [...new Set((scopes ?? []).flatMap((scope) => String(scope).split(/\s+/)).map((scope) => scope.trim()).filter(Boolean))].sort();
|
|
708
|
+
}
|
|
709
|
+
function normalizeOAuthScope(scope) {
|
|
710
|
+
const normalized = normalizeScopeList(scope ? [scope] : []);
|
|
711
|
+
return normalized.length ? normalized.join(" ") : void 0;
|
|
712
|
+
}
|
|
713
|
+
function hasRequiredOAuthScope(storedScope, requiredScope) {
|
|
714
|
+
const required = normalizeScopeList(requiredScope ? [requiredScope] : []);
|
|
715
|
+
if (required.length === 0) return true;
|
|
716
|
+
const stored = new Set(normalizeScopeList(storedScope ? [storedScope] : []));
|
|
717
|
+
if (stored.size === 0) return false;
|
|
718
|
+
return required.every((scope) => stored.has(scope));
|
|
719
|
+
}
|
|
720
|
+
function isGitHubApiUrl(upstreamUrl) {
|
|
721
|
+
return upstreamUrl.hostname.toLowerCase() === "api.github.com";
|
|
722
|
+
}
|
|
723
|
+
function base64Url(input) {
|
|
724
|
+
return Buffer.from(input).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
725
|
+
}
|
|
726
|
+
function getPrivateKey(envName) {
|
|
727
|
+
const raw = requireEnv(envName);
|
|
728
|
+
let key;
|
|
729
|
+
try {
|
|
730
|
+
key = createPrivateKey({
|
|
731
|
+
key: raw,
|
|
732
|
+
format: "pem"
|
|
733
|
+
});
|
|
734
|
+
} catch {
|
|
735
|
+
throw new GitHubPluginSetupError(`Invalid ${envName}: expected a PEM-encoded RSA private key`);
|
|
736
|
+
}
|
|
737
|
+
if (key.asymmetricKeyType !== "rsa") throw new GitHubPluginSetupError(`Invalid ${envName}: GitHub App signing requires an RSA private key`);
|
|
738
|
+
return key;
|
|
739
|
+
}
|
|
740
|
+
function createAppJwt(appId, privateKeyEnv) {
|
|
741
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
742
|
+
const header = {
|
|
743
|
+
alg: "RS256",
|
|
744
|
+
typ: "JWT"
|
|
745
|
+
};
|
|
746
|
+
const payload = {
|
|
747
|
+
iat: now - 60,
|
|
748
|
+
exp: now + 540,
|
|
749
|
+
iss: appId
|
|
750
|
+
};
|
|
751
|
+
const signingInput = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(payload))}`;
|
|
752
|
+
const signer = createSign("RSA-SHA256");
|
|
753
|
+
signer.update(signingInput);
|
|
754
|
+
signer.end();
|
|
755
|
+
return `${signingInput}.${signer.sign(getPrivateKey(privateKeyEnv)).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_")}`;
|
|
756
|
+
}
|
|
757
|
+
/** Send an authenticated request to the GitHub API. */
|
|
758
|
+
async function githubRequest(apiBase, path, params) {
|
|
759
|
+
const response = await fetch(`${apiBase}${path}`, {
|
|
760
|
+
method: params.method ?? "GET",
|
|
761
|
+
headers: {
|
|
762
|
+
Accept: "application/vnd.github+json",
|
|
763
|
+
Authorization: `Bearer ${params.token}`,
|
|
764
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
765
|
+
...params.body ? { "Content-Type": "application/json" } : void 0
|
|
766
|
+
},
|
|
767
|
+
...params.body ? { body: JSON.stringify(params.body) } : void 0
|
|
768
|
+
});
|
|
769
|
+
const text = await response.text();
|
|
770
|
+
let parsed;
|
|
771
|
+
if (text) try {
|
|
772
|
+
parsed = JSON.parse(text);
|
|
773
|
+
} catch {
|
|
774
|
+
parsed = void 0;
|
|
775
|
+
}
|
|
776
|
+
if (!response.ok) throw new GitHubRequestError(isRecord(parsed) && typeof parsed["message"] === "string" ? parsed["message"] : `GitHub API error ${response.status}`, response.status);
|
|
777
|
+
return parsed;
|
|
778
|
+
}
|
|
779
|
+
function buildOAuthTokenRequest(input) {
|
|
780
|
+
const payload = {
|
|
781
|
+
...input.payload,
|
|
782
|
+
client_id: input.clientId,
|
|
783
|
+
client_secret: input.clientSecret
|
|
784
|
+
};
|
|
785
|
+
return {
|
|
786
|
+
headers: {
|
|
787
|
+
Accept: "application/json",
|
|
788
|
+
"Content-Type": "application/x-www-form-urlencoded"
|
|
789
|
+
},
|
|
790
|
+
body: new URLSearchParams(payload)
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
function parseOAuthResponseJson(responseText) {
|
|
794
|
+
if (!responseText.trim()) return;
|
|
795
|
+
try {
|
|
796
|
+
return JSON.parse(responseText);
|
|
797
|
+
} catch {
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
function oauthErrorCode(data) {
|
|
802
|
+
return isRecord(data) && typeof data["error"] === "string" ? data["error"] : void 0;
|
|
803
|
+
}
|
|
804
|
+
function isRejectedRefreshError(errorCode) {
|
|
805
|
+
return errorCode === "bad_refresh_token" || errorCode === "invalid_grant";
|
|
806
|
+
}
|
|
807
|
+
function parseOAuthTokenResponse(data, requestedScope) {
|
|
808
|
+
if (!isRecord(data)) throw new Error("OAuth token response is invalid");
|
|
809
|
+
if (typeof data["access_token"] !== "string" || !data["access_token"].trim()) throw new Error("OAuth token response missing access_token");
|
|
810
|
+
if (typeof data["refresh_token"] !== "string" || !data["refresh_token"].trim()) throw new Error("OAuth token response missing refresh_token");
|
|
811
|
+
let scope = normalizeOAuthScope(requestedScope);
|
|
812
|
+
if (data["scope"] !== void 0) {
|
|
813
|
+
if (typeof data["scope"] !== "string") throw new Error("OAuth token response returned invalid scope");
|
|
814
|
+
scope = normalizeOAuthScope(data["scope"]) ?? scope;
|
|
815
|
+
}
|
|
816
|
+
const result = {
|
|
817
|
+
accessToken: data["access_token"],
|
|
818
|
+
refreshToken: data["refresh_token"],
|
|
819
|
+
...scope ? { scope } : void 0
|
|
820
|
+
};
|
|
821
|
+
if (data["expires_in"] !== void 0) {
|
|
822
|
+
if (typeof data["expires_in"] !== "number" || !Number.isFinite(data["expires_in"]) || data["expires_in"] <= 0) throw new Error("OAuth token response returned invalid expires_in");
|
|
823
|
+
result.expiresAt = Date.now() + data["expires_in"] * 1e3;
|
|
824
|
+
}
|
|
825
|
+
if (data["refresh_token_expires_in"] !== void 0) {
|
|
826
|
+
if (typeof data["refresh_token_expires_in"] !== "number" || !Number.isFinite(data["refresh_token_expires_in"]) || data["refresh_token_expires_in"] <= 0) throw new Error("OAuth token response returned invalid refresh_token_expires_in");
|
|
827
|
+
result.refreshTokenExpiresAt = Date.now() + data["refresh_token_expires_in"] * 1e3;
|
|
828
|
+
}
|
|
829
|
+
return result;
|
|
830
|
+
}
|
|
831
|
+
async function refreshUserAccessToken(input) {
|
|
832
|
+
const request = buildOAuthTokenRequest({
|
|
833
|
+
clientId: requireEnv(input.clientIdEnv),
|
|
834
|
+
clientSecret: requireEnv(input.clientSecretEnv),
|
|
835
|
+
payload: {
|
|
836
|
+
grant_type: "refresh_token",
|
|
837
|
+
refresh_token: input.refreshToken
|
|
838
|
+
}
|
|
839
|
+
});
|
|
840
|
+
const response = await fetch("https://github.com/login/oauth/access_token", {
|
|
841
|
+
method: "POST",
|
|
842
|
+
headers: request.headers,
|
|
843
|
+
body: request.body,
|
|
844
|
+
signal: AbortSignal.timeout(USER_REFRESH_TIMEOUT_MS)
|
|
845
|
+
});
|
|
846
|
+
const responseData = parseOAuthResponseJson(await response.text());
|
|
847
|
+
const errorCode = oauthErrorCode(responseData);
|
|
848
|
+
if (isRejectedRefreshError(errorCode)) throw new GitHubUserRefreshRejectedError(`GitHub user token refresh rejected: ${errorCode}`);
|
|
849
|
+
if (!response.ok || errorCode) throw new Error(`GitHub user token refresh failed: ${response.status}${errorCode ? ` ${errorCode}` : ""}`);
|
|
850
|
+
try {
|
|
851
|
+
return parseOAuthTokenResponse(responseData, input.requestedScope);
|
|
852
|
+
} catch (error) {
|
|
853
|
+
if (error instanceof Error && error.message === "OAuth token response missing access_token") throw new GitHubUserRefreshRejectedError(error.message);
|
|
854
|
+
throw error;
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
function leaseExpiry(expiresAt) {
|
|
858
|
+
return expiresAt ? Math.min(expiresAt, Date.now() + MAX_LEASE_MS) : Date.now() + MAX_LEASE_MS;
|
|
859
|
+
}
|
|
860
|
+
function isGitSmartHttpDomain(domain) {
|
|
861
|
+
return domain.toLowerCase() === "github.com";
|
|
862
|
+
}
|
|
863
|
+
function authorizationFor(domain, token) {
|
|
864
|
+
if (isGitSmartHttpDomain(domain)) return `Basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`;
|
|
865
|
+
return `Bearer ${token}`;
|
|
866
|
+
}
|
|
867
|
+
function createCredentialLease(input) {
|
|
868
|
+
return {
|
|
869
|
+
type: "lease",
|
|
870
|
+
lease: {
|
|
871
|
+
...input.account ? { account: input.account } : void 0,
|
|
872
|
+
...input.authorization ? { authorization: input.authorization } : void 0,
|
|
873
|
+
expiresAt: new Date(input.expiresAtMs).toISOString(),
|
|
874
|
+
headerTransforms: (input.domains ?? (input.authorization ? GITHUB_ASSET_UPLOAD_CREDENTIAL_DOMAINS : GITHUB_CREDENTIAL_DOMAINS)).map((domain) => ({
|
|
875
|
+
domain,
|
|
876
|
+
headers: { Authorization: authorizationFor(domain, input.token) }
|
|
877
|
+
}))
|
|
878
|
+
}
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
function githubUserAuthorization(scope) {
|
|
882
|
+
return {
|
|
883
|
+
type: "oauth",
|
|
884
|
+
provider: "github",
|
|
885
|
+
...scope ? { scope } : void 0
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
function credentialNeeded(message, scope, allowAuthorization = true) {
|
|
889
|
+
return {
|
|
890
|
+
type: "needed",
|
|
891
|
+
message,
|
|
892
|
+
...allowAuthorization ? { authorization: githubUserAuthorization(scope) } : void 0
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
/** Return a credential result for invalid GitHub App configuration. */
|
|
896
|
+
function credentialUnavailable(message) {
|
|
897
|
+
return {
|
|
898
|
+
type: "unavailable",
|
|
899
|
+
message
|
|
900
|
+
};
|
|
901
|
+
}
|
|
902
|
+
function parseInstallationTokenResponse(data) {
|
|
903
|
+
if (!isRecord(data)) throw new Error("GitHub installation token response is invalid");
|
|
904
|
+
const token = data["token"];
|
|
905
|
+
if (typeof token !== "string" || !token.trim()) throw new Error("GitHub installation token response missing token");
|
|
906
|
+
const expiresAt = data["expires_at"];
|
|
907
|
+
const expiresAtMs = typeof expiresAt === "string" ? Date.parse(expiresAt) : NaN;
|
|
908
|
+
if (!Number.isFinite(expiresAtMs) || expiresAtMs <= Date.now()) throw new Error("GitHub installation token response returned invalid expires_at");
|
|
909
|
+
return {
|
|
910
|
+
token,
|
|
911
|
+
expiresAtMs
|
|
912
|
+
};
|
|
913
|
+
}
|
|
914
|
+
function readInstallationPermissions(installation) {
|
|
915
|
+
if (!isRecord(installation) || !isRecord(installation["permissions"])) throw new Error("GitHub installation response missing permissions");
|
|
916
|
+
return readGrantPermissions(installation["permissions"]);
|
|
917
|
+
}
|
|
918
|
+
function decodeGitHubPathSegment(value) {
|
|
919
|
+
try {
|
|
920
|
+
const decoded = decodeURIComponent(value).trim();
|
|
921
|
+
return decoded && !decoded.includes("/") ? decoded : void 0;
|
|
922
|
+
} catch {
|
|
923
|
+
return;
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
/** Parse a GitHub repository from an API or Git URL. */
|
|
927
|
+
function githubRepositoryFromUrl(upstreamUrl) {
|
|
928
|
+
const segments = upstreamUrl.pathname.split("/").filter(Boolean);
|
|
929
|
+
if (isGitHubApiUrl(upstreamUrl) && segments[0]?.toLowerCase() === "repos") {
|
|
930
|
+
const owner = segments[1] ? decodeGitHubPathSegment(segments[1]) : void 0;
|
|
931
|
+
const name = segments[2] ? decodeGitHubPathSegment(segments[2]) : void 0;
|
|
932
|
+
return owner && name ? {
|
|
933
|
+
owner,
|
|
934
|
+
name
|
|
935
|
+
} : void 0;
|
|
936
|
+
}
|
|
937
|
+
if (upstreamUrl.hostname.toLowerCase() !== "github.com") return;
|
|
938
|
+
const owner = segments[0] ? decodeGitHubPathSegment(segments[0]) : void 0;
|
|
939
|
+
const rawName = segments[1]?.replace(/\.git$/i, "");
|
|
940
|
+
const name = rawName ? decodeGitHubPathSegment(rawName) : void 0;
|
|
941
|
+
return owner && name ? {
|
|
942
|
+
owner,
|
|
943
|
+
name
|
|
944
|
+
} : void 0;
|
|
945
|
+
}
|
|
946
|
+
/** Resolve the GitHub account associated with stored user tokens. */
|
|
947
|
+
async function resolveUserAccount(tokens) {
|
|
948
|
+
const account = await githubRequest("https://api.github.com", "/user", { token: tokens.accessToken });
|
|
949
|
+
if (!isRecord(account)) throw new Error("GitHub user response is invalid");
|
|
950
|
+
const id = account["id"];
|
|
951
|
+
const login = account["login"];
|
|
952
|
+
if (typeof id !== "number" && typeof id !== "string" || typeof login !== "string" || !login.trim()) throw new Error("GitHub user response missing id or login");
|
|
953
|
+
const url = typeof account["html_url"] === "string" ? account["html_url"] : void 0;
|
|
954
|
+
return {
|
|
955
|
+
handle: login.trim(),
|
|
956
|
+
id: String(id),
|
|
957
|
+
label: login.trim(),
|
|
958
|
+
...url ? { url } : void 0
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
/**
|
|
962
|
+
* List the email addresses GitHub verified for the user OAuth token.
|
|
963
|
+
*
|
|
964
|
+
* GitHub App user tokens need the App's "Email addresses" user permission.
|
|
965
|
+
* Return an empty list when the App does not have it.
|
|
966
|
+
*/
|
|
967
|
+
async function listVerifiedUserEmails(tokens) {
|
|
968
|
+
let emails;
|
|
969
|
+
try {
|
|
970
|
+
emails = await githubRequest("https://api.github.com", "/user/emails", { token: tokens.accessToken });
|
|
971
|
+
} catch (error) {
|
|
972
|
+
if (error instanceof GitHubRequestError && (error.status === 403 || error.status === 404)) return [];
|
|
973
|
+
throw error;
|
|
974
|
+
}
|
|
975
|
+
if (!Array.isArray(emails)) throw new Error("GitHub user emails response is invalid");
|
|
976
|
+
return emails.flatMap((entry) => isRecord(entry) && entry["verified"] === true && typeof entry["email"] === "string" && entry["email"].trim() ? [entry["email"].trim()] : []);
|
|
977
|
+
}
|
|
978
|
+
async function tokensWithAccount(tokenSlot, stored, scope) {
|
|
979
|
+
if (stored.account) return {
|
|
980
|
+
ok: true,
|
|
981
|
+
tokens: stored
|
|
982
|
+
};
|
|
983
|
+
let account;
|
|
984
|
+
try {
|
|
985
|
+
account = await resolveUserAccount(stored);
|
|
986
|
+
} catch (error) {
|
|
987
|
+
if (error instanceof GitHubRequestError && (error.status === 401 || error.status === 403)) return {
|
|
988
|
+
ok: false,
|
|
989
|
+
result: credentialNeeded("Your GitHub authorization needs to be refreshed.", scope)
|
|
990
|
+
};
|
|
991
|
+
throw error;
|
|
992
|
+
}
|
|
993
|
+
const updated = {
|
|
994
|
+
...stored,
|
|
995
|
+
account
|
|
996
|
+
};
|
|
997
|
+
await tokenSlot.set(updated);
|
|
998
|
+
return {
|
|
999
|
+
ok: true,
|
|
1000
|
+
tokens: updated
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
function shouldRefreshUserToken(stored, now = Date.now()) {
|
|
1004
|
+
return stored.expiresAt !== void 0 && stored.expiresAt - now < REFRESH_BUFFER_MS;
|
|
1005
|
+
}
|
|
1006
|
+
function canUseStoredUserToken(stored) {
|
|
1007
|
+
return stored.expiresAt === void 0 || stored.expiresAt > Date.now() && !shouldRefreshUserToken(stored);
|
|
1008
|
+
}
|
|
1009
|
+
/** Re-read under the token-slot refresh gate so concurrent callers reuse the winner's rotated tokens. */
|
|
1010
|
+
async function refreshUserTokensWithLock(tokenSlot, scope, options) {
|
|
1011
|
+
return await tokenSlot.withRefresh(async () => {
|
|
1012
|
+
const latest = await tokenSlot.get();
|
|
1013
|
+
if (!latest) return {
|
|
1014
|
+
ok: false,
|
|
1015
|
+
result: credentialNeeded("Connect your GitHub account.", scope)
|
|
1016
|
+
};
|
|
1017
|
+
if (!hasRequiredOAuthScope(latest.scope, scope)) return {
|
|
1018
|
+
ok: false,
|
|
1019
|
+
result: credentialNeeded("Your GitHub authorization needs to be refreshed.", scope)
|
|
1020
|
+
};
|
|
1021
|
+
if (canUseStoredUserToken(latest)) return {
|
|
1022
|
+
ok: true,
|
|
1023
|
+
tokens: latest
|
|
1024
|
+
};
|
|
1025
|
+
let refreshed;
|
|
1026
|
+
try {
|
|
1027
|
+
refreshed = await refreshUserAccessToken({
|
|
1028
|
+
clientIdEnv: options.clientIdEnv,
|
|
1029
|
+
clientSecretEnv: options.clientSecretEnv,
|
|
1030
|
+
refreshToken: latest.refreshToken,
|
|
1031
|
+
requestedScope: latest.scope ?? scope
|
|
1032
|
+
});
|
|
1033
|
+
} catch (error) {
|
|
1034
|
+
if (!(error instanceof GitHubUserRefreshRejectedError)) throw error;
|
|
1035
|
+
return {
|
|
1036
|
+
ok: false,
|
|
1037
|
+
result: credentialNeeded("Your GitHub authorization has expired.", scope)
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
if (!hasRequiredOAuthScope(refreshed.scope, scope)) return {
|
|
1041
|
+
ok: false,
|
|
1042
|
+
result: credentialNeeded("Your GitHub authorization needs to be refreshed.", scope)
|
|
1043
|
+
};
|
|
1044
|
+
const refreshedTokens = {
|
|
1045
|
+
...latest.refreshTokenExpiresAt ? { refreshTokenExpiresAt: latest.refreshTokenExpiresAt } : void 0,
|
|
1046
|
+
...refreshed,
|
|
1047
|
+
...latest.account ? { account: latest.account } : void 0
|
|
1048
|
+
};
|
|
1049
|
+
await tokenSlot.set(refreshedTokens);
|
|
1050
|
+
return {
|
|
1051
|
+
ok: true,
|
|
1052
|
+
tokens: refreshedTokens
|
|
1053
|
+
};
|
|
1054
|
+
});
|
|
1055
|
+
}
|
|
1056
|
+
/** Issue a bounded GitHub user credential for an approved grant. */
|
|
1057
|
+
async function issueUserCredential(ctx, options) {
|
|
1058
|
+
const scope = options.userScope;
|
|
1059
|
+
const tokenSlot = ctx.tokens.currentUser ?? ctx.tokens.credentialSubject;
|
|
1060
|
+
if (!tokenSlot) return credentialNeeded("GitHub write access requires a current user or delegated user credential subject.", scope, false);
|
|
1061
|
+
const stored = await tokenSlot.get();
|
|
1062
|
+
if (!stored) return credentialNeeded("GitHub write access requires user authorization.", scope);
|
|
1063
|
+
if (!hasRequiredOAuthScope(stored.scope, scope)) return credentialNeeded("Your GitHub authorization needs to be refreshed.", scope);
|
|
1064
|
+
const now = Date.now();
|
|
1065
|
+
if (stored.expiresAt !== void 0 && stored.expiresAt - now < REFRESH_BUFFER_MS) {
|
|
1066
|
+
const refreshResult = await refreshUserTokensWithLock(tokenSlot, scope, options);
|
|
1067
|
+
if (!refreshResult.ok) return refreshResult.result;
|
|
1068
|
+
const withAccount = await tokensWithAccount(tokenSlot, refreshResult.tokens, scope);
|
|
1069
|
+
if (!withAccount.ok) return withAccount.result;
|
|
1070
|
+
return createCredentialLease({
|
|
1071
|
+
account: withAccount.tokens.account,
|
|
1072
|
+
token: withAccount.tokens.accessToken,
|
|
1073
|
+
expiresAtMs: leaseExpiry(withAccount.tokens.expiresAt),
|
|
1074
|
+
authorization: githubUserAuthorization(scope)
|
|
1075
|
+
});
|
|
1076
|
+
}
|
|
1077
|
+
if (stored.expiresAt === void 0 || stored.expiresAt > Date.now()) {
|
|
1078
|
+
const withAccount = await tokensWithAccount(tokenSlot, stored, scope);
|
|
1079
|
+
if (!withAccount.ok) return withAccount.result;
|
|
1080
|
+
return createCredentialLease({
|
|
1081
|
+
account: withAccount.tokens.account,
|
|
1082
|
+
token: withAccount.tokens.accessToken,
|
|
1083
|
+
expiresAtMs: leaseExpiry(withAccount.tokens.expiresAt),
|
|
1084
|
+
authorization: githubUserAuthorization(scope)
|
|
1085
|
+
});
|
|
1086
|
+
}
|
|
1087
|
+
return credentialNeeded("Your GitHub authorization has expired.", scope);
|
|
1088
|
+
}
|
|
1089
|
+
/** Issue a bounded raw token for plugin-owned GitHub API calls. */
|
|
1090
|
+
async function issueInstallationToken(options) {
|
|
1091
|
+
const appId = requireEnv(options.appIdEnv);
|
|
1092
|
+
const installationIdRaw = requireEnv(options.installationIdEnv);
|
|
1093
|
+
const installationId = Number(installationIdRaw);
|
|
1094
|
+
if (!Number.isSafeInteger(installationId) || installationId <= 0) throw new GitHubPluginSetupError(`Invalid ${options.installationIdEnv}`);
|
|
1095
|
+
const appJwt = createAppJwt(appId, options.privateKeyEnv);
|
|
1096
|
+
const permissions = "permissions" in options ? options.permissions : typeof options.loadPermissions === "function" ? await options.loadPermissions({
|
|
1097
|
+
appJwt,
|
|
1098
|
+
installationId
|
|
1099
|
+
}) : void 0;
|
|
1100
|
+
const repositories = "repositories" in options ? options.repositories : void 0;
|
|
1101
|
+
const repositoryIds = "repositoryIds" in options ? options.repositoryIds : void 0;
|
|
1102
|
+
const body = {
|
|
1103
|
+
...permissions ? { permissions } : void 0,
|
|
1104
|
+
...repositories ? { repositories } : void 0,
|
|
1105
|
+
...repositoryIds ? { repository_ids: repositoryIds } : void 0
|
|
1106
|
+
};
|
|
1107
|
+
const parsedToken = parseInstallationTokenResponse(await githubRequest("https://api.github.com", `/app/installations/${installationId}/access_tokens`, {
|
|
1108
|
+
method: "POST",
|
|
1109
|
+
token: appJwt,
|
|
1110
|
+
body
|
|
1111
|
+
}));
|
|
1112
|
+
return {
|
|
1113
|
+
expiresAtMs: Math.min(parsedToken.expiresAtMs, Date.now() + MAX_LEASE_MS),
|
|
1114
|
+
token: parsedToken.token
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
/** Issue a bounded GitHub App installation credential. */
|
|
1118
|
+
async function issueInstallationCredential(options) {
|
|
1119
|
+
const token = await issueInstallationToken(options);
|
|
1120
|
+
return createCredentialLease({
|
|
1121
|
+
token: token.token,
|
|
1122
|
+
expiresAtMs: token.expiresAtMs
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* Issue the credential for one GitHub grant that host egress selected. Only
|
|
1127
|
+
* the `issueCredential` hook may call this. Other code reads and writes GitHub
|
|
1128
|
+
* through host egress.
|
|
1129
|
+
*/
|
|
1130
|
+
async function issueGitHubCredential(ctx, options) {
|
|
1131
|
+
const installation = {
|
|
1132
|
+
appIdEnv: options.appIdEnv,
|
|
1133
|
+
installationIdEnv: options.installationIdEnv,
|
|
1134
|
+
privateKeyEnv: options.privateKeyEnv
|
|
1135
|
+
};
|
|
1136
|
+
try {
|
|
1137
|
+
if (ctx.grant.name === "installation-read") return await issueInstallationCredential({
|
|
1138
|
+
...installation,
|
|
1139
|
+
...options.readPermissions
|
|
1140
|
+
});
|
|
1141
|
+
if (ctx.grant.name === "installation-write") return await issueInstallationCredential(installation);
|
|
1142
|
+
if (USER_TOKEN_GRANTS.has(ctx.grant.name)) return await issueUserCredential(ctx, options);
|
|
1143
|
+
} catch (error) {
|
|
1144
|
+
if (error instanceof GitHubPluginSetupError) return credentialUnavailable(error.message);
|
|
1145
|
+
throw error;
|
|
1146
|
+
}
|
|
1147
|
+
throw new Error(`GitHub plugin cannot issue unknown grant "${ctx.grant.name}".`);
|
|
1148
|
+
}
|
|
1149
|
+
/** Cache the installation's read permissions for one lease period. */
|
|
1150
|
+
function createPermissionCache() {
|
|
1151
|
+
let cached;
|
|
1152
|
+
let pending;
|
|
1153
|
+
return async ({ appJwt, installationId }) => {
|
|
1154
|
+
if (cached && cached.expiresAtMs > Date.now()) return cached.permissions;
|
|
1155
|
+
pending ??= githubRequest("https://api.github.com", `/app/installations/${installationId}`, { token: appJwt }).then((installation) => {
|
|
1156
|
+
const permissions = readInstallationPermissions(installation);
|
|
1157
|
+
cached = {
|
|
1158
|
+
expiresAtMs: Date.now() + MAX_LEASE_MS,
|
|
1159
|
+
permissions
|
|
1160
|
+
};
|
|
1161
|
+
return permissions;
|
|
1162
|
+
}).finally(() => {
|
|
1163
|
+
pending = void 0;
|
|
1164
|
+
});
|
|
1165
|
+
return await pending;
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
// src/webhooks/event-targets.ts
|
|
1169
|
+
/**
|
|
1170
|
+
* The user who sent a webhook. GitHub authenticates this user, so on a comment
|
|
1171
|
+
* or review it is the author, and on an issue update it made the change.
|
|
1172
|
+
* Match on the numeric id; logins can be renamed and reused.
|
|
1173
|
+
*/
|
|
1174
|
+
const gitHubSenderSchema = z.object({
|
|
1175
|
+
id: z.number(),
|
|
1176
|
+
login: z.string().min(1)
|
|
1177
|
+
});
|
|
1178
|
+
/** Trusted event data that names who sent a webhook. */
|
|
1179
|
+
function gitHubSenderData(sender) {
|
|
1180
|
+
return {
|
|
1181
|
+
senderId: sender?.id,
|
|
1182
|
+
senderLogin: sender?.login
|
|
1183
|
+
};
|
|
1184
|
+
}
|
|
1185
|
+
/** The GitHub user who did what an Event describes, when GitHub names one. */
|
|
1186
|
+
function gitHubDoneBy(login) {
|
|
1187
|
+
const handle = login?.trim();
|
|
1188
|
+
return handle ? { doneBy: {
|
|
1189
|
+
provider: "github",
|
|
1190
|
+
handle
|
|
1191
|
+
} } : void 0;
|
|
1192
|
+
}
|
|
1193
|
+
/** The text of a webhook value, or undefined when it is missing or blank. */
|
|
1194
|
+
function nonBlank(value) {
|
|
1195
|
+
return value?.trim() || void 0;
|
|
1196
|
+
}
|
|
1197
|
+
/** The title and body of an issue or pull request, as untrusted text. */
|
|
1198
|
+
function titleAndBodyText(item) {
|
|
1199
|
+
const parts = [item.title ? `Title: ${item.title}` : void 0, nonBlank(item.body)].filter((part) => part !== void 0);
|
|
1200
|
+
return parts.length > 0 ? parts.join("\n\n") : void 0;
|
|
1201
|
+
}
|
|
1202
|
+
/** Convert an optional provider timestamp for receipt-time fallback ordering. */
|
|
1203
|
+
function providerTime(value) {
|
|
1204
|
+
if (!value) return void 0;
|
|
1205
|
+
const parsed = Date.parse(value);
|
|
1206
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* Drop missing values from event data. A filter on a value that GitHub did not
|
|
1210
|
+
* send then does not match.
|
|
1211
|
+
*/
|
|
1212
|
+
function definedValues(data) {
|
|
1213
|
+
return Object.fromEntries(Object.entries(data).filter(([, value]) => value !== void 0));
|
|
1214
|
+
}
|
|
1215
|
+
/** Build the event key for one event type from one webhook delivery. */
|
|
1216
|
+
function gitHubEventKey(deliveryId, eventType) {
|
|
1217
|
+
return `github:${deliveryId}:${eventType}`;
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Address a pull request event through both the pull request and its
|
|
1221
|
+
* repository. Only the pull request copy keeps `terminal`, so a terminal
|
|
1222
|
+
* event never completes a repository Watch.
|
|
1223
|
+
*/
|
|
1224
|
+
function pullRequestTargets(event, repo) {
|
|
1225
|
+
const { terminal: _terminal, ...repositoryEvent } = event;
|
|
1226
|
+
return [event, {
|
|
1227
|
+
...repositoryEvent,
|
|
1228
|
+
identifier: gitHubRepositoryResource({ repo }).identifier
|
|
1229
|
+
}];
|
|
1230
|
+
}
|
|
1231
|
+
// src/webhooks/fail-open-log.ts
|
|
1232
|
+
/**
|
|
1233
|
+
* Log a failure of optional webhook work. A GitHub 5xx is a GitHub outage,
|
|
1234
|
+
* not a Junior bug, so it is a warning with the HTTP status. Other failures
|
|
1235
|
+
* stay errors.
|
|
1236
|
+
*/
|
|
1237
|
+
function logFailOpenFailure(log, message, error, metadata) {
|
|
1238
|
+
const attributes = {
|
|
1239
|
+
...metadata,
|
|
1240
|
+
errorType: error instanceof Error ? error.name : "UnknownError"
|
|
1241
|
+
};
|
|
1242
|
+
if (error instanceof GitHubRequestError && error.status >= 500) {
|
|
1243
|
+
log?.warn(message, {
|
|
1244
|
+
...attributes,
|
|
1245
|
+
"http.response.status_code": error.status
|
|
1246
|
+
});
|
|
1247
|
+
return;
|
|
1248
|
+
}
|
|
1249
|
+
log?.error(message, attributes);
|
|
1250
|
+
}
|
|
1251
|
+
// src/webhooks/check-suite.ts
|
|
1252
|
+
/** Match keys that need a pull request API load on check suite events. */
|
|
1253
|
+
const CHECK_SUITE_PULL_REQUEST_MATCH_KEYS = /* @__PURE__ */ new Set([
|
|
1254
|
+
"isDraft",
|
|
1255
|
+
"openerEmail",
|
|
1256
|
+
"openerRole",
|
|
1257
|
+
"openerUsername"
|
|
1258
|
+
]);
|
|
1259
|
+
/**
|
|
1260
|
+
* Match keys whose values load after the webhook decides whether to read the
|
|
1261
|
+
* check suites, so a match check then cannot rule out a filter on them.
|
|
1262
|
+
*/
|
|
1263
|
+
const LATE_MATCH_KEYS = /* @__PURE__ */ new Set([...CHECK_SUITE_PULL_REQUEST_MATCH_KEYS, "authors"]);
|
|
1264
|
+
/**
|
|
1265
|
+
* Check suite pull_requests use GitHub's CheckRunPullRequest shape:
|
|
1266
|
+
* url, id, number, head/base with repo { id, url, name }.
|
|
1267
|
+
* No draft, author, or full_name on those objects.
|
|
1268
|
+
* @see https://docs.github.com/en/webhooks/webhook-events-and-payloads#check_suite
|
|
1269
|
+
*/
|
|
1270
|
+
const checkRunRepoRefSchema = z.object({
|
|
1271
|
+
id: z.number(),
|
|
1272
|
+
name: z.string().min(1),
|
|
1273
|
+
url: z.string().min(1)
|
|
1274
|
+
}).passthrough();
|
|
1275
|
+
const checkRunPullRequestSideSchema = z.object({
|
|
1276
|
+
ref: z.string().optional(),
|
|
1277
|
+
repo: checkRunRepoRefSchema,
|
|
1278
|
+
sha: z.string().optional()
|
|
1279
|
+
}).passthrough();
|
|
1280
|
+
const checkRunPullRequestSchema = z.object({
|
|
1281
|
+
base: checkRunPullRequestSideSchema,
|
|
1282
|
+
head: checkRunPullRequestSideSchema.optional(),
|
|
1283
|
+
id: z.number().optional(),
|
|
1284
|
+
number: z.number(),
|
|
1285
|
+
url: z.string().optional()
|
|
1286
|
+
}).passthrough();
|
|
1287
|
+
const repositorySchema$1 = z.object({
|
|
1288
|
+
full_name: z.string().min(1),
|
|
1289
|
+
id: z.number(),
|
|
1290
|
+
name: z.string().min(1),
|
|
1291
|
+
owner: z.object({ login: z.string().min(1) }).passthrough()
|
|
1292
|
+
}).passthrough();
|
|
1293
|
+
const checkSuiteWebhookSchema = z.object({
|
|
1294
|
+
action: z.string(),
|
|
1295
|
+
check_suite: z.object({
|
|
1296
|
+
app: z.object({
|
|
1297
|
+
name: z.string().optional().nullable(),
|
|
1298
|
+
slug: z.string().optional().nullable()
|
|
1299
|
+
}).optional().nullable(),
|
|
1300
|
+
conclusion: z.string().optional().nullable(),
|
|
1301
|
+
/** Branch name for the suite head commit when GitHub sends it. */
|
|
1302
|
+
head_branch: z.string().optional().nullable(),
|
|
1303
|
+
head_sha: z.string().optional(),
|
|
1304
|
+
id: z.number().optional(),
|
|
1305
|
+
latest_check_runs_count: z.number().optional().nullable(),
|
|
1306
|
+
pull_requests: z.array(checkRunPullRequestSchema)
|
|
1307
|
+
}),
|
|
1308
|
+
repository: repositorySchema$1
|
|
1309
|
+
});
|
|
1310
|
+
/** List check suites for a commit: { total_count, check_suites: CheckSuite[] }. */
|
|
1311
|
+
const checkSuitesListResponseSchema = z.object({
|
|
1312
|
+
check_suites: z.array(z.object({
|
|
1313
|
+
app: z.object({ slug: z.string().nullable().optional() }).nullable().optional(),
|
|
1314
|
+
conclusion: z.string().nullable().optional(),
|
|
1315
|
+
id: z.number(),
|
|
1316
|
+
latest_check_runs_count: z.number().nullable().optional(),
|
|
1317
|
+
status: z.string().nullable().optional()
|
|
1318
|
+
})),
|
|
1319
|
+
total_count: z.number()
|
|
1320
|
+
});
|
|
1321
|
+
/** List check runs in a suite: { check_runs: CheckRun[] }. */
|
|
1322
|
+
const checkRunsListResponseSchema = z.object({ check_runs: z.array(z.unknown()).optional() }).passthrough();
|
|
1323
|
+
/**
|
|
1324
|
+
* Keep only pull requests whose base repo is the check suite repository.
|
|
1325
|
+
* GitHub attaches every open PR with the same head sha, including PRs based on forks.
|
|
1326
|
+
* Compare repository ids from the webhook payload — no URL parsing.
|
|
1327
|
+
*/
|
|
1328
|
+
function isCheckSuiteRepositoryPullRequest(pullRequest, repositoryId) {
|
|
1329
|
+
return pullRequest.base.repo.id === repositoryId;
|
|
1330
|
+
}
|
|
1331
|
+
const CHECKS_PASSED = "pull_request.checks.passed";
|
|
1332
|
+
/** Suite conclusions that count as passing for `pull_request.checks.passed`. */
|
|
1333
|
+
const PASSING_SUITE_CONCLUSIONS = /* @__PURE__ */ new Set([
|
|
1334
|
+
"neutral",
|
|
1335
|
+
"skipped",
|
|
1336
|
+
"success"
|
|
1337
|
+
]);
|
|
1338
|
+
/** Pages of 100 check suites to read for one commit before giving up. */
|
|
1339
|
+
const MAX_CHECK_SUITE_PAGES = 10;
|
|
1340
|
+
/** Map a completed check suite conclusion to the event type we publish. */
|
|
1341
|
+
function checkSuiteEventType(conclusion) {
|
|
1342
|
+
if (conclusion === "failure" || conclusion === "timed_out") return "pull_request.checks.failed";
|
|
1343
|
+
if (conclusion === "success") return "pull_request.checks.recovered";
|
|
1344
|
+
}
|
|
1345
|
+
/**
|
|
1346
|
+
* Event types that a completed suite may publish. Any passing suite can be
|
|
1347
|
+
* the last one on its commit, so each one is a `pull_request.checks.passed`
|
|
1348
|
+
* candidate. The webhook keeps that event only when every suite passed.
|
|
1349
|
+
*/
|
|
1350
|
+
function checkSuiteEventTypes(conclusion) {
|
|
1351
|
+
const eventType = checkSuiteEventType(conclusion);
|
|
1352
|
+
const eventTypes = eventType ? [eventType] : [];
|
|
1353
|
+
if (PASSING_SUITE_CONCLUSIONS.has(conclusion ?? "")) eventTypes.push(CHECKS_PASSED);
|
|
1354
|
+
return eventTypes;
|
|
1355
|
+
}
|
|
1356
|
+
/** True when a GitHub API call failed with HTTP 404. */
|
|
1357
|
+
function isGitHubNotFoundError(error) {
|
|
1358
|
+
return error instanceof Error && error.name === "GitHubRequestError" && "status" in error && error.status === 404;
|
|
1359
|
+
}
|
|
1360
|
+
const FAILING_CHECK_CONCLUSIONS = /* @__PURE__ */ new Set([
|
|
1361
|
+
"failure",
|
|
1362
|
+
"timed_out",
|
|
1363
|
+
"cancelled",
|
|
1364
|
+
"action_required",
|
|
1365
|
+
"startup_failure"
|
|
1366
|
+
]);
|
|
1367
|
+
/** Build a browser URL for one check suite. GitHub does not send html_url. */
|
|
1368
|
+
function buildCheckSuiteUrl(args) {
|
|
1369
|
+
return `https://github.com/${args.repo}/commit/${args.headSha}/checks?check_suite_id=${args.checkSuiteId}`;
|
|
1370
|
+
}
|
|
1371
|
+
/** Collapse provider free text into one short summary fragment. */
|
|
1372
|
+
function oneLineLabel(value, maxLength = 80) {
|
|
1373
|
+
return value.replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").trim().slice(0, maxLength);
|
|
1374
|
+
}
|
|
1375
|
+
/** Non-empty branch name from a webhook string. */
|
|
1376
|
+
function checkSuiteHeadBranch(value) {
|
|
1377
|
+
const branch = value?.trim();
|
|
1378
|
+
return branch ? branch : void 0;
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* Trusted data on every check suite event. `pullRequest` is missing when
|
|
1382
|
+
* GitHub links the suite to no pull request, such as on the main branch.
|
|
1383
|
+
* `commitSha` is missing when GitHub sends no full SHA. `suiteConclusion`
|
|
1384
|
+
* stays as a detail, not a filter: the event type already tells failed from
|
|
1385
|
+
* recovered.
|
|
1386
|
+
*/
|
|
1387
|
+
const checkSuiteEventDataSchema = z.object({
|
|
1388
|
+
repo: gitHubRepoDataSchema,
|
|
1389
|
+
pullRequest: z.number().optional(),
|
|
1390
|
+
commitSha: gitHubCommitShaDataSchema.optional(),
|
|
1391
|
+
suiteConclusion: z.string().min(1),
|
|
1392
|
+
isDraft: z.boolean().optional(),
|
|
1393
|
+
openerUsername: z.string().min(1).optional(),
|
|
1394
|
+
openerEmail: z.string().min(1).optional(),
|
|
1395
|
+
headBranch: z.string().min(1).optional(),
|
|
1396
|
+
checkSuiteId: z.number().optional(),
|
|
1397
|
+
checkSuiteUrl: z.string().min(1).optional(),
|
|
1398
|
+
appName: z.string().min(1).optional(),
|
|
1399
|
+
latestCheckRunsCount: z.number().optional(),
|
|
1400
|
+
failingChecks: z.array(z.object({
|
|
1401
|
+
conclusion: z.string(),
|
|
1402
|
+
htmlUrl: z.string().optional(),
|
|
1403
|
+
checkRunId: z.number()
|
|
1404
|
+
}).strict()).optional()
|
|
1405
|
+
}).strict();
|
|
1406
|
+
/** Build the trusted data and summary for one check-suite event. */
|
|
1407
|
+
function buildCheckSuiteEvent(args) {
|
|
1408
|
+
const pullRequestNumber = args.pullRequestNumber;
|
|
1409
|
+
const resource = pullRequestNumber === void 0 ? gitHubRepositoryResource({ repo: args.repo }) : gitHubPullRequestResource({
|
|
1410
|
+
number: pullRequestNumber,
|
|
1411
|
+
repo: args.repo
|
|
1412
|
+
});
|
|
1413
|
+
const shortSha = args.headSha?.slice(0, 12);
|
|
1414
|
+
const failingChecks = (args.failingChecks ?? []).slice(0, 12);
|
|
1415
|
+
const failingCount = failingChecks.length;
|
|
1416
|
+
const branchSuffix = args.headBranch ? ` on ${args.headBranch}` : "";
|
|
1417
|
+
const incidents = args.eventType === "pull_request.checks.failed" ? args.githubIncidents ?? [] : [];
|
|
1418
|
+
const incidentSuffix = incidents.length > 0 ? ` githubstatus.com lists ${incidents.length} open or recent GitHub incident${incidents.length === 1 ? "" : "s"}.` : "";
|
|
1419
|
+
const shaSuffix = shortSha ? ` for ${shortSha}` : "";
|
|
1420
|
+
const trustedSummary = args.eventType === "pull_request.checks.failed" ? `${resource.label} checks failed${failingCount > 0 ? ` (${failingCount})` : ""}${shaSuffix}${branchSuffix}.${incidentSuffix}` : args.eventType === CHECKS_PASSED ? `${resource.label} all check suites passed${shaSuffix}${branchSuffix}.` : `${resource.label} check suite recovered${shaSuffix}${branchSuffix}.`;
|
|
1421
|
+
const data = checkSuiteEventDataSchema.parse(definedValues({
|
|
1422
|
+
repo: args.repo,
|
|
1423
|
+
pullRequest: pullRequestNumber,
|
|
1424
|
+
commitSha: gitHubCommitShaDataSchema.safeParse(args.headSha).data,
|
|
1425
|
+
suiteConclusion: args.suiteConclusion,
|
|
1426
|
+
isDraft: args.isDraft,
|
|
1427
|
+
openerUsername: args.openerUsername,
|
|
1428
|
+
openerEmail: args.openerEmail,
|
|
1429
|
+
headBranch: args.headBranch,
|
|
1430
|
+
checkSuiteId: args.checkSuiteId,
|
|
1431
|
+
checkSuiteUrl: args.checkSuiteId !== void 0 && args.headSha ? buildCheckSuiteUrl({
|
|
1432
|
+
checkSuiteId: args.checkSuiteId,
|
|
1433
|
+
headSha: args.headSha,
|
|
1434
|
+
repo: args.repo
|
|
1435
|
+
}) : void 0,
|
|
1436
|
+
appName: args.appName ? oneLineLabel(args.appName, 120) : void 0,
|
|
1437
|
+
latestCheckRunsCount: args.latestCheckRunsCount,
|
|
1438
|
+
failingChecks: args.eventType === "pull_request.checks.failed" && failingCount > 0 ? failingChecks.map((check) => ({
|
|
1439
|
+
conclusion: check.conclusion,
|
|
1440
|
+
...check.htmlUrl ? { htmlUrl: check.htmlUrl } : void 0,
|
|
1441
|
+
checkRunId: check.checkRunId
|
|
1442
|
+
})) : void 0
|
|
1443
|
+
}));
|
|
1444
|
+
const untrustedParts = args.eventType === "pull_request.checks.failed" ? failingChecks.map((check) => {
|
|
1445
|
+
const name = oneLineLabel(check.name);
|
|
1446
|
+
if (!name) return void 0;
|
|
1447
|
+
return check.htmlUrl ? `${name}: ${check.htmlUrl}` : name;
|
|
1448
|
+
}).filter((part) => part !== void 0) : [];
|
|
1449
|
+
const untrustedSections = [...untrustedParts.length > 0 ? [[`Failed checks:`, ...untrustedParts.map((part) => `- ${part}`)].join("\n")] : [], ...incidents.length > 0 ? [["GitHub status incidents:", ...incidents.map((incident) => `- ${oneLineLabel(incident.name, 160)} (${incident.status}; ${incident.components.join(", ") || "no components"}; started ${incident.startedAt}${incident.resolvedAt ? `, resolved ${incident.resolvedAt}` : ""}): ${incident.url}`)].join("\n")] : []];
|
|
1450
|
+
const untrustedText = untrustedSections.length > 0 ? untrustedSections.join("\n\n") : void 0;
|
|
1451
|
+
return {
|
|
1452
|
+
eventKey: args.eventType === CHECKS_PASSED && args.headSha ? `github:${CHECKS_PASSED}:${resource.identifier}:${args.headSha.toLowerCase()}` : gitHubEventKey(args.deliveryId, pullRequestNumber === void 0 ? args.eventType : `${args.eventType}:${pullRequestNumber}`),
|
|
1453
|
+
eventType: args.eventType,
|
|
1454
|
+
occurredAtMs: Date.now(),
|
|
1455
|
+
identifier: resource.identifier,
|
|
1456
|
+
trustedSummary,
|
|
1457
|
+
data,
|
|
1458
|
+
...untrustedText ? { untrustedText } : void 0
|
|
1459
|
+
};
|
|
1460
|
+
}
|
|
1461
|
+
/** Keep only failed check runs from one suite. */
|
|
1462
|
+
function selectFailingChecks(checkRuns, options) {
|
|
1463
|
+
if (!Array.isArray(checkRuns)) return [];
|
|
1464
|
+
const failing = [];
|
|
1465
|
+
for (const run of checkRuns) {
|
|
1466
|
+
if (!run || typeof run !== "object" || Array.isArray(run)) continue;
|
|
1467
|
+
const record = run;
|
|
1468
|
+
if (options?.checkSuiteId !== void 0) {
|
|
1469
|
+
const suite = record["check_suite"];
|
|
1470
|
+
const suiteId = suite && typeof suite === "object" && !Array.isArray(suite) && typeof suite.id === "number" ? suite.id : void 0;
|
|
1471
|
+
if (suiteId !== void 0 && suiteId !== options.checkSuiteId) continue;
|
|
1472
|
+
}
|
|
1473
|
+
const conclusion = typeof record["conclusion"] === "string" ? record["conclusion"] : void 0;
|
|
1474
|
+
const name = typeof record["name"] === "string" ? record["name"].trim() : "";
|
|
1475
|
+
const checkRunId = typeof record["id"] === "number" && Number.isSafeInteger(record["id"]) ? record["id"] : void 0;
|
|
1476
|
+
if (!conclusion || !FAILING_CHECK_CONCLUSIONS.has(conclusion)) continue;
|
|
1477
|
+
if (!name || checkRunId === void 0) continue;
|
|
1478
|
+
const htmlUrl = typeof record["html_url"] === "string" && record["html_url"].length > 0 ? record["html_url"] : void 0;
|
|
1479
|
+
failing.push({
|
|
1480
|
+
checkRunId,
|
|
1481
|
+
conclusion,
|
|
1482
|
+
...htmlUrl ? { htmlUrl } : void 0,
|
|
1483
|
+
name
|
|
1484
|
+
});
|
|
1485
|
+
}
|
|
1486
|
+
return failing.slice(0, 12);
|
|
1487
|
+
}
|
|
1488
|
+
/** Normalize a completed check suite for attached PRs, or the repository alone. */
|
|
1489
|
+
function normalizeCheckSuiteEvents(deliveryId, body, options) {
|
|
1490
|
+
const parsed = checkSuiteWebhookSchema.safeParse(body);
|
|
1491
|
+
if (!parsed.success || parsed.data.action !== "completed") return [];
|
|
1492
|
+
const conclusion = parsed.data.check_suite.conclusion;
|
|
1493
|
+
const eventType = checkSuiteEventType(conclusion);
|
|
1494
|
+
const eventTypes = checkSuiteEventTypes(conclusion).filter((type) => type !== CHECKS_PASSED || options?.allCheckSuitesPassed);
|
|
1495
|
+
if (eventTypes.length === 0 || typeof conclusion !== "string") return [];
|
|
1496
|
+
const suite = parsed.data.check_suite;
|
|
1497
|
+
const appName = suite.app?.name?.trim() || suite.app?.slug?.trim() || void 0;
|
|
1498
|
+
const headBranch = checkSuiteHeadBranch(suite.head_branch);
|
|
1499
|
+
const headSha = typeof suite.head_sha === "string" && /^[0-9a-f]{7,40}$/i.test(suite.head_sha) ? suite.head_sha : void 0;
|
|
1500
|
+
const repository = parsed.data.repository;
|
|
1501
|
+
const repo = repository.full_name;
|
|
1502
|
+
const shared = {
|
|
1503
|
+
appName,
|
|
1504
|
+
checkSuiteId: suite.id,
|
|
1505
|
+
deliveryId,
|
|
1506
|
+
failingChecks: eventType === "pull_request.checks.failed" ? options?.failingChecks : void 0,
|
|
1507
|
+
githubIncidents: eventType === "pull_request.checks.failed" ? options?.githubIncidents : void 0,
|
|
1508
|
+
headSha,
|
|
1509
|
+
latestCheckRunsCount: typeof suite.latest_check_runs_count === "number" ? suite.latest_check_runs_count : void 0,
|
|
1510
|
+
repo,
|
|
1511
|
+
suiteConclusion: conclusion
|
|
1512
|
+
};
|
|
1513
|
+
const sameRepoPullRequests = suite.pull_requests.filter((pullRequest) => isCheckSuiteRepositoryPullRequest(pullRequest, repository.id));
|
|
1514
|
+
if (sameRepoPullRequests.length === 0) return eventTypes.map((type) => buildCheckSuiteEvent({
|
|
1515
|
+
...shared,
|
|
1516
|
+
eventType: type,
|
|
1517
|
+
...headBranch ? { headBranch } : void 0
|
|
1518
|
+
}));
|
|
1519
|
+
return eventTypes.flatMap((type) => sameRepoPullRequests.flatMap((pullRequest) => {
|
|
1520
|
+
const facts = options?.pullRequestFactsByNumber?.[pullRequest.number];
|
|
1521
|
+
const pullRequestHeadBranch = checkSuiteHeadBranch(pullRequest.head?.ref) ?? headBranch;
|
|
1522
|
+
return pullRequestTargets(buildCheckSuiteEvent({
|
|
1523
|
+
...shared,
|
|
1524
|
+
eventType: type,
|
|
1525
|
+
...facts?.openerEmail ? { openerEmail: facts.openerEmail } : void 0,
|
|
1526
|
+
...facts?.openerUsername ? { openerUsername: facts.openerUsername } : void 0,
|
|
1527
|
+
...pullRequestHeadBranch ? { headBranch: pullRequestHeadBranch } : void 0,
|
|
1528
|
+
...typeof facts?.isDraft === "boolean" ? { isDraft: facts.isDraft } : void 0,
|
|
1529
|
+
pullRequestNumber: pullRequest.number
|
|
1530
|
+
}), repo);
|
|
1531
|
+
}));
|
|
1532
|
+
}
|
|
1533
|
+
/** The same-repository pull requests of one completed check suite. */
|
|
1534
|
+
function checkSuitePullRequests(body) {
|
|
1535
|
+
const parsed = checkSuiteWebhookSchema.safeParse(body);
|
|
1536
|
+
if (!parsed.success || parsed.data.action !== "completed") return [];
|
|
1537
|
+
const repository = parsed.data.repository;
|
|
1538
|
+
return parsed.data.check_suite.pull_requests.filter((pullRequest) => isCheckSuiteRepositoryPullRequest(pullRequest, repository.id)).map((pullRequest) => ({
|
|
1539
|
+
number: pullRequest.number,
|
|
1540
|
+
repositoryFullName: repository.full_name
|
|
1541
|
+
}));
|
|
1542
|
+
}
|
|
1543
|
+
/** Identifiers and event types one completed check suite may publish. */
|
|
1544
|
+
function parseCheckSuitePublishTargets(body) {
|
|
1545
|
+
const parsed = checkSuiteWebhookSchema.safeParse(body);
|
|
1546
|
+
if (!parsed.success || parsed.data.action !== "completed") return void 0;
|
|
1547
|
+
const eventTypes = checkSuiteEventTypes(parsed.data.check_suite.conclusion);
|
|
1548
|
+
if (eventTypes.length === 0) return void 0;
|
|
1549
|
+
const repository = parsed.data.repository;
|
|
1550
|
+
const repo = repository.full_name;
|
|
1551
|
+
const identifiers = /* @__PURE__ */ new Set([gitHubRepositoryResource({ repo }).identifier]);
|
|
1552
|
+
for (const pullRequest of parsed.data.check_suite.pull_requests) {
|
|
1553
|
+
if (!isCheckSuiteRepositoryPullRequest(pullRequest, repository.id)) continue;
|
|
1554
|
+
identifiers.add(gitHubPullRequestResource({
|
|
1555
|
+
number: pullRequest.number,
|
|
1556
|
+
repo
|
|
1557
|
+
}).identifier);
|
|
1558
|
+
}
|
|
1559
|
+
return {
|
|
1560
|
+
data: { repo: gitHubRepoDataSchema.parse(repo) },
|
|
1561
|
+
eventTypes,
|
|
1562
|
+
identifiers: [...identifiers]
|
|
1563
|
+
};
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* True when a Watch or event automation may want `pull_request.checks.passed`
|
|
1567
|
+
* for this check suite, so the webhook reads the other suites on the commit
|
|
1568
|
+
* only then. A filter on a value that loads later counts as a match, so the
|
|
1569
|
+
* check never drops an Event that someone wants.
|
|
1570
|
+
*/
|
|
1571
|
+
async function wantsCheckSuitePassed(args) {
|
|
1572
|
+
const targets = parseCheckSuitePublishTargets(args.body);
|
|
1573
|
+
if (!args.hasMatch || !targets?.eventTypes.includes(CHECKS_PASSED)) return false;
|
|
1574
|
+
if ((await args.neededMatchKeys?.({
|
|
1575
|
+
...targets,
|
|
1576
|
+
eventTypes: [CHECKS_PASSED]
|
|
1577
|
+
}) ?? []).some((key) => LATE_MATCH_KEYS.has(key))) return true;
|
|
1578
|
+
return await args.hasMatch(normalizeCheckSuiteEvents(args.deliveryId, args.body, { allCheckSuitesPassed: true }).filter((event) => event.eventType === CHECKS_PASSED));
|
|
1579
|
+
}
|
|
1580
|
+
/** Read which check suite values still need a GitHub API load. */
|
|
1581
|
+
function parseCheckSuiteFactsTarget(body, options) {
|
|
1582
|
+
const parsed = checkSuiteWebhookSchema.safeParse(body);
|
|
1583
|
+
if (!parsed.success || parsed.data.action !== "completed") return void 0;
|
|
1584
|
+
const conclusion = parsed.data.check_suite.conclusion;
|
|
1585
|
+
if (checkSuiteEventTypes(conclusion).length === 0) return void 0;
|
|
1586
|
+
const headSha = parsed.data.check_suite.head_sha;
|
|
1587
|
+
const checkSuiteId = parsed.data.check_suite.id;
|
|
1588
|
+
if (typeof headSha !== "string" || !/^[0-9a-f]{7,40}$/i.test(headSha) || typeof checkSuiteId !== "number") return;
|
|
1589
|
+
const repository = parsed.data.repository;
|
|
1590
|
+
const pullRequestNumbers = [...new Set(parsed.data.check_suite.pull_requests.filter((pullRequest) => isCheckSuiteRepositoryPullRequest(pullRequest, repository.id)).map((pullRequest) => pullRequest.number))];
|
|
1591
|
+
const loadFailingChecks = conclusion === "failure" || conclusion === "timed_out";
|
|
1592
|
+
const loadPullRequestFacts = Boolean(options?.loadPullRequestFacts && pullRequestNumbers.length > 0);
|
|
1593
|
+
const loadCheckSuites = Boolean(options?.loadCheckSuites && PASSING_SUITE_CONCLUSIONS.has(conclusion ?? ""));
|
|
1594
|
+
if (!loadFailingChecks && !loadPullRequestFacts && !loadCheckSuites) return;
|
|
1595
|
+
return {
|
|
1596
|
+
checkSuiteId,
|
|
1597
|
+
headSha,
|
|
1598
|
+
loadCheckSuites,
|
|
1599
|
+
loadFailingChecks,
|
|
1600
|
+
loadPullRequestFacts,
|
|
1601
|
+
owner: repository.owner.login,
|
|
1602
|
+
pullRequestNumbers,
|
|
1603
|
+
repoName: repository.name
|
|
1604
|
+
};
|
|
1605
|
+
}
|
|
1606
|
+
function checkRunsFromResponse(value) {
|
|
1607
|
+
const parsed = checkRunsListResponseSchema.safeParse(value);
|
|
1608
|
+
if (!parsed.success) return [];
|
|
1609
|
+
return parsed.data.check_runs ?? [];
|
|
1610
|
+
}
|
|
1611
|
+
function pullRequestFactsFromResponse(value) {
|
|
1612
|
+
if (!isRecord(value)) return void 0;
|
|
1613
|
+
const facts = {};
|
|
1614
|
+
if (typeof value["draft"] === "boolean") facts.isDraft = value["draft"];
|
|
1615
|
+
const user = value["user"];
|
|
1616
|
+
if (isRecord(user)) {
|
|
1617
|
+
const username = typeof user["login"] === "string" ? user["login"].trim() : void 0;
|
|
1618
|
+
if (username) facts.openerUsername = username;
|
|
1619
|
+
const email = typeof user["email"] === "string" ? user["email"].trim() : void 0;
|
|
1620
|
+
if (email) facts.openerEmail = email;
|
|
1621
|
+
}
|
|
1622
|
+
return Object.keys(facts).length > 0 ? facts : void 0;
|
|
1623
|
+
}
|
|
1624
|
+
/** True when active match filters need pull request fields from the API. */
|
|
1625
|
+
function needsCheckSuitePullRequestFacts(matchKeys) {
|
|
1626
|
+
for (const key of matchKeys) if (CHECK_SUITE_PULL_REQUEST_MATCH_KEYS.has(key)) return true;
|
|
1627
|
+
return false;
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* Read every check suite on one commit and return whether all of them passed.
|
|
1631
|
+
* The suite that sent the webhook already passed. GitHub makes a queued suite
|
|
1632
|
+
* for each app that can write checks, even when the app never adds a check
|
|
1633
|
+
* run, so a queued suite with no check runs does not count. GitHub Actions
|
|
1634
|
+
* makes a suite only for a workflow that runs, and its suite can be queued
|
|
1635
|
+
* before it adds runs, so its suites always count. With more suites than the
|
|
1636
|
+
* pages read, the answer is false.
|
|
1637
|
+
*/
|
|
1638
|
+
async function loadAllCheckSuitesPassed(args) {
|
|
1639
|
+
const suites = [];
|
|
1640
|
+
let totalCount = 0;
|
|
1641
|
+
for (let page = 1; page <= MAX_CHECK_SUITE_PAGES; page += 1) {
|
|
1642
|
+
const response = checkSuitesListResponseSchema.parse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repoName)}/commits/${args.headSha}/check-suites?per_page=100&page=${page}`, { token: args.token }));
|
|
1643
|
+
suites.push(...response.check_suites);
|
|
1644
|
+
totalCount = response.total_count;
|
|
1645
|
+
if (suites.length >= totalCount || response.check_suites.length === 0) break;
|
|
1646
|
+
}
|
|
1647
|
+
if (suites.length < totalCount) return false;
|
|
1648
|
+
return suites.every((suite) => suite.id === args.checkSuiteId || suite.status === "queued" && suite.latest_check_runs_count === 0 && suite.app?.slug !== "github-actions" || suite.status === "completed" && PASSING_SUITE_CONCLUSIONS.has(suite.conclusion ?? ""));
|
|
1649
|
+
}
|
|
1650
|
+
/**
|
|
1651
|
+
* Load failed check runs, whether every check suite on the commit passed,
|
|
1652
|
+
* and optional pull request match fields.
|
|
1653
|
+
*/
|
|
1654
|
+
async function loadCheckSuiteFacts(args) {
|
|
1655
|
+
const target = parseCheckSuiteFactsTarget(args.body, {
|
|
1656
|
+
loadCheckSuites: args.loadCheckSuites,
|
|
1657
|
+
loadPullRequestFacts: args.loadPullRequestFacts
|
|
1658
|
+
});
|
|
1659
|
+
if (!target) return void 0;
|
|
1660
|
+
const facts = {};
|
|
1661
|
+
if (target.loadFailingChecks) try {
|
|
1662
|
+
const token = await issueInstallationToken({
|
|
1663
|
+
appIdEnv: args.appIdEnv,
|
|
1664
|
+
installationIdEnv: args.installationIdEnv,
|
|
1665
|
+
permissions: { checks: "read" },
|
|
1666
|
+
privateKeyEnv: args.privateKeyEnv,
|
|
1667
|
+
repositories: [target.repoName]
|
|
1668
|
+
});
|
|
1669
|
+
const failing = selectFailingChecks(checkRunsFromResponse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/check-suites/${target.checkSuiteId}/check-runs?filter=latest&per_page=100`, { token: token.token })), { checkSuiteId: target.checkSuiteId });
|
|
1670
|
+
if (failing.length > 0) facts.failingChecks = failing;
|
|
1671
|
+
} catch (error) {
|
|
1672
|
+
logFailOpenFailure(args.log, "GitHub check suite load failed", error, {
|
|
1673
|
+
checkSuiteId: target.checkSuiteId,
|
|
1674
|
+
repository: `${target.owner}/${target.repoName}`
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
if (target.loadCheckSuites) try {
|
|
1678
|
+
const token = await issueInstallationToken({
|
|
1679
|
+
appIdEnv: args.appIdEnv,
|
|
1680
|
+
installationIdEnv: args.installationIdEnv,
|
|
1681
|
+
permissions: { checks: "read" },
|
|
1682
|
+
privateKeyEnv: args.privateKeyEnv,
|
|
1683
|
+
repositories: [target.repoName]
|
|
1684
|
+
});
|
|
1685
|
+
if (await loadAllCheckSuitesPassed({
|
|
1686
|
+
checkSuiteId: target.checkSuiteId,
|
|
1687
|
+
headSha: target.headSha,
|
|
1688
|
+
owner: target.owner,
|
|
1689
|
+
repoName: target.repoName,
|
|
1690
|
+
token: token.token
|
|
1691
|
+
})) facts.allCheckSuitesPassed = true;
|
|
1692
|
+
} catch (error) {
|
|
1693
|
+
logFailOpenFailure(args.log, "GitHub commit check suites load failed", error, {
|
|
1694
|
+
checkSuiteId: target.checkSuiteId,
|
|
1695
|
+
repository: `${target.owner}/${target.repoName}`
|
|
1696
|
+
});
|
|
1697
|
+
}
|
|
1698
|
+
if (target.loadFailingChecks && args.loadGitHubIncidents) try {
|
|
1699
|
+
const incidents = await args.loadGitHubIncidents();
|
|
1700
|
+
if (incidents.length > 0) facts.githubIncidents = incidents;
|
|
1701
|
+
} catch (error) {
|
|
1702
|
+
logFailOpenFailure(args.log, "GitHub status load failed", error, {});
|
|
1703
|
+
}
|
|
1704
|
+
if (target.loadPullRequestFacts) try {
|
|
1705
|
+
const token = await issueInstallationToken({
|
|
1706
|
+
appIdEnv: args.appIdEnv,
|
|
1707
|
+
installationIdEnv: args.installationIdEnv,
|
|
1708
|
+
permissions: { pull_requests: "read" },
|
|
1709
|
+
privateKeyEnv: args.privateKeyEnv,
|
|
1710
|
+
repositories: [target.repoName]
|
|
1711
|
+
});
|
|
1712
|
+
const loaded = await Promise.all(target.pullRequestNumbers.map(async (number) => {
|
|
1713
|
+
try {
|
|
1714
|
+
const loadedFacts = pullRequestFactsFromResponse(await githubRequest("https://api.github.com", `/repos/${encodeURIComponent(target.owner)}/${encodeURIComponent(target.repoName)}/pulls/${number}`, { token: token.token }));
|
|
1715
|
+
return loadedFacts ? [number, loadedFacts] : void 0;
|
|
1716
|
+
} catch (error) {
|
|
1717
|
+
if (!isGitHubNotFoundError(error)) logFailOpenFailure(args.log, "GitHub pull request data load failed", error, {
|
|
1718
|
+
pullRequest: number,
|
|
1719
|
+
repository: `${target.owner}/${target.repoName}`
|
|
1720
|
+
});
|
|
1721
|
+
return;
|
|
1722
|
+
}
|
|
1723
|
+
}));
|
|
1724
|
+
const pullRequestFactsByNumber = {};
|
|
1725
|
+
for (const entry of loaded) {
|
|
1726
|
+
if (!entry) continue;
|
|
1727
|
+
pullRequestFactsByNumber[entry[0]] = entry[1];
|
|
1728
|
+
}
|
|
1729
|
+
if (Object.keys(pullRequestFactsByNumber).length > 0) facts.pullRequestFactsByNumber = pullRequestFactsByNumber;
|
|
1730
|
+
} catch (error) {
|
|
1731
|
+
logFailOpenFailure(args.log, "GitHub check suite pull request data load failed", error, {
|
|
1732
|
+
checkSuiteId: target.checkSuiteId,
|
|
1733
|
+
repository: `${target.owner}/${target.repoName}`
|
|
1734
|
+
});
|
|
1735
|
+
}
|
|
1736
|
+
return facts.failingChecks || facts.allCheckSuitesPassed || facts.pullRequestFactsByNumber ? facts : void 0;
|
|
1737
|
+
}
|
|
1738
|
+
// src/webhooks/issue-update.ts
|
|
1739
|
+
const issueUpdateWebhookSchema = z.object({
|
|
1740
|
+
action: z.enum(GITHUB_ISSUE_UPDATE_CHANGES),
|
|
1741
|
+
assignee: z.object({ login: z.string().nullish() }).nullish(),
|
|
1742
|
+
changes: z.record(z.string(), z.unknown()).optional(),
|
|
1743
|
+
issue: z.object({
|
|
1744
|
+
body: z.string().optional().nullable(),
|
|
1745
|
+
number: z.number(),
|
|
1746
|
+
title: z.string().optional(),
|
|
1747
|
+
updated_at: z.string().optional()
|
|
1748
|
+
}),
|
|
1749
|
+
label: z.object({ name: z.string() }).nullish(),
|
|
1750
|
+
milestone: z.object({ title: z.string() }).nullish(),
|
|
1751
|
+
repository: z.object({ full_name: z.string().min(1) }),
|
|
1752
|
+
sender: gitHubSenderSchema.optional()
|
|
1753
|
+
});
|
|
1754
|
+
/**
|
|
1755
|
+
* Describe what an `issues` update action changed. `change` is trusted text:
|
|
1756
|
+
* GitHub logins and field names only. Label and milestone names are
|
|
1757
|
+
* repository-controlled text, so they stay out of `change` and go in
|
|
1758
|
+
* `untrustedText`. Event data also carries the lowercase label name as a
|
|
1759
|
+
* match value; only people with repository write access create labels.
|
|
1760
|
+
*/
|
|
1761
|
+
function describeIssueUpdate(delivery) {
|
|
1762
|
+
const assignee = nonBlank(delivery.assignee?.login);
|
|
1763
|
+
switch (delivery.action) {
|
|
1764
|
+
case "edited": {
|
|
1765
|
+
const fields = ["title", "body"].filter((field) => field in (delivery.changes ?? {}));
|
|
1766
|
+
return { change: fields.length ? `edited (${fields.join(", ")})` : "edited" };
|
|
1767
|
+
}
|
|
1768
|
+
case "labeled":
|
|
1769
|
+
case "unlabeled": return {
|
|
1770
|
+
change: delivery.action,
|
|
1771
|
+
untrustedText: delivery.label ? `Label: ${delivery.label.name}` : void 0
|
|
1772
|
+
};
|
|
1773
|
+
case "assigned": return { change: assignee ? `assigned to ${assignee}` : "assigned" };
|
|
1774
|
+
case "unassigned": return { change: assignee ? `unassigned from ${assignee}` : "unassigned" };
|
|
1775
|
+
case "milestoned":
|
|
1776
|
+
case "demilestoned": return {
|
|
1777
|
+
change: delivery.action,
|
|
1778
|
+
untrustedText: delivery.milestone ? `Milestone: ${delivery.milestone.title}` : void 0
|
|
1779
|
+
};
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
/**
|
|
1783
|
+
* Normalize an issue edit, label, assignee, or milestone change into
|
|
1784
|
+
* `issue.updated` for the issue and its repository. Return undefined when the
|
|
1785
|
+
* delivery is not one of these updates. Changes that the bot makes publish
|
|
1786
|
+
* nothing, so Junior's own issue updates do not wake its Watches.
|
|
1787
|
+
*/
|
|
1788
|
+
function normalizeIssueUpdateEvents(deliveryId, body, botEmail) {
|
|
1789
|
+
const parsed = issueUpdateWebhookSchema.safeParse(body);
|
|
1790
|
+
if (!parsed.success) return void 0;
|
|
1791
|
+
const update = describeIssueUpdate(parsed.data);
|
|
1792
|
+
const { action, label, sender } = parsed.data;
|
|
1793
|
+
const doneBy = sender?.login;
|
|
1794
|
+
if (isBotLogin(doneBy, botEmail)) return [];
|
|
1795
|
+
const input = {
|
|
1796
|
+
number: parsed.data.issue.number,
|
|
1797
|
+
repo: parsed.data.repository.full_name
|
|
1798
|
+
};
|
|
1799
|
+
const issue = gitHubIssueResource(input);
|
|
1800
|
+
const untrustedText = [update.untrustedText, titleAndBodyText(parsed.data.issue)].filter((part) => part !== void 0).join("\n\n");
|
|
1801
|
+
return [issue, gitHubRepositoryResource(input)].map((resource) => ({
|
|
1802
|
+
eventKey: gitHubEventKey(deliveryId, "issue.updated"),
|
|
1803
|
+
eventType: "issue.updated",
|
|
1804
|
+
occurredAtMs: providerTime(parsed.data.issue.updated_at) ?? Date.now(),
|
|
1805
|
+
identifier: resource.identifier,
|
|
1806
|
+
trustedSummary: `${issue.label} was ${update.change}${doneBy ? ` by ${doneBy}` : ""}.`,
|
|
1807
|
+
...gitHubDoneBy(doneBy),
|
|
1808
|
+
data: definedValues({
|
|
1809
|
+
repo: gitHubRepoDataSchema.parse(input.repo),
|
|
1810
|
+
issue: input.number,
|
|
1811
|
+
change: action,
|
|
1812
|
+
label: label?.name.toLowerCase(),
|
|
1813
|
+
...gitHubSenderData(sender)
|
|
1814
|
+
}),
|
|
1815
|
+
...untrustedText ? { untrustedText } : void 0
|
|
1816
|
+
}));
|
|
1817
|
+
}
|
|
1818
|
+
// src/webhooks/events.ts
|
|
1819
|
+
const repositorySchema = z.object({ full_name: z.string().min(1) }).passthrough();
|
|
1820
|
+
const deploymentSchema = z.object({
|
|
1821
|
+
created_at: z.string().optional(),
|
|
1822
|
+
environment: z.string().trim().min(1),
|
|
1823
|
+
id: z.number(),
|
|
1824
|
+
sha: z.string().regex(/^[0-9a-f]{40}$/i)
|
|
1825
|
+
}).passthrough();
|
|
1826
|
+
const deploymentWorkflowSchema = {
|
|
1827
|
+
workflow: z.object({
|
|
1828
|
+
id: z.number(),
|
|
1829
|
+
path: z.string().min(1)
|
|
1830
|
+
}).passthrough().nullish(),
|
|
1831
|
+
workflow_run: z.object({ id: z.number() }).passthrough().nullish()
|
|
1832
|
+
};
|
|
1833
|
+
const deploymentWebhookSchema = z.object({
|
|
1834
|
+
action: z.string(),
|
|
1835
|
+
deployment: deploymentSchema,
|
|
1836
|
+
repository: repositorySchema,
|
|
1837
|
+
...deploymentWorkflowSchema
|
|
1838
|
+
}).passthrough();
|
|
1839
|
+
const canonicalDeploymentEventSchema = z.object({
|
|
1840
|
+
action: z.string(),
|
|
1841
|
+
commitSha: z.string().regex(/^[0-9a-f]{40}$/i),
|
|
1842
|
+
createdAt: z.string().optional(),
|
|
1843
|
+
deploymentId: z.number(),
|
|
1844
|
+
environment: z.string().min(1),
|
|
1845
|
+
repo: z.string().min(1),
|
|
1846
|
+
workflowId: z.number().optional(),
|
|
1847
|
+
workflowPath: z.string().min(1).optional(),
|
|
1848
|
+
workflowRunId: z.number().optional()
|
|
1849
|
+
}).strict();
|
|
1850
|
+
/** Select the canonical deployment fields shared by both webhook envelopes. */
|
|
1851
|
+
function canonicalDeploymentFields(data) {
|
|
1852
|
+
return {
|
|
1853
|
+
action: data.action,
|
|
1854
|
+
commitSha: data.deployment.sha,
|
|
1855
|
+
createdAt: data.deployment.created_at,
|
|
1856
|
+
deploymentId: data.deployment.id,
|
|
1857
|
+
environment: data.deployment.environment,
|
|
1858
|
+
repo: data.repository.full_name,
|
|
1859
|
+
workflowId: data.workflow?.id,
|
|
1860
|
+
workflowPath: data.workflow?.path,
|
|
1861
|
+
workflowRunId: data.workflow_run?.id
|
|
1862
|
+
};
|
|
1863
|
+
}
|
|
1864
|
+
/** Convert GitHub's permissive webhook envelope into routing-safe fields. */
|
|
1865
|
+
function parseDeploymentEvent(body) {
|
|
1866
|
+
const parsed = deploymentWebhookSchema.safeParse(body);
|
|
1867
|
+
if (!parsed.success) return void 0;
|
|
1868
|
+
return canonicalDeploymentEventSchema.parse(canonicalDeploymentFields(parsed.data));
|
|
1869
|
+
}
|
|
1870
|
+
/** Normalize a newly created GitHub deployment. */
|
|
1871
|
+
function normalizeDeploymentEvent(deliveryId, body) {
|
|
1872
|
+
const parsed = parseDeploymentEvent(body);
|
|
1873
|
+
if (!parsed || parsed.action !== "created") return [];
|
|
1874
|
+
const eventType = "deployment.created";
|
|
1875
|
+
const { label } = gitHubDeploymentSourceResource(parsed);
|
|
1876
|
+
return deploymentTargets(parsed).map(({ identifier }) => ({
|
|
1877
|
+
eventKey: gitHubEventKey(deliveryId, eventType),
|
|
1878
|
+
eventType,
|
|
1879
|
+
occurredAtMs: providerTime(parsed.createdAt) ?? Date.now(),
|
|
1880
|
+
identifier,
|
|
1881
|
+
trustedSummary: `${label} was created (deployment ${parsed.deploymentId}).`,
|
|
1882
|
+
data: deploymentEventData(parsed)
|
|
1883
|
+
}));
|
|
1884
|
+
}
|
|
1885
|
+
const deploymentStatusWebhookSchema = deploymentWebhookSchema.extend({ deployment_status: z.object({
|
|
1886
|
+
created_at: z.string().optional(),
|
|
1887
|
+
description: z.string().optional().nullable(),
|
|
1888
|
+
state: z.string()
|
|
1889
|
+
}).passthrough() });
|
|
1890
|
+
const canonicalDeploymentStatusEventSchema = canonicalDeploymentEventSchema.extend({
|
|
1891
|
+
description: z.string().optional().nullable(),
|
|
1892
|
+
state: z.string(),
|
|
1893
|
+
statusCreatedAt: z.string().optional()
|
|
1894
|
+
}).strict();
|
|
1895
|
+
/** Convert a GitHub status envelope into canonical deployment event fields. */
|
|
1896
|
+
function parseDeploymentStatusEvent(body) {
|
|
1897
|
+
const parsed = deploymentStatusWebhookSchema.safeParse(body);
|
|
1898
|
+
if (!parsed.success) return void 0;
|
|
1899
|
+
return canonicalDeploymentStatusEventSchema.parse({
|
|
1900
|
+
...canonicalDeploymentFields(parsed.data),
|
|
1901
|
+
description: parsed.data.deployment_status.description,
|
|
1902
|
+
state: parsed.data.deployment_status.state,
|
|
1903
|
+
statusCreatedAt: parsed.data.deployment_status.created_at
|
|
1904
|
+
});
|
|
1905
|
+
}
|
|
1906
|
+
/** Map GitHub status vocabulary to Junior's deployment event contract. */
|
|
1907
|
+
function deploymentStatusEventType(state) {
|
|
1908
|
+
switch (state) {
|
|
1909
|
+
case "queued":
|
|
1910
|
+
case "pending":
|
|
1911
|
+
case "in_progress": return `deployment.${state}`;
|
|
1912
|
+
case "success": return "deployment.succeeded";
|
|
1913
|
+
case "failure": return "deployment.failed";
|
|
1914
|
+
case "error": return "deployment.error";
|
|
1915
|
+
default: return;
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
/** Normalize a GitHub deployment status into a source event. */
|
|
1919
|
+
function normalizeDeploymentStatusEvent(deliveryId, body) {
|
|
1920
|
+
const parsed = parseDeploymentStatusEvent(body);
|
|
1921
|
+
if (!parsed || parsed.action !== "created") return [];
|
|
1922
|
+
const eventType = deploymentStatusEventType(parsed.state);
|
|
1923
|
+
if (!eventType) return [];
|
|
1924
|
+
const outcome = eventType === "deployment.succeeded" ? "succeeded" : eventType === "deployment.failed" ? "failed" : eventType === "deployment.error" ? "reported an error" : eventType === "deployment.in_progress" ? "started" : `is ${parsed.state}`;
|
|
1925
|
+
const terminal = eventType === "deployment.succeeded" || eventType === "deployment.failed" || eventType === "deployment.error";
|
|
1926
|
+
const { label } = gitHubDeploymentSourceResource(parsed);
|
|
1927
|
+
return deploymentTargets(parsed).map(({ completeOnTerminalEvent, identifier }) => ({
|
|
1928
|
+
eventKey: gitHubEventKey(deliveryId, eventType),
|
|
1929
|
+
eventType,
|
|
1930
|
+
occurredAtMs: providerTime(parsed.statusCreatedAt) ?? Date.now(),
|
|
1931
|
+
identifier,
|
|
1932
|
+
...terminal && completeOnTerminalEvent ? { terminal: true } : void 0,
|
|
1933
|
+
trustedSummary: `${label} ${outcome} (deployment ${parsed.deploymentId}).`,
|
|
1934
|
+
data: deploymentEventData(parsed),
|
|
1935
|
+
untrustedText: parsed.description ?? void 0
|
|
1936
|
+
}));
|
|
1937
|
+
}
|
|
1938
|
+
/** Trusted data on every deployment event. */
|
|
1939
|
+
const deploymentEventDataSchema = z.object({
|
|
1940
|
+
repo: gitHubRepoDataSchema,
|
|
1941
|
+
commitSha: gitHubCommitShaDataSchema,
|
|
1942
|
+
deploymentId: z.number(),
|
|
1943
|
+
environment: z.string().trim().min(1).toLowerCase(),
|
|
1944
|
+
workflowId: z.number().optional(),
|
|
1945
|
+
workflowPath: z.string().min(1).optional(),
|
|
1946
|
+
workflowRunId: z.number().optional()
|
|
1947
|
+
}).strict();
|
|
1948
|
+
/** Build the trusted data of one deployment event. */
|
|
1949
|
+
function deploymentEventData(input) {
|
|
1950
|
+
return deploymentEventDataSchema.parse(definedValues({
|
|
1951
|
+
repo: input.repo,
|
|
1952
|
+
commitSha: input.commitSha,
|
|
1953
|
+
deploymentId: input.deploymentId,
|
|
1954
|
+
environment: input.environment,
|
|
1955
|
+
workflowId: input.workflowId,
|
|
1956
|
+
workflowPath: input.workflowPath,
|
|
1957
|
+
workflowRunId: input.workflowRunId
|
|
1958
|
+
}));
|
|
1959
|
+
}
|
|
1960
|
+
/**
|
|
1961
|
+
* Address one deployment through its exact environment, its commit, and its
|
|
1962
|
+
* repository. Only the exact target completes on a terminal status; the
|
|
1963
|
+
* repository target lets event automations follow every deployment.
|
|
1964
|
+
*/
|
|
1965
|
+
function deploymentTargets(input) {
|
|
1966
|
+
return [
|
|
1967
|
+
{
|
|
1968
|
+
completeOnTerminalEvent: true,
|
|
1969
|
+
identifier: gitHubDeploymentSourceResource(input).identifier
|
|
1970
|
+
},
|
|
1971
|
+
{
|
|
1972
|
+
completeOnTerminalEvent: false,
|
|
1973
|
+
identifier: gitHubDeploymentSourceResource({
|
|
1974
|
+
commitSha: input.commitSha,
|
|
1975
|
+
repo: input.repo
|
|
1976
|
+
}).identifier
|
|
1977
|
+
},
|
|
1978
|
+
{
|
|
1979
|
+
completeOnTerminalEvent: false,
|
|
1980
|
+
identifier: gitHubRepositoryResource({ repo: input.repo }).identifier
|
|
1981
|
+
}
|
|
1982
|
+
];
|
|
1983
|
+
}
|
|
1984
|
+
const gitHubUserSchema = z.object({
|
|
1985
|
+
email: z.string().nullish(),
|
|
1986
|
+
login: z.string().nullish()
|
|
1987
|
+
});
|
|
1988
|
+
const commentSchema = z.object({
|
|
1989
|
+
body: z.string(),
|
|
1990
|
+
id: z.number(),
|
|
1991
|
+
user: z.object({ login: z.string().optional() }).optional()
|
|
1992
|
+
});
|
|
1993
|
+
/** Trusted data that every comment and review event sets. */
|
|
1994
|
+
const commentAuthorDataSchema = z.object({
|
|
1995
|
+
mentionsBot: z.boolean().optional(),
|
|
1996
|
+
senderId: z.number().optional(),
|
|
1997
|
+
senderLogin: z.string().min(1).optional()
|
|
1998
|
+
});
|
|
1999
|
+
/**
|
|
2000
|
+
* Who wrote a comment or review, and whether its text mentions the bot.
|
|
2001
|
+
* `mentionsBot` is set only when the bot email is configured.
|
|
2002
|
+
*/
|
|
2003
|
+
function commentAuthorData(input) {
|
|
2004
|
+
return {
|
|
2005
|
+
mentionsBot: input.botEmail ? mentionsBotLogin(input.text ?? "", input.botEmail) : void 0,
|
|
2006
|
+
...gitHubSenderData(input.sender)
|
|
2007
|
+
};
|
|
2008
|
+
}
|
|
2009
|
+
/** The pull request values that every pull request webhook sends. */
|
|
2010
|
+
const pullRequestSchema = z.object({
|
|
2011
|
+
draft: z.boolean().optional(),
|
|
2012
|
+
head: z.object({ ref: z.string().nullish() }).nullish(),
|
|
2013
|
+
number: z.number(),
|
|
2014
|
+
user: gitHubUserSchema.nullish()
|
|
2015
|
+
});
|
|
2016
|
+
/**
|
|
2017
|
+
* Trusted data on every pull request event. The opener is the GitHub user
|
|
2018
|
+
* who opened the pull request, not the commenter. The pull request comment
|
|
2019
|
+
* webhook has no head branch.
|
|
2020
|
+
*/
|
|
2021
|
+
const pullRequestEventDataSchema = commentAuthorDataSchema.extend({
|
|
2022
|
+
repo: gitHubRepoDataSchema,
|
|
2023
|
+
pullRequest: z.number(),
|
|
2024
|
+
headBranch: z.string().min(1).optional(),
|
|
2025
|
+
isDraft: z.boolean().optional(),
|
|
2026
|
+
openerEmail: z.string().min(1).optional(),
|
|
2027
|
+
openerUsername: z.string().min(1).optional(),
|
|
2028
|
+
commentId: z.number().optional(),
|
|
2029
|
+
commentKind: z.enum([
|
|
2030
|
+
"conversation",
|
|
2031
|
+
"review",
|
|
2032
|
+
"review_body"
|
|
2033
|
+
]).optional()
|
|
2034
|
+
}).strict();
|
|
2035
|
+
/** Build the trusted data of one pull request event. */
|
|
2036
|
+
function pullRequestEventData(input) {
|
|
2037
|
+
const { pullRequest } = input;
|
|
2038
|
+
return pullRequestEventDataSchema.parse(definedValues({
|
|
2039
|
+
repo: input.repo,
|
|
2040
|
+
pullRequest: pullRequest.number,
|
|
2041
|
+
headBranch: nonBlank(pullRequest.head?.ref),
|
|
2042
|
+
isDraft: pullRequest.draft,
|
|
2043
|
+
openerEmail: nonBlank(pullRequest.user?.email),
|
|
2044
|
+
openerUsername: nonBlank(pullRequest.user?.login),
|
|
2045
|
+
...input.comment
|
|
2046
|
+
}));
|
|
2047
|
+
}
|
|
2048
|
+
/** Trusted data on every issue event. */
|
|
2049
|
+
const issueEventDataSchema = commentAuthorDataSchema.extend({
|
|
2050
|
+
repo: gitHubRepoDataSchema,
|
|
2051
|
+
issue: z.number(),
|
|
2052
|
+
commentId: z.number().optional()
|
|
2053
|
+
}).strict();
|
|
2054
|
+
/** Build the trusted data of one issue event. */
|
|
2055
|
+
function issueEventData(input) {
|
|
2056
|
+
return issueEventDataSchema.parse(definedValues(input));
|
|
2057
|
+
}
|
|
2058
|
+
const issueCommentWebhookSchema = z.object({
|
|
2059
|
+
action: z.string(),
|
|
2060
|
+
comment: commentSchema,
|
|
2061
|
+
issue: z.object({
|
|
2062
|
+
draft: z.boolean().optional(),
|
|
2063
|
+
number: z.number(),
|
|
2064
|
+
pull_request: z.object({ url: z.string().min(1) }).optional(),
|
|
2065
|
+
user: gitHubUserSchema.nullish()
|
|
2066
|
+
}),
|
|
2067
|
+
repository: repositorySchema,
|
|
2068
|
+
sender: gitHubSenderSchema.optional()
|
|
2069
|
+
});
|
|
2070
|
+
/** Normalize a newly created issue or pull request comment. */
|
|
2071
|
+
function normalizeIssueCommentEvents(deliveryId, body, botEmail) {
|
|
2072
|
+
const parsed = issueCommentWebhookSchema.safeParse(body);
|
|
2073
|
+
if (!parsed.success || parsed.data.action !== "created") return [];
|
|
2074
|
+
const { comment, issue, sender } = parsed.data;
|
|
2075
|
+
const author = comment.user?.login;
|
|
2076
|
+
if (isBotLogin(author, botEmail)) return [];
|
|
2077
|
+
const input = {
|
|
2078
|
+
number: issue.number,
|
|
2079
|
+
repo: parsed.data.repository.full_name
|
|
2080
|
+
};
|
|
2081
|
+
const writtenBy = commentAuthorData({
|
|
2082
|
+
botEmail,
|
|
2083
|
+
sender,
|
|
2084
|
+
text: comment.body
|
|
2085
|
+
});
|
|
2086
|
+
if (issue.pull_request) {
|
|
2087
|
+
const eventType = "pull_request.comment.created";
|
|
2088
|
+
const resource = gitHubPullRequestResource(input);
|
|
2089
|
+
return pullRequestTargets({
|
|
2090
|
+
eventKey: gitHubEventKey(deliveryId, eventType),
|
|
2091
|
+
eventType,
|
|
2092
|
+
occurredAtMs: Date.now(),
|
|
2093
|
+
identifier: resource.identifier,
|
|
2094
|
+
trustedSummary: `${resource.label} received a comment${author ? ` from ${author}` : ""}.`,
|
|
2095
|
+
...gitHubDoneBy(author),
|
|
2096
|
+
data: pullRequestEventData({
|
|
2097
|
+
comment: {
|
|
2098
|
+
commentId: comment.id,
|
|
2099
|
+
commentKind: "conversation",
|
|
2100
|
+
...writtenBy
|
|
2101
|
+
},
|
|
2102
|
+
pullRequest: issue,
|
|
2103
|
+
repo: input.repo
|
|
2104
|
+
}),
|
|
2105
|
+
untrustedText: comment.body
|
|
2106
|
+
}, input.repo);
|
|
2107
|
+
}
|
|
2108
|
+
const issueResource = gitHubIssueResource(input);
|
|
2109
|
+
const repository = gitHubRepositoryResource(input);
|
|
2110
|
+
const data = issueEventData({
|
|
2111
|
+
repo: input.repo,
|
|
2112
|
+
issue: input.number,
|
|
2113
|
+
commentId: comment.id,
|
|
2114
|
+
...writtenBy
|
|
2115
|
+
});
|
|
2116
|
+
return [issueResource, repository].map((resource) => ({
|
|
2117
|
+
eventKey: gitHubEventKey(deliveryId, "issue.comment.created"),
|
|
2118
|
+
eventType: "issue.comment.created",
|
|
2119
|
+
occurredAtMs: Date.now(),
|
|
2120
|
+
identifier: resource.identifier,
|
|
2121
|
+
trustedSummary: `${issueResource.label} received a comment${author ? ` from ${author}` : ""}.`,
|
|
2122
|
+
...gitHubDoneBy(author),
|
|
2123
|
+
data,
|
|
2124
|
+
untrustedText: comment.body
|
|
2125
|
+
}));
|
|
2126
|
+
}
|
|
2127
|
+
const issueWebhookSchema = z.object({
|
|
2128
|
+
action: z.string(),
|
|
2129
|
+
issue: z.object({
|
|
2130
|
+
body: z.string().optional().nullable(),
|
|
2131
|
+
closed_at: z.string().optional().nullable(),
|
|
2132
|
+
created_at: z.string().optional(),
|
|
2133
|
+
number: z.number(),
|
|
2134
|
+
title: z.string().optional(),
|
|
2135
|
+
updated_at: z.string().optional()
|
|
2136
|
+
}),
|
|
2137
|
+
repository: repositorySchema
|
|
2138
|
+
});
|
|
2139
|
+
/** Normalize issue lifecycle changes and updates for the issue and its repository. */
|
|
2140
|
+
function normalizeIssueEvents(deliveryId, body, botEmail) {
|
|
2141
|
+
const updates = normalizeIssueUpdateEvents(deliveryId, body, botEmail);
|
|
2142
|
+
if (updates) return updates;
|
|
2143
|
+
const parsed = issueWebhookSchema.safeParse(body);
|
|
2144
|
+
if (!parsed.success) return [];
|
|
2145
|
+
const state = parsed.data.action === "opened" ? "opened" : parsed.data.action === "closed" ? "closed" : parsed.data.action === "reopened" ? "reopened" : void 0;
|
|
2146
|
+
if (!state) return [];
|
|
2147
|
+
const input = {
|
|
2148
|
+
number: parsed.data.issue.number,
|
|
2149
|
+
repo: parsed.data.repository.full_name
|
|
2150
|
+
};
|
|
2151
|
+
const issue = gitHubIssueResource(input);
|
|
2152
|
+
const repository = gitHubRepositoryResource(input);
|
|
2153
|
+
const occurredAtMs = providerTime(state === "opened" ? parsed.data.issue.created_at : state === "closed" ? parsed.data.issue.closed_at : parsed.data.issue.updated_at) ?? Date.now();
|
|
2154
|
+
const data = issueEventData({
|
|
2155
|
+
repo: input.repo,
|
|
2156
|
+
issue: input.number
|
|
2157
|
+
});
|
|
2158
|
+
const untrustedText = titleAndBodyText(parsed.data.issue);
|
|
2159
|
+
return [issue, repository].map((resource) => ({
|
|
2160
|
+
eventKey: gitHubEventKey(deliveryId, `issue.${state}`),
|
|
2161
|
+
eventType: `issue.${state}`,
|
|
2162
|
+
occurredAtMs,
|
|
2163
|
+
identifier: resource.identifier,
|
|
2164
|
+
trustedSummary: `${issue.label} was ${state}.`,
|
|
2165
|
+
data,
|
|
2166
|
+
...untrustedText ? { untrustedText } : void 0
|
|
2167
|
+
}));
|
|
2168
|
+
}
|
|
2169
|
+
const pullRequestReviewCommentWebhookSchema = z.object({
|
|
2170
|
+
action: z.string(),
|
|
2171
|
+
comment: commentSchema,
|
|
2172
|
+
pull_request: pullRequestSchema,
|
|
2173
|
+
repository: repositorySchema,
|
|
2174
|
+
sender: gitHubSenderSchema.optional()
|
|
2175
|
+
});
|
|
2176
|
+
/** Normalize a newly created inline pull request review comment. */
|
|
2177
|
+
function normalizePullRequestReviewCommentEvent(deliveryId, body, botEmail) {
|
|
2178
|
+
const parsed = pullRequestReviewCommentWebhookSchema.safeParse(body);
|
|
2179
|
+
if (!parsed.success || parsed.data.action !== "created") return [];
|
|
2180
|
+
const { comment, pull_request: pullRequest, sender } = parsed.data;
|
|
2181
|
+
const author = comment.user?.login;
|
|
2182
|
+
if (isBotLogin(author, botEmail)) return [];
|
|
2183
|
+
const eventType = "pull_request.review_comment.created";
|
|
2184
|
+
const repo = parsed.data.repository.full_name;
|
|
2185
|
+
const resource = gitHubPullRequestResource({
|
|
2186
|
+
number: pullRequest.number,
|
|
2187
|
+
repo
|
|
2188
|
+
});
|
|
2189
|
+
return pullRequestTargets({
|
|
2190
|
+
eventKey: gitHubEventKey(deliveryId, eventType),
|
|
2191
|
+
eventType,
|
|
2192
|
+
occurredAtMs: Date.now(),
|
|
2193
|
+
identifier: resource.identifier,
|
|
2194
|
+
trustedSummary: `${resource.label} received an inline review comment${author ? ` from ${author}` : ""}.`,
|
|
2195
|
+
...gitHubDoneBy(author),
|
|
2196
|
+
data: pullRequestEventData({
|
|
2197
|
+
comment: {
|
|
2198
|
+
commentId: comment.id,
|
|
2199
|
+
commentKind: "review",
|
|
2200
|
+
...commentAuthorData({
|
|
2201
|
+
botEmail,
|
|
2202
|
+
sender,
|
|
2203
|
+
text: comment.body
|
|
2204
|
+
})
|
|
2205
|
+
},
|
|
2206
|
+
pullRequest,
|
|
2207
|
+
repo
|
|
2208
|
+
}),
|
|
2209
|
+
untrustedText: comment.body
|
|
2210
|
+
}, repo);
|
|
2211
|
+
}
|
|
2212
|
+
const pullRequestReviewWebhookSchema = z.object({
|
|
2213
|
+
action: z.string(),
|
|
2214
|
+
pull_request: pullRequestSchema,
|
|
2215
|
+
repository: repositorySchema,
|
|
2216
|
+
review: z.object({
|
|
2217
|
+
body: z.string().optional().nullable(),
|
|
2218
|
+
id: z.number().optional(),
|
|
2219
|
+
state: z.string(),
|
|
2220
|
+
user: z.object({ login: z.string().optional() }).optional()
|
|
2221
|
+
}),
|
|
2222
|
+
sender: gitHubSenderSchema.optional()
|
|
2223
|
+
});
|
|
2224
|
+
/** Normalize a submitted pull request review into its review-state event. */
|
|
2225
|
+
function normalizePullRequestReviewEvent(deliveryId, body, botEmail) {
|
|
2226
|
+
const parsed = pullRequestReviewWebhookSchema.safeParse(body);
|
|
2227
|
+
if (!parsed.success || parsed.data.action !== "submitted") return [];
|
|
2228
|
+
const { pull_request: pullRequest, review, sender } = parsed.data;
|
|
2229
|
+
if (isBotLogin(review.user?.login, botEmail)) return [];
|
|
2230
|
+
const reviewState = review.state.toUpperCase();
|
|
2231
|
+
const eventType = reviewState === "APPROVED" ? "pull_request.review.approved" : reviewState === "CHANGES_REQUESTED" ? "pull_request.review.changes_requested" : reviewState === "COMMENTED" ? "pull_request.review.commented" : void 0;
|
|
2232
|
+
if (!eventType) return [];
|
|
2233
|
+
const repo = parsed.data.repository.full_name;
|
|
2234
|
+
const resource = gitHubPullRequestResource({
|
|
2235
|
+
number: pullRequest.number,
|
|
2236
|
+
repo
|
|
2237
|
+
});
|
|
2238
|
+
const reviewer = review.user?.login;
|
|
2239
|
+
const event = {
|
|
2240
|
+
eventKey: gitHubEventKey(deliveryId, eventType),
|
|
2241
|
+
eventType,
|
|
2242
|
+
occurredAtMs: Date.now(),
|
|
2243
|
+
identifier: resource.identifier,
|
|
2244
|
+
trustedSummary: eventType === "pull_request.review.approved" ? `${resource.label} was approved${reviewer ? ` by ${reviewer}` : ""}.` : eventType === "pull_request.review.changes_requested" ? `${resource.label} received requested changes${reviewer ? ` from ${reviewer}` : ""}.` : `${resource.label} received a review comment${reviewer ? ` from ${reviewer}` : ""}.`,
|
|
2245
|
+
...gitHubDoneBy(reviewer),
|
|
2246
|
+
data: pullRequestEventData({
|
|
2247
|
+
comment: {
|
|
2248
|
+
...review.id !== void 0 && nonBlank(review.body) ? {
|
|
2249
|
+
commentId: review.id,
|
|
2250
|
+
commentKind: "review_body"
|
|
2251
|
+
} : void 0,
|
|
2252
|
+
...commentAuthorData({
|
|
2253
|
+
botEmail,
|
|
2254
|
+
sender,
|
|
2255
|
+
text: review.body
|
|
2256
|
+
})
|
|
2257
|
+
},
|
|
2258
|
+
pullRequest,
|
|
2259
|
+
repo
|
|
2260
|
+
}),
|
|
2261
|
+
untrustedText: review.body ?? void 0
|
|
2262
|
+
};
|
|
2263
|
+
const events = pullRequestTargets(event, repo);
|
|
2264
|
+
if (eventType !== "pull_request.review.approved" || !nonBlank(review.body)) return events;
|
|
2265
|
+
return [...events, ...pullRequestTargets({
|
|
2266
|
+
...event,
|
|
2267
|
+
eventKey: gitHubEventKey(deliveryId, "pull_request.review.commented"),
|
|
2268
|
+
eventType: "pull_request.review.commented"
|
|
2269
|
+
}, repo)];
|
|
2270
|
+
}
|
|
2271
|
+
const pullRequestWebhookSchema = z.object({
|
|
2272
|
+
action: z.string(),
|
|
2273
|
+
pull_request: pullRequestSchema.extend({
|
|
2274
|
+
body: z.string().optional().nullable(),
|
|
2275
|
+
closed_at: z.string().optional().nullable(),
|
|
2276
|
+
created_at: z.string().optional(),
|
|
2277
|
+
merged: z.boolean().optional(),
|
|
2278
|
+
merged_at: z.string().optional().nullable(),
|
|
2279
|
+
title: z.string().optional(),
|
|
2280
|
+
updated_at: z.string().optional()
|
|
2281
|
+
}),
|
|
2282
|
+
repository: repositorySchema
|
|
2283
|
+
});
|
|
2284
|
+
/** Normalize pull request opened, ready-for-review, and terminal lifecycle events. */
|
|
2285
|
+
function normalizePullRequestEvent(deliveryId, body) {
|
|
2286
|
+
const parsed = pullRequestWebhookSchema.safeParse(body);
|
|
2287
|
+
if (!parsed.success) return [];
|
|
2288
|
+
const { pull_request: pullRequest } = parsed.data;
|
|
2289
|
+
const repo = parsed.data.repository.full_name;
|
|
2290
|
+
const resource = gitHubPullRequestResource({
|
|
2291
|
+
number: pullRequest.number,
|
|
2292
|
+
repo
|
|
2293
|
+
});
|
|
2294
|
+
const data = pullRequestEventData({
|
|
2295
|
+
pullRequest,
|
|
2296
|
+
repo
|
|
2297
|
+
});
|
|
2298
|
+
const readyData = pullRequestEventData({
|
|
2299
|
+
pullRequest: {
|
|
2300
|
+
...pullRequest,
|
|
2301
|
+
draft: false
|
|
2302
|
+
},
|
|
2303
|
+
repo
|
|
2304
|
+
});
|
|
2305
|
+
const untrustedText = titleAndBodyText(pullRequest);
|
|
2306
|
+
const lifecycleEvents = (event) => pullRequestTargets({
|
|
2307
|
+
eventKey: gitHubEventKey(deliveryId, event.eventType),
|
|
2308
|
+
eventType: event.eventType,
|
|
2309
|
+
occurredAtMs: event.occurredAtMs,
|
|
2310
|
+
identifier: resource.identifier,
|
|
2311
|
+
trustedSummary: event.trustedSummary,
|
|
2312
|
+
data: event.isDraft === false ? readyData : data,
|
|
2313
|
+
...event.untrustedText ? { untrustedText: event.untrustedText } : void 0
|
|
2314
|
+
}, repo);
|
|
2315
|
+
if (parsed.data.action === "opened") {
|
|
2316
|
+
const openedAtMs = providerTime(pullRequest.created_at) ?? Date.now();
|
|
2317
|
+
const events = lifecycleEvents({
|
|
2318
|
+
eventType: "pull_request.opened",
|
|
2319
|
+
occurredAtMs: openedAtMs,
|
|
2320
|
+
trustedSummary: `${resource.label} was opened.`,
|
|
2321
|
+
untrustedText
|
|
2322
|
+
});
|
|
2323
|
+
if (pullRequest.draft !== true) events.push(...lifecycleEvents({
|
|
2324
|
+
eventType: "pull_request.ready_for_review",
|
|
2325
|
+
isDraft: false,
|
|
2326
|
+
occurredAtMs: openedAtMs,
|
|
2327
|
+
trustedSummary: `${resource.label} is ready for review.`,
|
|
2328
|
+
untrustedText
|
|
2329
|
+
}));
|
|
2330
|
+
return events;
|
|
2331
|
+
}
|
|
2332
|
+
if (parsed.data.action === "ready_for_review") return lifecycleEvents({
|
|
2333
|
+
eventType: "pull_request.ready_for_review",
|
|
2334
|
+
isDraft: false,
|
|
2335
|
+
occurredAtMs: providerTime(pullRequest.updated_at) ?? Date.now(),
|
|
2336
|
+
trustedSummary: `${resource.label} is ready for review.`,
|
|
2337
|
+
untrustedText
|
|
2338
|
+
});
|
|
2339
|
+
return gitHubPullRequestTerminalEvents(body);
|
|
2340
|
+
}
|
|
2341
|
+
/**
|
|
2342
|
+
* Build the merged or closed_unmerged events of one closed pull request.
|
|
2343
|
+
* The webhook and the daily reconcile both publish them. The key names the
|
|
2344
|
+
* close, not the webhook delivery, so a Watch gets the close once.
|
|
2345
|
+
*/
|
|
2346
|
+
function gitHubPullRequestTerminalEvents(body) {
|
|
2347
|
+
const parsed = pullRequestWebhookSchema.safeParse(body);
|
|
2348
|
+
if (!parsed.success || parsed.data.action !== "closed") return [];
|
|
2349
|
+
const { pull_request: pullRequest } = parsed.data;
|
|
2350
|
+
const repo = parsed.data.repository.full_name;
|
|
2351
|
+
const resource = gitHubPullRequestResource({
|
|
2352
|
+
number: pullRequest.number,
|
|
2353
|
+
repo
|
|
2354
|
+
});
|
|
2355
|
+
const merged = pullRequest.merged === true;
|
|
2356
|
+
const eventType = merged ? "pull_request.merged" : "pull_request.closed_unmerged";
|
|
2357
|
+
const occurredAtMs = providerTime(merged ? pullRequest.merged_at : pullRequest.closed_at) ?? providerTime(pullRequest.updated_at) ?? Date.now();
|
|
2358
|
+
return pullRequestTargets({
|
|
2359
|
+
eventKey: merged ? `github:${resource.identifier}:${eventType}` : `github:${resource.identifier}:${eventType}:${occurredAtMs}`,
|
|
2360
|
+
eventType,
|
|
2361
|
+
occurredAtMs,
|
|
2362
|
+
identifier: resource.identifier,
|
|
2363
|
+
terminal: true,
|
|
2364
|
+
trustedSummary: merged ? `${resource.label} was merged.` : `${resource.label} was closed without being merged.`,
|
|
2365
|
+
data: pullRequestEventData({
|
|
2366
|
+
pullRequest,
|
|
2367
|
+
repo
|
|
2368
|
+
})
|
|
2369
|
+
}, repo);
|
|
2370
|
+
}
|
|
2371
|
+
const releaseWebhookSchema = z.object({
|
|
2372
|
+
action: z.string(),
|
|
2373
|
+
release: z.object({
|
|
2374
|
+
body: z.string().optional().nullable(),
|
|
2375
|
+
draft: z.boolean().optional(),
|
|
2376
|
+
id: z.number(),
|
|
2377
|
+
name: z.string().optional().nullable(),
|
|
2378
|
+
prerelease: z.boolean().optional(),
|
|
2379
|
+
published_at: z.string().optional().nullable(),
|
|
2380
|
+
tag_name: z.string().min(1)
|
|
2381
|
+
}).passthrough(),
|
|
2382
|
+
repository: repositorySchema
|
|
2383
|
+
}).passthrough();
|
|
2384
|
+
/** Trusted data on every release event. */
|
|
2385
|
+
const releaseEventDataSchema = z.object({
|
|
2386
|
+
repo: gitHubRepoDataSchema,
|
|
2387
|
+
tag: gitHubReleaseTagDataSchema
|
|
2388
|
+
}).strict();
|
|
2389
|
+
/** Address one release through both its exact tag and its repository. */
|
|
2390
|
+
function releaseSourceTargets(input) {
|
|
2391
|
+
return [{
|
|
2392
|
+
completeOnTerminalEvent: true,
|
|
2393
|
+
resource: gitHubReleaseSourceResource(input)
|
|
2394
|
+
}, {
|
|
2395
|
+
completeOnTerminalEvent: false,
|
|
2396
|
+
resource: gitHubReleaseSourceResource({ repo: input.repo })
|
|
2397
|
+
}];
|
|
2398
|
+
}
|
|
2399
|
+
/** Normalize a published GitHub release for tag and repository watches. */
|
|
2400
|
+
function normalizeReleaseEvent(deliveryId, body) {
|
|
2401
|
+
const parsed = releaseWebhookSchema.safeParse(body);
|
|
2402
|
+
if (!parsed.success || parsed.data.action !== "published") return [];
|
|
2403
|
+
if (parsed.data.release.draft) return [];
|
|
2404
|
+
const eventType = "release.published";
|
|
2405
|
+
const repo = parsed.data.repository.full_name;
|
|
2406
|
+
const tag = parsed.data.release.tag_name.trim();
|
|
2407
|
+
if (!tag) return [];
|
|
2408
|
+
const untrustedParts = [
|
|
2409
|
+
`Tag: ${tag}`,
|
|
2410
|
+
parsed.data.release.name?.trim() ? `Name: ${parsed.data.release.name.trim()}` : void 0,
|
|
2411
|
+
parsed.data.release.body?.trim() || void 0
|
|
2412
|
+
].filter((part) => part !== void 0);
|
|
2413
|
+
const untrustedText = untrustedParts.length > 0 ? untrustedParts.join("\n\n") : void 0;
|
|
2414
|
+
const data = releaseEventDataSchema.parse({
|
|
2415
|
+
repo,
|
|
2416
|
+
tag
|
|
2417
|
+
});
|
|
2418
|
+
return releaseSourceTargets({
|
|
2419
|
+
repo,
|
|
2420
|
+
tag
|
|
2421
|
+
}).map(({ completeOnTerminalEvent, resource }) => ({
|
|
2422
|
+
eventKey: gitHubEventKey(deliveryId, eventType),
|
|
2423
|
+
eventType,
|
|
2424
|
+
occurredAtMs: providerTime(parsed.data.release.published_at) ?? Date.now(),
|
|
2425
|
+
identifier: resource.identifier,
|
|
2426
|
+
...completeOnTerminalEvent ? { terminal: true } : void 0,
|
|
2427
|
+
trustedSummary: `${resource.label} was published (release ${parsed.data.release.id}).`,
|
|
2428
|
+
data,
|
|
2429
|
+
...untrustedText ? { untrustedText } : void 0
|
|
2430
|
+
}));
|
|
2431
|
+
}
|
|
2432
|
+
/**
|
|
2433
|
+
* Normalize one verified GitHub delivery into conversation events.
|
|
2434
|
+
*
|
|
2435
|
+
* Comments and reviews written by the configured bot are dropped, so Junior
|
|
2436
|
+
* does not react to or act on its own feedback.
|
|
2437
|
+
*/
|
|
2438
|
+
function normalizeGitHubEvents(args) {
|
|
2439
|
+
switch (args.eventName) {
|
|
2440
|
+
case "deployment": return normalizeDeploymentEvent(args.deliveryId, args.body);
|
|
2441
|
+
case "deployment_status": return normalizeDeploymentStatusEvent(args.deliveryId, args.body);
|
|
2442
|
+
case "pull_request": return normalizePullRequestEvent(args.deliveryId, args.body);
|
|
2443
|
+
case "issues": return normalizeIssueEvents(args.deliveryId, args.body, args.botEmail);
|
|
2444
|
+
case "pull_request_review": return normalizePullRequestReviewEvent(args.deliveryId, args.body, args.botEmail);
|
|
2445
|
+
case "issue_comment": return normalizeIssueCommentEvents(args.deliveryId, args.body, args.botEmail);
|
|
2446
|
+
case "pull_request_review_comment": return normalizePullRequestReviewCommentEvent(args.deliveryId, args.body, args.botEmail);
|
|
2447
|
+
case "check_suite": return normalizeCheckSuiteEvents(args.deliveryId, args.body, args.checkSuiteFacts);
|
|
2448
|
+
case "release": return normalizeReleaseEvent(args.deliveryId, args.body);
|
|
2449
|
+
default: return [];
|
|
2450
|
+
}
|
|
2451
|
+
}
|
|
2452
|
+
export { GITHUB_DEPLOYMENT_EVENTS as $, requireEnv as A, GITHUB_RELEASE_MATCH_FIELDS as B, githubRequest as C, listVerifiedUserEmails as D, issueInstallationToken as E, GITHUB_REPOSITORY_EVENTS as F, GITHUB_PULL_REQUEST_IDENTIFIER as G, GITHUB_RELEASE_SUGGESTED_EVENTS as H, GITHUB_REPOSITORY_IDENTIFIER as I, gitHubPullRequestCreateWatch as J, GITHUB_PULL_REQUEST_MATCH_FIELDS as K, GITHUB_REPOSITORY_SUGGESTED_EVENTS as L, botLoginFromEmail as M, botUserIdFromEmail as N, normalizeScopeList as O, isBotLogin as P, gitHubPullRequestSubscription as Q, gitHubRepositorySubscribable as R, githubRepositoryFromUrl as S, issueGitHubCredential as T, gitHubReleaseSourceSubscribable as U, GITHUB_RELEASE_SOURCE_IDENTIFIER as V, GITHUB_PULL_REQUEST_EVENTS as W, gitHubPullRequestResource as X, gitHubPullRequestEventGuidance as Y, gitHubPullRequestSubscribable as Z, GITHUB_INSTALLATION_ID_ENV as _, needsCheckSuitePullRequestFacts as a, GITHUB_ISSUE_IDENTIFIER as at, USER_WRITE_REQUIREMENTS as b, logFailOpenFailure as c, gitHubIssueSubscribable as ct, CREATE_TOOL_ROUTING_GUIDANCE as d, readGrantPermissions as dt, GITHUB_DEPLOYMENT_MATCH_FIELDS as et, GITHUB_APP_ID_ENV as f, GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES as g, GITHUB_AUTH_TOKEN_PLACEHOLDER as h, loadCheckSuiteFacts as i, GITHUB_ISSUE_EVENTS as it, resolveUserAccount as j, readEnv as k, definedValues as l, gitHubRepoDataSchema as lt, GITHUB_AUTH_TOKEN_ENV as m, normalizeGitHubEvents as n, GITHUB_DEPLOYMENT_SUGGESTED_EVENTS as nt, parseCheckSuitePublishTargets as o, GITHUB_ISSUE_MATCH_FIELDS as ot, GITHUB_APP_PRIVATE_KEY_ENV as p, GITHUB_PULL_REQUEST_SUGGESTED_EVENTS as q, checkSuitePullRequests as r, gitHubDeploymentSourceSubscribable as rt, wantsCheckSuitePassed as s, GITHUB_ISSUE_SUGGESTED_EVENTS as st, gitHubPullRequestTerminalEvents as t, GITHUB_DEPLOYMENT_SOURCE_IDENTIFIER as tt, pullRequestTargets as u, normalizePermissions as ut, GitHubRequestError as v, isRecord as w, createPermissionCache as x, HTTP_READ_METHODS as y, GITHUB_RELEASE_EVENTS as z };
|