@sentry/junior-github 0.310.0 → 0.311.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.
@@ -100,23 +100,39 @@ function parseRepo(value) {
100
100
  ref: `${parts[0]}/${parts[1]}`
101
101
  };
102
102
  }
103
+ const githubErrorBodySchema = z.object({
104
+ errors: z.unknown().optional(),
105
+ message: z.unknown().optional()
106
+ });
107
+ const githubErrorEntrySchema = z.object({
108
+ code: z.unknown().optional(),
109
+ field: z.unknown().optional(),
110
+ message: z.unknown().optional(),
111
+ resource: z.unknown().optional()
112
+ });
113
+ const GITHUB_ERROR_DETAIL_FIELDS = [
114
+ "resource",
115
+ "field",
116
+ "code",
117
+ "message"
118
+ ];
103
119
  /**
104
120
  * Return a readable error from a GitHub REST or GraphQL error body.
105
121
  *
106
122
  * REST validation errors list the failed fields in `errors`, and GraphQL puts
107
123
  * every message in `errors`. Both details help the model fix its input.
108
124
  */
109
- function githubErrorMessage(body) {
110
- if (typeof body === "string" && body.trim()) return body.trim();
111
- if (!isRecord$1(body)) return "GitHub request failed";
112
- const errors = Array.isArray(body["errors"]) ? body["errors"].filter(isRecord$1) : [];
125
+ function githubErrorMessage(value) {
126
+ if (typeof value === "string" && value.trim()) return value.trim();
127
+ const parsed = githubErrorBodySchema.safeParse(value);
128
+ if (!parsed.success) return "GitHub request failed";
129
+ const body = parsed.data;
130
+ const errors = Array.isArray(body["errors"]) ? body["errors"].flatMap((entry) => {
131
+ const error = githubErrorEntrySchema.safeParse(entry);
132
+ return error.success ? [error.data] : [];
133
+ }) : [];
113
134
  if (typeof body["message"] === "string" && body["message"].trim()) {
114
- const details = errors.map((error) => [
115
- "resource",
116
- "field",
117
- "code",
118
- "message"
119
- ].map((name) => {
135
+ const details = errors.map((error) => GITHUB_ERROR_DETAIL_FIELDS.map((name) => {
120
136
  const value = error[name];
121
137
  return typeof value === "string" && value.trim() ? `${name}=${value.trim()}` : void 0;
122
138
  }).filter(Boolean).join(" ")).filter(Boolean).join("; ");
@@ -126,9 +142,6 @@ function githubErrorMessage(body) {
126
142
  const graphqlMessages = errors.map((error) => error["message"]).filter((message) => typeof message === "string" && message.trim());
127
143
  return graphqlMessages.length ? graphqlMessages.join("; ") : "GitHub request failed";
128
144
  }
129
- function isRecord$1(value) {
130
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
131
- }
132
145
  // src/tool-support/attribution.ts
133
146
  const GITHUB_REQUEST_ATTRIBUTION_START = "<!-- junior-request-attribution:start -->";
134
147
  const GITHUB_REQUEST_ATTRIBUTION_END = "<!-- junior-request-attribution:end -->";
@@ -638,7 +651,7 @@ function gitHubPullRequestEventGuidance(guidance) {
638
651
  * Junior maintains the pull requests it creates. The pull request is its own
639
652
  * work, so it answers and fixes review feedback without asking first.
640
653
  * GitHub already tells people about reviews, approvals, merges, and closes,
641
- * and the review desk shows the next action. So the Watch gets approvals,
654
+ * and the Inbox shows the next action. So the Watch gets approvals,
642
655
  * merges, and closes only as Quiet Events, and posts in the thread only when
643
656
  * a person must act.
644
657
  */
@@ -1054,10 +1067,30 @@ var GitHubPluginSetupError = class extends Error {
1054
1067
  this.name = "GitHubPluginSetupError";
1055
1068
  }
1056
1069
  };
1057
- /** Return whether a provider value is a JSON object. */
1058
- function isRecord(value) {
1059
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
1060
- }
1070
+ /** GitHub REST error body with a `message`. */
1071
+ const githubMessageSchema = z.object({ message: z.string() });
1072
+ const oauthErrorSchema = z.object({ error: z.string() });
1073
+ const oauthTokenResponseSchema = z.object({
1074
+ access_token: z.unknown().optional(),
1075
+ expires_in: z.unknown().optional(),
1076
+ refresh_token: z.unknown().optional(),
1077
+ refresh_token_expires_in: z.unknown().optional(),
1078
+ scope: z.unknown().optional()
1079
+ });
1080
+ const installationTokenResponseSchema = z.object({
1081
+ expires_at: z.unknown().optional(),
1082
+ token: z.unknown().optional()
1083
+ });
1084
+ const installationPermissionsSchema = z.object({ permissions: z.record(z.string(), z.unknown()) });
1085
+ const userAccountSchema = z.object({
1086
+ html_url: z.unknown().optional(),
1087
+ id: z.unknown().optional(),
1088
+ login: z.unknown().optional()
1089
+ });
1090
+ const verifiedEmailSchema = z.object({
1091
+ email: z.string(),
1092
+ verified: z.literal(true)
1093
+ });
1061
1094
  /** Read a non-empty GitHub plugin environment value. */
1062
1095
  function readEnv(name) {
1063
1096
  const value = process.env[name];
@@ -1142,7 +1175,10 @@ async function githubRequest(apiBase, path, params) {
1142
1175
  } catch {
1143
1176
  parsed = void 0;
1144
1177
  }
1145
- if (!response.ok) throw new GitHubRequestError(isRecord(parsed) && typeof parsed["message"] === "string" ? parsed["message"] : `GitHub API error ${response.status}`, response.status);
1178
+ if (!response.ok) {
1179
+ const error = githubMessageSchema.safeParse(parsed);
1180
+ throw new GitHubRequestError(error.success ? error.data.message : `GitHub API error ${response.status}`, response.status);
1181
+ }
1146
1182
  return parsed;
1147
1183
  }
1148
1184
  function buildOAuthTokenRequest(input) {
@@ -1168,13 +1204,16 @@ function parseOAuthResponseJson(responseText) {
1168
1204
  }
1169
1205
  }
1170
1206
  function oauthErrorCode(data) {
1171
- return isRecord(data) && typeof data["error"] === "string" ? data["error"] : void 0;
1207
+ const parsed = oauthErrorSchema.safeParse(data);
1208
+ return parsed.success ? parsed.data.error : void 0;
1172
1209
  }
1173
1210
  function isRejectedRefreshError(errorCode) {
1174
1211
  return errorCode === "bad_refresh_token" || errorCode === "invalid_grant";
1175
1212
  }
1176
- function parseOAuthTokenResponse(data, requestedScope) {
1177
- if (!isRecord(data)) throw new Error("OAuth token response is invalid");
1213
+ function parseOAuthTokenResponse(value, requestedScope) {
1214
+ const parsed = oauthTokenResponseSchema.safeParse(value);
1215
+ if (!parsed.success) throw new Error("OAuth token response is invalid");
1216
+ const data = parsed.data;
1178
1217
  if (typeof data["access_token"] !== "string" || !data["access_token"].trim()) throw new Error("OAuth token response missing access_token");
1179
1218
  if (typeof data["refresh_token"] !== "string" || !data["refresh_token"].trim()) throw new Error("OAuth token response missing refresh_token");
1180
1219
  let scope = normalizeOAuthScope(requestedScope);
@@ -1268,8 +1307,10 @@ function credentialUnavailable(message) {
1268
1307
  message
1269
1308
  };
1270
1309
  }
1271
- function parseInstallationTokenResponse(data) {
1272
- if (!isRecord(data)) throw new Error("GitHub installation token response is invalid");
1310
+ function parseInstallationTokenResponse(value) {
1311
+ const parsed = installationTokenResponseSchema.safeParse(value);
1312
+ if (!parsed.success) throw new Error("GitHub installation token response is invalid");
1313
+ const data = parsed.data;
1273
1314
  const token = data["token"];
1274
1315
  if (typeof token !== "string" || !token.trim()) throw new Error("GitHub installation token response missing token");
1275
1316
  const expiresAt = data["expires_at"];
@@ -1281,8 +1322,9 @@ function parseInstallationTokenResponse(data) {
1281
1322
  };
1282
1323
  }
1283
1324
  function readInstallationPermissions(installation) {
1284
- if (!isRecord(installation) || !isRecord(installation["permissions"])) throw new Error("GitHub installation response missing permissions");
1285
- return readGrantPermissions(installation["permissions"]);
1325
+ const parsed = installationPermissionsSchema.safeParse(installation);
1326
+ if (!parsed.success) throw new Error("GitHub installation response missing permissions");
1327
+ return readGrantPermissions(parsed.data.permissions);
1286
1328
  }
1287
1329
  function decodeGitHubPathSegment(value) {
1288
1330
  try {
@@ -1314,8 +1356,9 @@ function githubRepositoryFromUrl(upstreamUrl) {
1314
1356
  }
1315
1357
  /** Resolve the GitHub account associated with stored user tokens. */
1316
1358
  async function resolveUserAccount(tokens) {
1317
- const account = await githubRequest("https://api.github.com", "/user", { token: tokens.accessToken });
1318
- if (!isRecord(account)) throw new Error("GitHub user response is invalid");
1359
+ const parsed = userAccountSchema.safeParse(await githubRequest("https://api.github.com", "/user", { token: tokens.accessToken }));
1360
+ if (!parsed.success) throw new Error("GitHub user response is invalid");
1361
+ const account = parsed.data;
1319
1362
  const id = account["id"];
1320
1363
  const login = account["login"];
1321
1364
  if (typeof id !== "number" && typeof id !== "string" || typeof login !== "string" || !login.trim()) throw new Error("GitHub user response missing id or login");
@@ -1342,7 +1385,11 @@ async function listVerifiedUserEmails(tokens) {
1342
1385
  throw error;
1343
1386
  }
1344
1387
  if (!Array.isArray(emails)) throw new Error("GitHub user emails response is invalid");
1345
- return emails.flatMap((entry) => isRecord(entry) && entry["verified"] === true && typeof entry["email"] === "string" && entry["email"].trim() ? [entry["email"].trim()] : []);
1388
+ return emails.flatMap((entry) => {
1389
+ const parsed = verifiedEmailSchema.safeParse(entry);
1390
+ const email = parsed.success ? parsed.data.email.trim() : "";
1391
+ return email ? [email] : [];
1392
+ });
1346
1393
  }
1347
1394
  async function tokensWithAccount(tokenSlot, stored, scope) {
1348
1395
  if (stored.account) return {
@@ -1534,6 +1581,26 @@ function createPermissionCache() {
1534
1581
  return await pending;
1535
1582
  };
1536
1583
  }
1584
+ // src/webhooks/fail-open-log.ts
1585
+ /**
1586
+ * Log a failure of optional webhook work. A GitHub 5xx is a GitHub outage,
1587
+ * not a Junior bug, so it is a warning with the HTTP status. Other failures
1588
+ * stay errors.
1589
+ */
1590
+ function logFailOpenFailure(log, message, error, metadata) {
1591
+ const attributes = {
1592
+ ...metadata,
1593
+ errorType: error instanceof Error ? error.name : "UnknownError"
1594
+ };
1595
+ if (error instanceof GitHubRequestError && error.status >= 500) {
1596
+ log?.warn(message, {
1597
+ ...attributes,
1598
+ "http.response.status_code": error.status
1599
+ });
1600
+ return;
1601
+ }
1602
+ log?.error(message, attributes);
1603
+ }
1537
1604
  // src/webhooks/event-targets.ts
1538
1605
  /**
1539
1606
  * The user who sent a webhook. GitHub authenticates this user, so on a comment
@@ -1626,26 +1693,6 @@ function pullRequestTargets(event, repo) {
1626
1693
  identifier: gitHubRepositoryResource({ repo }).identifier
1627
1694
  }];
1628
1695
  }
1629
- // src/webhooks/fail-open-log.ts
1630
- /**
1631
- * Log a failure of optional webhook work. A GitHub 5xx is a GitHub outage,
1632
- * not a Junior bug, so it is a warning with the HTTP status. Other failures
1633
- * stay errors.
1634
- */
1635
- function logFailOpenFailure(log, message, error, metadata) {
1636
- const attributes = {
1637
- ...metadata,
1638
- errorType: error instanceof Error ? error.name : "UnknownError"
1639
- };
1640
- if (error instanceof GitHubRequestError && error.status >= 500) {
1641
- log?.warn(message, {
1642
- ...attributes,
1643
- "http.response.status_code": error.status
1644
- });
1645
- return;
1646
- }
1647
- log?.error(message, attributes);
1648
- }
1649
1696
  // src/webhooks/check-suite.ts
1650
1697
  /**
1651
1698
  * GitHub check suite events.
@@ -2010,17 +2057,23 @@ function checkRunsFromResponse(value) {
2010
2057
  if (!parsed.success) return [];
2011
2058
  return parsed.data.check_runs ?? [];
2012
2059
  }
2060
+ const pullRequestFactsResponseSchema = z.object({
2061
+ draft: z.boolean().optional().catch(void 0),
2062
+ user: z.object({
2063
+ email: z.string().optional().catch(void 0),
2064
+ login: z.string().optional().catch(void 0)
2065
+ }).optional().catch(void 0)
2066
+ });
2013
2067
  function pullRequestFactsFromResponse(value) {
2014
- if (!isRecord(value)) return void 0;
2068
+ const parsed = pullRequestFactsResponseSchema.safeParse(value);
2069
+ if (!parsed.success) return void 0;
2070
+ const { draft, user } = parsed.data;
2015
2071
  const facts = {};
2016
- if (typeof value["draft"] === "boolean") facts.isDraft = value["draft"];
2017
- const user = value["user"];
2018
- if (isRecord(user)) {
2019
- const username = typeof user["login"] === "string" ? user["login"].trim() : void 0;
2020
- if (username) facts.openerUsername = username;
2021
- const email = typeof user["email"] === "string" ? user["email"].trim() : void 0;
2022
- if (email) facts.openerEmail = email;
2023
- }
2072
+ if (draft !== void 0) facts.isDraft = draft;
2073
+ const username = user?.login?.trim();
2074
+ if (username) facts.openerUsername = username;
2075
+ const email = user?.email?.trim();
2076
+ if (email) facts.openerEmail = email;
2024
2077
  return Object.keys(facts).length > 0 ? facts : void 0;
2025
2078
  }
2026
2079
  /** True when active match filters need pull request fields from the API. */
@@ -2852,4 +2905,4 @@ function normalizeGitHubEvents(args) {
2852
2905
  default: return [];
2853
2906
  }
2854
2907
  }
2855
- export { GITHUB_DEPLOYMENT_EVENTS as $, requireEnv as A, GITHUB_RELEASE_MATCH_FIELDS as B, githubRequest as C, githubErrorMessage as Ct, 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, githubAttachmentLocation as St, issueGitHubCredential as T, repoPath as Tt, 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 _, readGitHubBody as _t, needsCheckSuitePullRequestFacts as a, GITHUB_ISSUE_IDENTIFIER as at, USER_WRITE_REQUIREMENTS as b, startedByPerson as bt, logFailOpenFailure as c, gitHubIssueSubscribable as ct, CREATE_TOOL_ROUTING_GUIDANCE as d, normalizePermissions as dt, GITHUB_DEPLOYMENT_MATCH_FIELDS as et, GITHUB_APP_ID_ENV as f, readGrantPermissions as ft, GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES as g, parseGitHubLogin as gt, GITHUB_AUTH_TOKEN_PLACEHOLDER as h, linkedGitHubLogin as ht, loadCheckSuiteFacts as i, GITHUB_ISSUE_EVENTS as it, resolveUserAccount as j, readEnv as k, definedValues as l, watchGitHubIssue as lt, GITHUB_AUTH_TOKEN_ENV as m, assertGitHubPullRequestRequester as mt, 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, appendGitHubRequesterAttribution as pt, 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, gitHubRepoDataSchema as ut, GitHubRequestError as v, requesterPerson as vt, isRecord as w, parseRepo as wt, createPermissionCache as x, githubApi as xt, HTTP_READ_METHODS as y, resolveGitHubRequester as yt, GITHUB_RELEASE_EVENTS as z };
2908
+ export { GITHUB_DEPLOYMENT_EVENTS as $, requireEnv as A, GITHUB_RELEASE_MATCH_FIELDS as B, githubRepositoryFromUrl as C, githubErrorMessage as Ct, 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, githubMessageSchema as S, githubAttachmentLocation as St, issueGitHubCredential as T, repoPath as Tt, 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 _, readGitHubBody as _t, needsCheckSuitePullRequestFacts as a, GITHUB_ISSUE_IDENTIFIER as at, USER_WRITE_REQUIREMENTS as b, startedByPerson as bt, definedValues as c, gitHubIssueSubscribable as ct, CREATE_TOOL_ROUTING_GUIDANCE as d, normalizePermissions as dt, GITHUB_DEPLOYMENT_MATCH_FIELDS as et, GITHUB_APP_ID_ENV as f, readGrantPermissions as ft, GITHUB_GRAPHQL_RESPONSE_BODY_LIMIT_BYTES as g, parseGitHubLogin as gt, GITHUB_AUTH_TOKEN_PLACEHOLDER as h, linkedGitHubLogin as ht, loadCheckSuiteFacts as i, GITHUB_ISSUE_EVENTS as it, resolveUserAccount as j, readEnv as k, pullRequestTargets as l, watchGitHubIssue as lt, GITHUB_AUTH_TOKEN_ENV as m, assertGitHubPullRequestRequester as mt, 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, appendGitHubRequesterAttribution as pt, 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, logFailOpenFailure as u, gitHubRepoDataSchema as ut, GitHubRequestError as v, requesterPerson as vt, githubRequest as w, parseRepo as wt, createPermissionCache as x, githubApi as xt, HTTP_READ_METHODS as y, resolveGitHubRequester as yt, GITHUB_RELEASE_EVENTS as z };