@socketsecurity/cli-with-sentry 1.0.20 → 1.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/cli.js +349 -326
  2. package/dist/cli.js.map +1 -1
  3. package/dist/constants.js +4 -4
  4. package/dist/constants.js.map +1 -1
  5. package/dist/shadow-npm-inject.js +64 -7
  6. package/dist/shadow-npm-inject.js.map +1 -1
  7. package/dist/types/commands/audit-log/output-audit-log.d.mts.map +1 -1
  8. package/dist/types/commands/fix/agent-fix.d.mts +3 -5
  9. package/dist/types/commands/fix/agent-fix.d.mts.map +1 -1
  10. package/dist/types/commands/fix/fix-branch-helpers.d.mts +3 -4
  11. package/dist/types/commands/fix/fix-branch-helpers.d.mts.map +1 -1
  12. package/dist/types/commands/fix/fix-env-helpers.d.mts +9 -9
  13. package/dist/types/commands/fix/fix-env-helpers.d.mts.map +1 -1
  14. package/dist/types/commands/fix/git.d.mts +1 -0
  15. package/dist/types/commands/fix/git.d.mts.map +1 -1
  16. package/dist/types/commands/fix/handle-fix.d.mts.map +1 -1
  17. package/dist/types/commands/fix/npm-fix.d.mts.map +1 -1
  18. package/dist/types/commands/fix/pnpm-fix.d.mts.map +1 -1
  19. package/dist/types/commands/fix/{open-pr.d.mts → pull-request.d.mts} +11 -6
  20. package/dist/types/commands/fix/pull-request.d.mts.map +1 -0
  21. package/dist/types/commands/fix/shared.d.mts +1 -2
  22. package/dist/types/commands/fix/shared.d.mts.map +1 -1
  23. package/dist/types/commands/manifest/cmd-manifest-cdxgen.d.mts.map +1 -1
  24. package/dist/types/commands/manifest/cmd-manifest-gradle.d.mts.map +1 -1
  25. package/dist/types/commands/manifest/cmd-manifest-kotlin.d.mts.map +1 -1
  26. package/dist/types/commands/manifest/cmd-manifest-scala.d.mts.map +1 -1
  27. package/dist/types/commands/manifest/detect-manifest-actions.d.mts.map +1 -1
  28. package/dist/types/commands/optimize/update-lockfile.d.mts.map +1 -1
  29. package/dist/types/commands/repository/fetch-list-all-repos.d.mts.map +1 -1
  30. package/dist/types/commands/scan/fetch-report-data.d.mts.map +1 -1
  31. package/dist/types/commands/scan/fetch-scan.d.mts.map +1 -1
  32. package/dist/types/commands/wrapper/postinstall-wrapper.d.mts.map +1 -1
  33. package/dist/types/shadow/npm/arborist-helpers.d.mts.map +1 -1
  34. package/dist/types/utils/alerts-map.d.mts +0 -1
  35. package/dist/types/utils/alerts-map.d.mts.map +1 -1
  36. package/dist/types/utils/api.d.mts.map +1 -1
  37. package/dist/types/utils/npm-config.d.mts +14 -0
  38. package/dist/types/utils/npm-config.d.mts.map +1 -0
  39. package/dist/types/utils/npm-paths.d.mts +2 -2
  40. package/dist/types/utils/npm-paths.d.mts.map +1 -1
  41. package/dist/types/utils/package-environment.d.mts.map +1 -1
  42. package/dist/types/utils/path-resolve.d.mts.map +1 -1
  43. package/dist/types/utils/socket-package-alert.d.mts +1 -2
  44. package/dist/types/utils/socket-package-alert.d.mts.map +1 -1
  45. package/dist/types/utils/socketjson.d.mts.map +1 -1
  46. package/dist/utils.js +148 -70
  47. package/dist/utils.js.map +1 -1
  48. package/dist/vendor.js +66962 -66962
  49. package/external/@coana-tech/cli/cli.mjs +60278 -55993
  50. package/external/@socketsecurity/registry/external/@inquirer/confirm.js +1 -1
  51. package/external/@socketsecurity/registry/external/@inquirer/input.js +10 -2
  52. package/external/@socketsecurity/registry/external/@inquirer/password.js +1 -1
  53. package/external/@socketsecurity/registry/external/@inquirer/search.js +1 -1
  54. package/external/@socketsecurity/registry/external/@inquirer/select.js +1 -1
  55. package/external/@socketsecurity/registry/external/browserslist.js +572 -570
  56. package/external/@socketsecurity/registry/external/debug.js +1163 -0
  57. package/external/@socketsecurity/registry/lib/constants/env.js +9 -4
  58. package/external/@socketsecurity/registry/lib/debug.js +139 -47
  59. package/external/@socketsecurity/registry/lib/logger.js +2 -2
  60. package/external/@socketsecurity/registry/lib/packages.js +1 -2
  61. package/package.json +18 -18
  62. package/dist/types/commands/fix/open-pr.d.mts.map +0 -1
  63. package/dist/types/shadow/npm/proc-log/index.d.mts +0 -3
  64. package/dist/types/shadow/npm/proc-log/index.d.mts.map +0 -1
package/dist/cli.js CHANGED
@@ -22,8 +22,8 @@ var sorts = require('../external/@socketsecurity/registry/lib/sorts');
22
22
  var strings = require('../external/@socketsecurity/registry/lib/strings');
23
23
  var path$1 = require('../external/@socketsecurity/registry/lib/path');
24
24
  var regexps = require('../external/@socketsecurity/registry/lib/regexps');
25
- var shadowNpmInject = require('./shadow-npm-inject.js');
26
25
  var fs$2 = require('../external/@socketsecurity/registry/lib/fs');
26
+ var shadowNpmInject = require('./shadow-npm-inject.js');
27
27
  var objects = require('../external/@socketsecurity/registry/lib/objects');
28
28
  var shadowNpmBin = require('./shadow-npm-bin.js');
29
29
  var require$$7 = require('../external/@socketsecurity/registry/lib/promises');
@@ -591,7 +591,10 @@ ${table}
591
591
  } catch (e) {
592
592
  process.exitCode = 1;
593
593
  logger.logger.fail('There was a problem converting the logs to Markdown, please try the `--json` flag');
594
- debug.debugFn('catch: unexpected\n', e);
594
+ debug.debugFn('error', 'caught: unexpected error');
595
+ debug.debugDir('inspect', {
596
+ error: e
597
+ });
595
598
  return 'Failed to generate the markdown report';
596
599
  }
597
600
  }
@@ -863,7 +866,7 @@ async function run$O(argv, importMeta, {
863
866
  async function getDefaultOrgSlug() {
864
867
  const defaultOrgResult = utils.getConfigValueOrUndef('defaultOrg');
865
868
  if (defaultOrgResult) {
866
- debug.debugFn('use: default org', defaultOrgResult);
869
+ debug.debugFn('notice', 'use: default org', defaultOrgResult);
867
870
  return {
868
871
  ok: true,
869
872
  data: defaultOrgResult
@@ -895,7 +898,7 @@ async function getDefaultOrgSlug() {
895
898
  data: `Was unable to determine the default organization for the current API token. Unable to continue.`
896
899
  };
897
900
  }
898
- debug.debugFn('resolve: org', slug);
901
+ debug.debugFn('notice', 'resolve: org', slug);
899
902
  return {
900
903
  ok: true,
901
904
  message: 'Retrieved default org from server',
@@ -999,7 +1002,10 @@ async function fetchReportData(orgSlug, scanId, includeLicensePolicy) {
999
1002
  return JSON.parse(line);
1000
1003
  } catch {
1001
1004
  ok = false;
1002
- debug.debugFn('fail: parse NDJSON\n', line);
1005
+ debug.debugFn('error', 'fail: parse NDJSON');
1006
+ debug.debugDir('inspect', {
1007
+ line
1008
+ });
1003
1009
  return;
1004
1010
  }
1005
1011
  });
@@ -1497,28 +1503,28 @@ sockJson, cwd = process.cwd()) {
1497
1503
  sbt: false
1498
1504
  };
1499
1505
  if (sockJson?.defaults?.manifest?.sbt?.disabled) {
1500
- debug.debugLog('[DEBUG] - sbt auto-detection is disabled in socket.json');
1506
+ debug.debugLog('notice', '[DEBUG] - sbt auto-detection is disabled in socket.json');
1501
1507
  } else if (fs$1.existsSync(path.join(cwd, 'build.sbt'))) {
1502
- debug.debugLog('[DEBUG] - Detected a Scala sbt build file');
1508
+ debug.debugLog('notice', '[DEBUG] - Detected a Scala sbt build file');
1503
1509
  output.sbt = true;
1504
1510
  output.count += 1;
1505
1511
  }
1506
1512
  if (sockJson?.defaults?.manifest?.gradle?.disabled) {
1507
- debug.debugLog('[DEBUG] - gradle auto-detection is disabled in socket.json');
1513
+ debug.debugLog('notice', '[DEBUG] - gradle auto-detection is disabled in socket.json');
1508
1514
  } else if (fs$1.existsSync(path.join(cwd, 'gradlew'))) {
1509
- debug.debugLog('[DEBUG] - Detected a gradle build file');
1515
+ debug.debugLog('notice', '[DEBUG] - Detected a gradle build file');
1510
1516
  output.gradle = true;
1511
1517
  output.count += 1;
1512
1518
  }
1513
1519
  if (sockJson?.defaults?.manifest?.conda?.disabled) {
1514
- debug.debugLog('[DEBUG] - conda auto-detection is disabled in socket.json');
1520
+ debug.debugLog('notice', '[DEBUG] - conda auto-detection is disabled in socket.json');
1515
1521
  } else {
1516
1522
  const envyml = path.join(cwd, 'environment.yml');
1517
1523
  const hasEnvyml = fs$1.existsSync(envyml);
1518
1524
  const envyaml = path.join(cwd, 'environment.yaml');
1519
1525
  const hasEnvyaml = !hasEnvyml && fs$1.existsSync(envyaml);
1520
1526
  if (hasEnvyml || hasEnvyaml) {
1521
- debug.debugLog('[DEBUG] - Detected an environment.yml Conda file');
1527
+ debug.debugLog('notice', '[DEBUG] - Detected an environment.yml Conda file');
1522
1528
  output.conda = true;
1523
1529
  output.count += 1;
1524
1530
  }
@@ -2992,6 +2998,7 @@ function createSocketBranchParser(options) {
2992
2998
  };
2993
2999
  };
2994
3000
  }
3001
+ const genericSocketBranchParser = createSocketBranchParser();
2995
3002
  async function getBaseGitBranch(cwd = process.cwd()) {
2996
3003
  // Lazily access constants.ENV properties.
2997
3004
  const {
@@ -3024,17 +3031,17 @@ async function getBaseGitBranch(cwd = process.cwd()) {
3024
3031
  }
3025
3032
  function getSocketBranchFullNameComponent(pkgName) {
3026
3033
  const purlObj = utils.getPurlObject(typeof pkgName === 'string' && !pkgName.startsWith('pkg:') ? vendor.packageurlJsExports.PackageURL.fromString(`pkg:unknown/${pkgName}`) : pkgName);
3027
- const fmtMaybeNamespace = purlObj.namespace ? `${formatBranchName(purlObj.namespace)}--` : '';
3028
- return `${fmtMaybeNamespace}${formatBranchName(purlObj.name)}`;
3034
+ const branchMaybeNamespace = purlObj.namespace ? `${formatBranchName(purlObj.namespace)}--` : '';
3035
+ return `${branchMaybeNamespace}${formatBranchName(purlObj.name)}`;
3029
3036
  }
3030
3037
  function getSocketBranchName(purl, newVersion, workspace) {
3031
3038
  const purlObj = utils.getPurlObject(purl);
3032
- const fmtType = getSocketBranchPurlTypeComponent(purlObj);
3033
- const fmtWorkspace = getSocketBranchWorkspaceComponent(workspace);
3034
- const fmtFullName = getSocketBranchFullNameComponent(purlObj);
3035
- const fmtVersion = getSocketBranchPackageVersionComponent(purlObj.version);
3036
- const fmtNewVersion = formatBranchName(newVersion);
3037
- return `socket/${fmtType}/${fmtWorkspace}/${fmtFullName}_${fmtVersion}_${fmtNewVersion}`;
3039
+ const branchType = getSocketBranchPurlTypeComponent(purlObj);
3040
+ const branchWorkspace = getSocketBranchWorkspaceComponent(workspace);
3041
+ const branchFullName = getSocketBranchFullNameComponent(purlObj);
3042
+ const branchVersion = getSocketBranchPackageVersionComponent(purlObj.version);
3043
+ const branchNewVersion = formatBranchName(newVersion);
3044
+ return `socket/${branchType}/${branchWorkspace}/${branchFullName}_${branchVersion}_${branchNewVersion}`;
3038
3045
  }
3039
3046
  function getSocketBranchPackageVersionComponent(version) {
3040
3047
  const purlObj = utils.getPurlObject(typeof version === 'string' && !version.startsWith('pkg:') ? vendor.packageurlJsExports.PackageURL.fromString(`pkg:unknown/unknown@${version}`) : version);
@@ -3112,7 +3119,7 @@ async function gitCreateAndPushBranch(branch, commitMsg, filepaths, options) {
3112
3119
  await spawn.spawn('git', ['push', '--force', '--set-upstream', 'origin', branch], stdioIgnoreOptions);
3113
3120
  return true;
3114
3121
  } catch (e) {
3115
- debug.debugFn(`catch: git push --force --set-upstream origin ${branch} failed\n`, e);
3122
+ debug.debugFn('error', `caught: git push --force --set-upstream origin ${branch} failed\n`, e);
3116
3123
  }
3117
3124
  try {
3118
3125
  // Will throw with exit code 1 if branch does not exist.
@@ -3146,9 +3153,15 @@ async function gitRepoInfo(cwd = process.cwd()) {
3146
3153
  };
3147
3154
  }
3148
3155
  } catch {}
3149
- debug.debugFn('git: unmatched git remote URL format', remoteUrl);
3156
+ debug.debugFn('error', 'git: unmatched git remote URL format');
3157
+ debug.debugDir('inspect', {
3158
+ remoteUrl
3159
+ });
3150
3160
  } catch (e) {
3151
- debug.debugFn('catch: git remote get-url origin failed\n', e);
3161
+ debug.debugFn('error', 'caught: `git remote get-url origin` failed');
3162
+ debug.debugDir('inspect', {
3163
+ error: e
3164
+ });
3152
3165
  }
3153
3166
  return null;
3154
3167
  }
@@ -3174,7 +3187,10 @@ async function gitEnsureIdentity(name, email, cwd = process.cwd()) {
3174
3187
  try {
3175
3188
  await spawn.spawn('git', ['config', prop, value], stdioIgnoreOptions);
3176
3189
  } catch (e) {
3177
- debug.debugFn(`catch: git config ${prop} ${value} failed\n`, e);
3190
+ debug.debugFn('error', `caught: git config ${prop} ${value} failed`);
3191
+ debug.debugDir('inspect', {
3192
+ error: e
3193
+ });
3178
3194
  }
3179
3195
  }
3180
3196
  }));
@@ -3213,7 +3229,10 @@ async function gitUnstagedModifiedFiles(cwd = process.cwd()) {
3213
3229
  data: rawRelPaths.map(relPath => path$1.normalizePath(relPath))
3214
3230
  };
3215
3231
  } catch (e) {
3216
- debug.debugFn('catch: git diff --name-only failed\n', e);
3232
+ debug.debugFn('error', 'caught: git diff --name-only failed');
3233
+ debug.debugDir('inspect', {
3234
+ error: e
3235
+ });
3217
3236
  return {
3218
3237
  ok: false,
3219
3238
  message: 'Git Error',
@@ -3222,41 +3241,32 @@ async function gitUnstagedModifiedFiles(cwd = process.cwd()) {
3222
3241
  }
3223
3242
  }
3224
3243
 
3225
- function getActiveBranchesForPackage(ciEnv, partialPurl, openPrs) {
3226
- if (!ciEnv) {
3244
+ function getPrsForPurl(fixEnv, partialPurl) {
3245
+ if (!fixEnv) {
3227
3246
  return [];
3228
3247
  }
3229
- const activeBranches = [];
3248
+ const prs = [];
3230
3249
  const partialPurlObj = utils.getPurlObject(partialPurl);
3231
3250
  const branchFullName = getSocketBranchFullNameComponent(partialPurlObj);
3232
3251
  const branchPurlType = getSocketBranchPurlTypeComponent(partialPurlObj);
3233
- for (const pr of openPrs) {
3234
- const parsedBranch = ciEnv.branchParser(pr.headRefName);
3252
+ for (const pr of fixEnv.prs) {
3253
+ const parsedBranch = genericSocketBranchParser(pr.headRefName);
3235
3254
  if (branchPurlType === parsedBranch?.type && branchFullName === parsedBranch?.fullName) {
3236
- activeBranches.push(parsedBranch);
3255
+ prs.push(pr);
3237
3256
  }
3238
3257
  }
3239
- if (debug.isDebug()) {
3258
+ if (debug.isDebug('notice,inspect')) {
3240
3259
  const fullName = packages.resolvePackageName(partialPurlObj);
3241
- if (activeBranches.length) {
3242
- debug.debugFn(`found: ${activeBranches.length} active branches for ${fullName}\n`, activeBranches);
3243
- } else if (openPrs.length) {
3244
- debug.debugFn(`miss: 0 active branches found for ${fullName}`);
3260
+ if (prs.length) {
3261
+ debug.debugFn('notice', `found: ${prs.length} PRs for ${fullName}`);
3262
+ debug.debugDir('inspect', {
3263
+ prs
3264
+ });
3265
+ } else if (fixEnv.prs.length) {
3266
+ debug.debugFn('notice', `miss: 0 PRs found for ${fullName}`);
3245
3267
  }
3246
3268
  }
3247
- return activeBranches;
3248
- }
3249
-
3250
- async function getActualTree(cwd = process.cwd()) {
3251
- // @npmcli/arborist DOES have partial support for pnpm structured node_modules
3252
- // folders. However, support is iffy resulting in unhappy path errors and hangs.
3253
- // So, to avoid the unhappy path, we restrict our usage to --dry-run loading
3254
- // of the node_modules folder.
3255
- const arb = new shadowNpmInject.Arborist({
3256
- path: cwd,
3257
- ...shadowNpmInject.SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES
3258
- });
3259
- return await arb.loadActual();
3269
+ return prs;
3260
3270
  }
3261
3271
 
3262
3272
  let _octokit;
@@ -3267,7 +3277,7 @@ function getOctokit() {
3267
3277
  SOCKET_CLI_GITHUB_TOKEN
3268
3278
  } = constants.ENV;
3269
3279
  if (!SOCKET_CLI_GITHUB_TOKEN) {
3270
- debug.debugFn('miss: SOCKET_CLI_GITHUB_TOKEN env var');
3280
+ debug.debugFn('notice', 'miss: SOCKET_CLI_GITHUB_TOKEN env var');
3271
3281
  }
3272
3282
  _octokit = new vendor.Octokit({
3273
3283
  auth: SOCKET_CLI_GITHUB_TOKEN
@@ -3283,7 +3293,7 @@ function getOctokitGraphql() {
3283
3293
  SOCKET_CLI_GITHUB_TOKEN
3284
3294
  } = constants.ENV;
3285
3295
  if (!SOCKET_CLI_GITHUB_TOKEN) {
3286
- debug.debugFn('miss: SOCKET_CLI_GITHUB_TOKEN env var');
3296
+ debug.debugFn('notice', 'miss: SOCKET_CLI_GITHUB_TOKEN env var');
3287
3297
  }
3288
3298
  _octokitGraphql = vendor.graphql2.defaults({
3289
3299
  headers: {
@@ -3333,8 +3343,8 @@ async function writeCache(key, data) {
3333
3343
  }
3334
3344
  await fs$2.writeJson(cacheJsonPath, data);
3335
3345
  }
3336
- async function cleanupOpenPrs(owner, repo, options) {
3337
- const contextualMatches = await getOpenSocketPrsWithContext(owner, repo, options);
3346
+ async function cleanupPrs(owner, repo, options) {
3347
+ const contextualMatches = await getSocketPrsWithContext(owner, repo, options);
3338
3348
  if (!contextualMatches.length) {
3339
3349
  return [];
3340
3350
  }
@@ -3367,14 +3377,14 @@ async function cleanupOpenPrs(owner, repo, options) {
3367
3377
  pull_number: prNum,
3368
3378
  state: 'closed'
3369
3379
  });
3370
- debug.debugFn(`close: ${prRef} for ${prToVersion}`);
3380
+ debug.debugFn('notice', `close: ${prRef} for ${prToVersion}`);
3371
3381
  // Remove entry from parent object.
3372
3382
  context.parent.splice(context.index, 1);
3373
3383
  // Mark cache to be saved.
3374
3384
  cachesToSave.set(context.cacheKey, context.data);
3375
3385
  return null;
3376
3386
  } catch (e) {
3377
- debug.debugFn(`fail: close ${prRef} for ${prToVersion}\n`, e?.message || 'unknown error');
3387
+ debug.debugFn('error', `fail: close ${prRef} for ${prToVersion}\n`, e?.message || 'unknown error');
3378
3388
  }
3379
3389
  }
3380
3390
  // Update stale PRs.
@@ -3387,7 +3397,7 @@ async function cleanupOpenPrs(owner, repo, options) {
3387
3397
  base: match.headRefName,
3388
3398
  head: match.baseRefName
3389
3399
  });
3390
- debug.debugFn('update: stale', prRef);
3400
+ debug.debugFn('notice', 'update: stale', prRef);
3391
3401
  // Update entry entry.
3392
3402
  if (context.apiType === 'graphql') {
3393
3403
  context.entry.mergeStateStatus = 'CLEAN';
@@ -3398,7 +3408,7 @@ async function cleanupOpenPrs(owner, repo, options) {
3398
3408
  cachesToSave.set(context.cacheKey, context.data);
3399
3409
  } catch (e) {
3400
3410
  const message = e?.message || 'Unknown error';
3401
- debug.debugFn(`fail: update ${prRef} - ${message}`);
3411
+ debug.debugFn('error', `fail: update ${prRef} - ${message}`);
3402
3412
  }
3403
3413
  }
3404
3414
  return match;
@@ -3453,30 +3463,30 @@ async function enablePrAutoMerge({
3453
3463
  enabled: false
3454
3464
  };
3455
3465
  }
3456
- async function getOpenSocketPrs(owner, repo, options) {
3457
- return (await getOpenSocketPrsWithContext(owner, repo, options)).map(d => d.match);
3466
+ async function getSocketPrs(owner, repo, options) {
3467
+ return (await getSocketPrsWithContext(owner, repo, options)).map(d => d.match);
3458
3468
  }
3459
- async function getOpenSocketPrsWithContext(owner, repo, options_) {
3460
- const options = {
3469
+ async function getSocketPrsWithContext(owner, repo, options) {
3470
+ const {
3471
+ author,
3472
+ states: statesValue = 'all'
3473
+ } = {
3461
3474
  __proto__: null,
3462
- ...options_
3475
+ ...options
3463
3476
  };
3464
- const {
3465
- author
3466
- } = options;
3467
3477
  const checkAuthor = strings.isNonEmptyString(author);
3468
3478
  const octokit = getOctokit();
3469
3479
  const octokitGraphql = getOctokitGraphql();
3470
- const branchPattern = getSocketBranchPattern(options);
3471
3480
  const contextualMatches = [];
3481
+ const states = (typeof statesValue === 'string' ? statesValue.toLowerCase() === 'all' ? ['OPEN', 'CLOSED', 'MERGED'] : [statesValue] : statesValue).map(s => s.toUpperCase());
3472
3482
  try {
3473
3483
  // Optimistically fetch only the first 50 open PRs using GraphQL to minimize
3474
3484
  // API quota usage. Fallback to REST if no matching PRs are found.
3475
3485
  const gqlCacheKey = `${repo}-pr-graphql-snapshot`;
3476
3486
  const gqlResp = await cacheFetch(gqlCacheKey, () => octokitGraphql(`
3477
- query($owner: String!, $repo: String!) {
3487
+ query($owner: String!, $repo: String!, $states: [PullRequestState!]) {
3478
3488
  repository(owner: $owner, name: $repo) {
3479
- pullRequests(first: 50, states: OPEN, orderBy: {field: CREATED_AT, direction: DESC}) {
3489
+ pullRequests(first: 50, states: $states, orderBy: {field: CREATED_AT, direction: DESC}) {
3480
3490
  nodes {
3481
3491
  author {
3482
3492
  login
@@ -3485,6 +3495,7 @@ async function getOpenSocketPrsWithContext(owner, repo, options_) {
3485
3495
  headRefName
3486
3496
  mergeStateStatus
3487
3497
  number
3498
+ state
3488
3499
  title
3489
3500
  }
3490
3501
  }
@@ -3492,7 +3503,8 @@ async function getOpenSocketPrsWithContext(owner, repo, options_) {
3492
3503
  }
3493
3504
  `, {
3494
3505
  owner,
3495
- repo
3506
+ repo,
3507
+ states
3496
3508
  }));
3497
3509
  const nodes = gqlResp?.repository?.pullRequests?.nodes ?? [];
3498
3510
  for (let i = 0, {
@@ -3501,8 +3513,8 @@ async function getOpenSocketPrsWithContext(owner, repo, options_) {
3501
3513
  const node = nodes[i];
3502
3514
  const login = node.author?.login;
3503
3515
  const matchesAuthor = checkAuthor ? login === author : true;
3504
- const matchesBranch = branchPattern.test(node.headRefName);
3505
- if (matchesAuthor && matchesBranch) {
3516
+ const parsedBranch = genericSocketBranchParser(node.headRefName);
3517
+ if (matchesAuthor && parsedBranch) {
3506
3518
  contextualMatches.push({
3507
3519
  context: {
3508
3520
  apiType: 'graphql',
@@ -3514,7 +3526,8 @@ async function getOpenSocketPrsWithContext(owner, repo, options_) {
3514
3526
  },
3515
3527
  match: {
3516
3528
  ...node,
3517
- author: login ?? '<unknown>'
3529
+ author: login ?? '<unknown>',
3530
+ parsedBranch
3518
3531
  }
3519
3532
  });
3520
3533
  }
@@ -3525,44 +3538,52 @@ async function getOpenSocketPrsWithContext(owner, repo, options_) {
3525
3538
  }
3526
3539
 
3527
3540
  // Fallback to REST if GraphQL found no matching PRs.
3528
- let allOpenPrs;
3529
- const cacheKey = `${repo}-open-prs`;
3541
+ let allPrs;
3542
+ const cacheKey = `${repo}-pull-requests`;
3530
3543
  try {
3531
- allOpenPrs = await cacheFetch(cacheKey, async () => await octokit.paginate(octokit.pulls.list, {
3544
+ allPrs = await cacheFetch(cacheKey, async () => await octokit.paginate(octokit.pulls.list, {
3532
3545
  owner,
3533
3546
  repo,
3534
- state: 'open',
3547
+ state: 'all',
3535
3548
  per_page: 100
3536
3549
  }));
3537
3550
  } catch {}
3538
- if (!allOpenPrs) {
3551
+ if (!allPrs) {
3539
3552
  return contextualMatches;
3540
3553
  }
3541
3554
  for (let i = 0, {
3542
3555
  length
3543
- } = allOpenPrs; i < length; i += 1) {
3544
- const pr = allOpenPrs[i];
3556
+ } = allPrs; i < length; i += 1) {
3557
+ const pr = allPrs[i];
3545
3558
  const login = pr.user?.login;
3559
+ const headRefName = pr.head.ref;
3546
3560
  const matchesAuthor = checkAuthor ? login === author : true;
3547
- const matchesBranch = branchPattern.test(pr.head.ref);
3548
- if (matchesAuthor && matchesBranch) {
3561
+ const parsedBranch = genericSocketBranchParser(headRefName);
3562
+ if (matchesAuthor && parsedBranch) {
3563
+ // Upper cased mergeable_state is equivalent to mergeStateStatus.
3564
+ // https://docs.github.com/en/rest/pulls/pulls?apiVersion=2022-11-28#get-a-pull-request
3565
+ const mergeStateStatus = pr.mergeable_state?.toUpperCase?.() ?? 'UNKNOWN';
3566
+ // The REST API does not have a distinct merged state for pull requests.
3567
+ // Instead, a merged pull request is represented as a closed pull request
3568
+ // with a non-null merged_at timestamp.
3569
+ const state = pr.merged_at ? 'MERGED' : pr.state.toUpperCase();
3549
3570
  contextualMatches.push({
3550
3571
  context: {
3551
3572
  apiType: 'rest',
3552
3573
  cacheKey,
3553
- data: allOpenPrs,
3574
+ data: allPrs,
3554
3575
  entry: pr,
3555
3576
  index: i,
3556
- parent: allOpenPrs
3577
+ parent: allPrs
3557
3578
  },
3558
3579
  match: {
3559
3580
  author: login ?? '<unknown>',
3560
3581
  baseRefName: pr.base.ref,
3561
- headRefName: pr.head.ref,
3562
- // Upper cased mergeable_state is equivalent to mergeStateStatus.
3563
- // https://docs.github.com/en/rest/pulls/pulls?apiVersion=2022-11-28#get-a-pull-request
3564
- mergeStateStatus: pr.mergeable_state?.toUpperCase?.() ?? 'UNKNOWN',
3582
+ headRefName,
3583
+ mergeStateStatus,
3565
3584
  number: pr.number,
3585
+ parsedBranch,
3586
+ state,
3566
3587
  title: pr.title
3567
3588
  }
3568
3589
  });
@@ -3596,26 +3617,10 @@ async function openPr(owner, repo, branch, purl, newVersion, options) {
3596
3617
  const details = errors.map(d => `- ${d.message?.trim() ?? `${d.resource}.${d.field} (${d.code})`}`).join('\n');
3597
3618
  message += `:\n${details}`;
3598
3619
  }
3599
- debug.debugFn(message);
3620
+ debug.debugFn('error', message);
3600
3621
  }
3601
3622
  return null;
3602
3623
  }
3603
- async function prExistForBranch(owner, repo, branch) {
3604
- const octokit = getOctokit();
3605
- try {
3606
- const {
3607
- data: prs
3608
- } = await octokit.pulls.list({
3609
- owner,
3610
- repo,
3611
- head: `${owner}:${branch}`,
3612
- state: 'open',
3613
- per_page: 1
3614
- });
3615
- return prs.length > 0;
3616
- } catch {}
3617
- return false;
3618
- }
3619
3624
  async function setGitRemoteGithubRepoUrl(owner, repo, token, cwd = process.cwd()) {
3620
3625
  const stdioIgnoreOptions = {
3621
3626
  cwd,
@@ -3625,8 +3630,72 @@ async function setGitRemoteGithubRepoUrl(owner, repo, token, cwd = process.cwd()
3625
3630
  try {
3626
3631
  await spawn.spawn('git', ['remote', 'set-url', 'origin', url], stdioIgnoreOptions);
3627
3632
  } catch (e) {
3628
- debug.debugFn('catch: unexpected\n', e);
3633
+ debug.debugFn('error', 'caught: unexpected error');
3634
+ debug.debugDir('inspect', {
3635
+ error: e
3636
+ });
3637
+ }
3638
+ }
3639
+
3640
+ function ciRepoInfo() {
3641
+ // Lazily access constants.ENV.GITHUB_REPOSITORY.
3642
+ const {
3643
+ GITHUB_REPOSITORY
3644
+ } = constants.ENV;
3645
+ if (!GITHUB_REPOSITORY) {
3646
+ debug.debugFn('notice', 'miss: GITHUB_REPOSITORY env var');
3629
3647
  }
3648
+ const ownerSlashRepo = GITHUB_REPOSITORY;
3649
+ const slashIndex = ownerSlashRepo.indexOf('/');
3650
+ if (slashIndex === -1) {
3651
+ return null;
3652
+ }
3653
+ return {
3654
+ owner: ownerSlashRepo.slice(0, slashIndex),
3655
+ repo: ownerSlashRepo.slice(slashIndex + 1)
3656
+ };
3657
+ }
3658
+ async function getFixEnv() {
3659
+ const baseBranch = await getBaseGitBranch();
3660
+ const gitEmail = constants.ENV.SOCKET_CLI_GIT_USER_EMAIL;
3661
+ const gitUser = constants.ENV.SOCKET_CLI_GIT_USER_NAME;
3662
+ const githubToken = constants.ENV.SOCKET_CLI_GITHUB_TOKEN;
3663
+ const isCi = !!(constants.ENV.CI && gitEmail && gitUser && githubToken);
3664
+ let repoInfo = null;
3665
+ if (isCi) {
3666
+ repoInfo = ciRepoInfo();
3667
+ }
3668
+ if (!repoInfo) {
3669
+ if (isCi) {
3670
+ debug.debugFn('notice', 'falling back to `git remote get-url origin`');
3671
+ }
3672
+ repoInfo = await gitRepoInfo();
3673
+ }
3674
+ const prs = isCi && repoInfo ? await getSocketPrs(repoInfo.owner, repoInfo.repo, {
3675
+ author: gitUser,
3676
+ states: 'all'
3677
+ }) : [];
3678
+ return {
3679
+ baseBranch,
3680
+ gitEmail,
3681
+ githubToken,
3682
+ gitUser,
3683
+ isCi,
3684
+ prs,
3685
+ repoInfo
3686
+ };
3687
+ }
3688
+
3689
+ async function getActualTree(cwd = process.cwd()) {
3690
+ // @npmcli/arborist DOES have partial support for pnpm structured node_modules
3691
+ // folders. However, support is iffy resulting in unhappy path errors and hangs.
3692
+ // So, to avoid the unhappy path, we restrict our usage to --dry-run loading
3693
+ // of the node_modules folder.
3694
+ const arb = new shadowNpmInject.Arborist({
3695
+ path: cwd,
3696
+ ...shadowNpmInject.SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES
3697
+ });
3698
+ return await arb.loadActual();
3630
3699
  }
3631
3700
 
3632
3701
  const {
@@ -3717,10 +3786,11 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3717
3786
  // eslint-disable-next-line sort-destructure-keys/sort-destructure-keys
3718
3787
  afterInstall = noopHandler,
3719
3788
  revertInstall = noopHandler
3720
- }, ciEnv, openPrs, fixConfig) {
3789
+ }, fixConfig) {
3721
3790
  const {
3722
3791
  pkgPath: rootPath
3723
3792
  } = pkgEnvDetails;
3793
+ const fixEnv = await getFixEnv();
3724
3794
  const {
3725
3795
  autoMerge,
3726
3796
  cwd,
@@ -3733,17 +3803,19 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3733
3803
  } = fixConfig;
3734
3804
  let count = 0;
3735
3805
  const infoByPartialPurl = utils.getCveInfoFromAlertsMap(alertsMap, {
3736
- limit: Math.max(limit, openPrs.length)
3806
+ exclude: {
3807
+ upgradable: true
3808
+ }
3737
3809
  });
3738
3810
  if (!infoByPartialPurl) {
3739
3811
  spinner?.stop();
3740
3812
  logger.logger.info('No fixable vulns found.');
3741
3813
  if (alertsMap.size) {
3742
- debug.debugFn('inspect:', {
3814
+ debug.debugDir('inspect', {
3743
3815
  alertsMap
3744
3816
  });
3745
3817
  } else {
3746
- debug.debugFn('inspect: { alertsMap: Map(0) {} }');
3818
+ debug.debugFn('inspect', '{ alertsMap: Map(0) {} }');
3747
3819
  }
3748
3820
  return {
3749
3821
  ok: true,
@@ -3752,8 +3824,17 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3752
3824
  }
3753
3825
  };
3754
3826
  }
3755
- if (debug.isDebug()) {
3756
- debug.debugFn('found: cves for', Array.from(infoByPartialPurl.keys()));
3827
+ if (debug.isDebug('notice,inspect')) {
3828
+ spinner?.stop();
3829
+ const partialPurls = Array.from(infoByPartialPurl.keys());
3830
+ const {
3831
+ length: purlsCount
3832
+ } = partialPurls;
3833
+ debug.debugFn('notice', `found: ${purlsCount} ${words.pluralize('PURL', purlsCount)} with CVEs`);
3834
+ debug.debugDir('inspect', {
3835
+ partialPurls
3836
+ });
3837
+ spinner?.start();
3757
3838
  }
3758
3839
 
3759
3840
  // Lazily access constants.packumentCache.
@@ -3788,13 +3869,14 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3788
3869
  const name = packages.resolvePackageName(partialPurlObj);
3789
3870
  const infos = Array.from(infoEntry[1].values());
3790
3871
  if (!infos.length) {
3872
+ debug.debugFn('notice', `miss: CVEs expected, but not found, for ${name}`);
3791
3873
  continue infoEntriesLoop;
3792
3874
  }
3793
- logger.logger.log(`Processing vulns for ${name}:`);
3875
+ logger.logger.log(`Processing vulns for ${name}`);
3794
3876
  logger.logger.indent();
3795
3877
  spinner?.indent();
3796
3878
  if (registry.getManifestData(partialPurlObj.type, name)) {
3797
- debug.debugFn(`found: Socket Optimize variant for ${name}`);
3879
+ debug.debugFn('notice', `found: Socket Optimize variant for ${name}`);
3798
3880
  }
3799
3881
  // eslint-disable-next-line no-await-in-loop
3800
3882
  const packument = await packages.fetchPackagePackument(name);
@@ -3803,8 +3885,8 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3803
3885
  cleanupInfoEntriesLoop();
3804
3886
  continue infoEntriesLoop;
3805
3887
  }
3806
- const activeBranches = getActiveBranchesForPackage(ciEnv, infoEntry[0], openPrs);
3807
3888
  const availableVersions = Object.keys(packument.versions);
3889
+ const prs = getPrsForPurl(fixEnv, infoEntry[0]);
3808
3890
  const warningsForAfter = new Set();
3809
3891
 
3810
3892
  // eslint-disable-next-line no-unused-labels
@@ -3816,15 +3898,14 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3816
3898
  const pkgPath = path.dirname(pkgJsonPath);
3817
3899
  const isWorkspaceRoot = pkgJsonPath === pkgEnvDetails.editablePkgJson.filename;
3818
3900
  const workspace = isWorkspaceRoot ? 'root' : path.relative(rootPath, pkgPath);
3819
- const branchWorkspace = ciEnv ? getSocketBranchWorkspaceComponent(workspace) : '';
3820
-
3901
+ const branchWorkspace = fixEnv.isCi ? getSocketBranchWorkspaceComponent(workspace) : '';
3821
3902
  // actualTree may not be defined on the first iteration of pkgJsonPathsLoop.
3822
3903
  if (!actualTree) {
3823
- if (!ciEnv) {
3904
+ if (!fixEnv.isCi) {
3824
3905
  // eslint-disable-next-line no-await-in-loop
3825
3906
  await utils.removeNodeModules(cwd);
3826
3907
  }
3827
- const maybeActualTree = ciEnv && fs$1.existsSync(path.join(rootPath, 'node_modules')) ?
3908
+ const maybeActualTree = fixEnv.isCi && fs$1.existsSync(path.join(rootPath, 'node_modules')) ?
3828
3909
  // eslint-disable-next-line no-await-in-loop
3829
3910
  await getActualTree(cwd) :
3830
3911
  // eslint-disable-next-line no-await-in-loop
@@ -3845,7 +3926,7 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3845
3926
  }
3846
3927
  const oldVersions = arrays.arrayUnique(shadowNpmInject.findPackageNodes(actualTree, name).map(n => n.version).filter(Boolean));
3847
3928
  if (!oldVersions.length) {
3848
- debug.debugFn(`skip: ${name} not found\n`);
3929
+ debug.debugFn('notice', `skip: ${name} not found\n`);
3849
3930
  // Skip to next package.
3850
3931
  cleanupInfoEntriesLoop();
3851
3932
  continue infoEntriesLoop;
@@ -3860,8 +3941,8 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3860
3941
  const seenVersions = new Set();
3861
3942
  let hasAnnouncedWorkspace = false;
3862
3943
  let workspaceLogCallCount = logger.logger.logCallCount;
3863
- if (debug.isDebug()) {
3864
- debug.debugFn(`check: workspace ${workspace}`);
3944
+ if (debug.isDebug('notice')) {
3945
+ debug.debugFn('notice', `check: workspace ${workspace}`);
3865
3946
  hasAnnouncedWorkspace = true;
3866
3947
  workspaceLogCallCount = logger.logger.logCallCount;
3867
3948
  }
@@ -3870,7 +3951,7 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3870
3951
  const oldPurl = utils.idToPurl(oldId, partialPurlObj.type);
3871
3952
  const node = shadowNpmInject.findPackageNode(actualTree, name, oldVersion);
3872
3953
  if (!node) {
3873
- debug.debugFn(`skip: ${oldId} not found`);
3954
+ debug.debugFn('notice', `skip: ${oldId} not found`);
3874
3955
  continue oldVersionsLoop;
3875
3956
  }
3876
3957
  infosLoop: for (const {
@@ -3890,11 +3971,25 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3890
3971
  continue infosLoop;
3891
3972
  }
3892
3973
  if (vendor.semverExports.gte(oldVersion, newVersion)) {
3893
- debug.debugFn(`skip: ${oldId} is >= ${newVersion}`);
3974
+ debug.debugFn('silly', `skip: ${oldId} is >= ${newVersion}`);
3894
3975
  continue infosLoop;
3895
3976
  }
3896
- if (activeBranches.find(b => b.workspace === branchWorkspace && b.newVersion === newVersion)) {
3897
- debug.debugFn(`skip: open PR found for ${name}@${newVersion}`);
3977
+ const branch = getSocketBranchName(oldPurl, newVersion, workspace);
3978
+ const pr = prs.find(({
3979
+ parsedBranch: b
3980
+ }) => b.workspace === branchWorkspace && b.newVersion === newVersion);
3981
+ if (pr) {
3982
+ debug.debugFn('notice', `skip: PR #${pr.number} for ${name} exists`);
3983
+ if (++count >= limit) {
3984
+ cleanupInfoEntriesLoop();
3985
+ break infoEntriesLoop;
3986
+ }
3987
+ continue infosLoop;
3988
+ }
3989
+ if (fixEnv.isCi && (
3990
+ // eslint-disable-next-line no-await-in-loop
3991
+ await gitRemoteBranchExists(branch, cwd))) {
3992
+ debug.debugFn('notice', `skip: remote branch "${branch}" exists`);
3898
3993
  if (++count >= limit) {
3899
3994
  cleanupInfoEntriesLoop();
3900
3995
  break infoEntriesLoop;
@@ -3913,17 +4008,26 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3913
4008
  }
3914
4009
 
3915
4010
  // eslint-disable-next-line no-await-in-loop
3916
- await beforeInstall(editablePkgJson, name, oldVersion, newVersion, vulnerableVersionRange, fixConfig);
4011
+ await beforeInstall(editablePkgJson, packument, oldVersion, newVersion, vulnerableVersionRange, fixConfig);
3917
4012
  shadowNpmInject.updatePackageJsonFromNode(editablePkgJson, actualTree, node, newVersion, rangeStyle);
4013
+
3918
4014
  // eslint-disable-next-line no-await-in-loop
3919
- if (!(await editablePkgJson.save({
4015
+ await editablePkgJson.save({
3920
4016
  ignoreWhitespace: true
3921
- }))) {
3922
- debug.debugFn(`skip: ${workspace}/package.json unchanged`);
4017
+ });
4018
+
4019
+ // eslint-disable-next-line no-await-in-loop
4020
+ const unstagedCResult = await gitUnstagedModifiedFiles(cwd);
4021
+ const moddedFilepaths = unstagedCResult.ok ? unstagedCResult.data.filter(filepath => {
4022
+ const basename = path.basename(filepath);
4023
+ return basename === 'package.json' || basename === pkgEnvDetails.lockName;
4024
+ }) : [];
4025
+ if (!moddedFilepaths.length) {
4026
+ logger.logger.warn('Unexpected condition: Nothing to commit, skipping PR creation.');
3923
4027
  // Reset things just in case.
3924
- if (ciEnv) {
4028
+ if (fixEnv.isCi) {
3925
4029
  // eslint-disable-next-line no-await-in-loop
3926
- await gitResetAndClean(ciEnv.baseBranch, cwd);
4030
+ await gitResetAndClean(fixEnv.baseBranch, cwd);
3927
4031
  }
3928
4032
  continue infosLoop;
3929
4033
  }
@@ -3948,7 +4052,7 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3948
4052
  if (maybeActualTree && maybeLockSrc) {
3949
4053
  actualTree = maybeActualTree;
3950
4054
  // eslint-disable-next-line no-await-in-loop
3951
- await afterInstall(editablePkgJson, name, oldVersion, newVersion, vulnerableVersionRange, fixConfig);
4055
+ await afterInstall(editablePkgJson, packument, oldVersion, newVersion, vulnerableVersionRange, fixConfig);
3952
4056
  if (test) {
3953
4057
  spinner?.info(`Testing ${newId} in ${workspace}.`);
3954
4058
  // eslint-disable-next-line no-await-in-loop
@@ -3969,47 +4073,18 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
3969
4073
  spinner?.stop();
3970
4074
 
3971
4075
  // Check repoInfo to make TypeScript happy.
3972
- if (!errored && ciEnv?.repoInfo) {
4076
+ if (!errored && fixEnv.isCi && fixEnv.repoInfo) {
3973
4077
  try {
3974
- // eslint-disable-next-line no-await-in-loop
3975
- const unstagedCResult = await gitUnstagedModifiedFiles(cwd);
3976
- if (!unstagedCResult.ok) {
3977
- logger.logger.warn('Unexpected condition: Nothing to commit, skipping PR creation.');
3978
- continue;
3979
- }
3980
- const moddedFilepaths = unstagedCResult.data.filter(filepath => {
3981
- const basename = path.basename(filepath);
3982
- return basename === 'package.json' || basename === pkgEnvDetails.lockName;
3983
- });
3984
- if (!moddedFilepaths.length) {
3985
- logger.logger.warn('Unexpected condition: Nothing to commit, skipping PR creation.');
3986
- continue infosLoop;
3987
- }
3988
- const branch = getSocketBranchName(oldPurl, newVersion, workspace);
3989
- let skipPr = false;
3990
4078
  if (
3991
4079
  // eslint-disable-next-line no-await-in-loop
3992
- await prExistForBranch(ciEnv.repoInfo.owner, ciEnv.repoInfo.repo, branch)) {
3993
- skipPr = true;
3994
- debug.debugFn(`skip: branch "${branch}" exists`);
3995
- }
3996
- // eslint-disable-next-line no-await-in-loop
3997
- else if (await gitRemoteBranchExists(branch, cwd)) {
3998
- skipPr = true;
3999
- debug.debugFn(`skip: remote branch "${branch}" exists`);
4000
- } else if (
4001
- // eslint-disable-next-line no-await-in-loop
4002
4080
  !(await gitCreateAndPushBranch(branch, getSocketCommitMessage(oldPurl, newVersion, workspace), moddedFilepaths, {
4003
4081
  cwd,
4004
- email: ciEnv.gitEmail,
4005
- user: ciEnv.gitUser
4082
+ email: fixEnv.gitEmail,
4083
+ user: fixEnv.gitUser
4006
4084
  }))) {
4007
- skipPr = true;
4008
4085
  logger.logger.warn('Unexpected condition: Push failed, skipping PR creation.');
4009
- }
4010
- if (skipPr) {
4011
4086
  // eslint-disable-next-line no-await-in-loop
4012
- await gitResetAndClean(ciEnv.baseBranch, cwd);
4087
+ await gitResetAndClean(fixEnv.baseBranch, cwd);
4013
4088
  // eslint-disable-next-line no-await-in-loop
4014
4089
  const maybeActualTree = await installer(pkgEnvDetails, {
4015
4090
  cwd,
@@ -4027,14 +4102,14 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
4027
4102
  }
4028
4103
 
4029
4104
  // eslint-disable-next-line no-await-in-loop
4030
- await Promise.allSettled([setGitRemoteGithubRepoUrl(ciEnv.repoInfo.owner, ciEnv.repoInfo.repo, ciEnv.githubToken, cwd), cleanupOpenPrs(ciEnv.repoInfo.owner, ciEnv.repoInfo.repo, {
4105
+ await Promise.allSettled([setGitRemoteGithubRepoUrl(fixEnv.repoInfo.owner, fixEnv.repoInfo.repo, fixEnv.githubToken, cwd), cleanupPrs(fixEnv.repoInfo.owner, fixEnv.repoInfo.repo, {
4031
4106
  newVersion,
4032
4107
  purl: oldPurl,
4033
4108
  workspace
4034
4109
  })]);
4035
4110
  // eslint-disable-next-line no-await-in-loop
4036
- const prResponse = await openPr(ciEnv.repoInfo.owner, ciEnv.repoInfo.repo, branch, oldPurl, newVersion, {
4037
- baseBranch: ciEnv.baseBranch,
4111
+ const prResponse = await openPr(fixEnv.repoInfo.owner, fixEnv.repoInfo.repo, branch, oldPurl, newVersion, {
4112
+ baseBranch: fixEnv.baseBranch,
4038
4113
  cwd,
4039
4114
  workspace
4040
4115
  });
@@ -4067,10 +4142,10 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
4067
4142
  errored = true;
4068
4143
  }
4069
4144
  }
4070
- if (ciEnv) {
4145
+ if (fixEnv.isCi) {
4071
4146
  spinner?.start();
4072
4147
  // eslint-disable-next-line no-await-in-loop
4073
- await gitResetAndClean(ciEnv.baseBranch, cwd);
4148
+ await gitResetAndClean(fixEnv.baseBranch, cwd);
4074
4149
  // eslint-disable-next-line no-await-in-loop
4075
4150
  const maybeActualTree = await installer(pkgEnvDetails, {
4076
4151
  cwd,
@@ -4084,10 +4159,10 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
4084
4159
  }
4085
4160
  }
4086
4161
  if (errored) {
4087
- if (!ciEnv) {
4162
+ if (!fixEnv.isCi) {
4088
4163
  spinner?.start();
4089
4164
  // eslint-disable-next-line no-await-in-loop
4090
- await revertInstall(editablePkgJson, name, oldVersion, newVersion, vulnerableVersionRange, fixConfig);
4165
+ await revertInstall(editablePkgJson, packument, oldVersion, newVersion, vulnerableVersionRange, fixConfig);
4091
4166
  // eslint-disable-next-line no-await-in-loop
4092
4167
  await Promise.all([utils.removeNodeModules(cwd), editablePkgJson.save({
4093
4168
  ignoreWhitespace: true
@@ -4111,8 +4186,7 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
4111
4186
  cause: `Update failed for ${oldId} in ${workspace}${error ? '; ' + error : ''}`
4112
4187
  };
4113
4188
  }
4114
- debug.debugFn('name:', name);
4115
- debug.debugFn('increment: count', count + 1);
4189
+ debug.debugFn('notice', 'increment: count', count + 1);
4116
4190
  if (++count >= limit) {
4117
4191
  cleanupInfoEntriesLoop();
4118
4192
  break infoEntriesLoop;
@@ -4142,57 +4216,8 @@ async function agentFix(pkgEnvDetails, actualTree, alertsMap, installer, {
4142
4216
  };
4143
4217
  }
4144
4218
 
4145
- async function getEnvRepoInfo(cwd) {
4146
- // Lazily access constants.ENV.GITHUB_REPOSITORY.
4147
- const {
4148
- GITHUB_REPOSITORY
4149
- } = constants.ENV;
4150
- if (!GITHUB_REPOSITORY) {
4151
- debug.debugFn('miss: GITHUB_REPOSITORY env var');
4152
- }
4153
- const ownerSlashRepo = GITHUB_REPOSITORY;
4154
- const slashIndex = ownerSlashRepo.indexOf('/');
4155
- if (slashIndex !== -1) {
4156
- return {
4157
- owner: ownerSlashRepo.slice(0, slashIndex),
4158
- repo: ownerSlashRepo.slice(slashIndex + 1)
4159
- };
4160
- }
4161
- return await gitRepoInfo(cwd);
4162
- }
4163
- async function getCiEnv() {
4164
- const gitEmail = constants.ENV.SOCKET_CLI_GIT_USER_EMAIL;
4165
- const gitUser = constants.ENV.SOCKET_CLI_GIT_USER_NAME;
4166
- const githubToken = constants.ENV.SOCKET_CLI_GITHUB_TOKEN;
4167
- const isCi = !!(constants.ENV.CI && gitEmail && gitUser && githubToken);
4168
- if (!isCi) {
4169
- return null;
4170
- }
4171
- const baseBranch = await getBaseGitBranch();
4172
- if (!baseBranch) {
4173
- return null;
4174
- }
4175
- const repoInfo = await getEnvRepoInfo();
4176
- if (!repoInfo) {
4177
- return null;
4178
- }
4179
- return {
4180
- gitEmail,
4181
- gitUser,
4182
- githubToken,
4183
- repoInfo,
4184
- baseBranch,
4185
- branchParser: createSocketBranchParser()
4186
- };
4187
- }
4188
- async function getOpenPrsForEnvironment(env) {
4189
- return env ? await getOpenSocketPrs(env.repoInfo.owner, env.repoInfo.repo, {
4190
- author: env.gitUser
4191
- }) : [];
4192
- }
4193
-
4194
4219
  const CMD_NAME$1 = 'socket fix';
4195
- function getAlertsMapOptions(options = {}) {
4220
+ function getFixAlertsMapOptions(options = {}) {
4196
4221
  return {
4197
4222
  __proto__: null,
4198
4223
  consolidate: true,
@@ -4221,7 +4246,7 @@ async function install$1(pkgEnvDetails, options) {
4221
4246
  await utils.runAgentInstall(pkgEnvDetails, {
4222
4247
  args,
4223
4248
  spinner,
4224
- stdio: debug.isDebug() ? 'inherit' : 'ignore'
4249
+ stdio: debug.isDebug('stdio') ? 'inherit' : 'ignore'
4225
4250
  });
4226
4251
  return await getActualTree(cwd);
4227
4252
  } catch {}
@@ -4229,59 +4254,35 @@ async function install$1(pkgEnvDetails, options) {
4229
4254
  }
4230
4255
  async function npmFix(pkgEnvDetails, fixConfig) {
4231
4256
  const {
4232
- limit,
4233
4257
  purls,
4234
4258
  spinner
4235
4259
  } = fixConfig;
4236
4260
  spinner?.start();
4237
- const ciEnv = await getCiEnv();
4238
- const openPrs = ciEnv ? await getOpenPrsForEnvironment(ciEnv) : [];
4261
+ let arb;
4239
4262
  let actualTree;
4240
4263
  let alertsMap;
4241
4264
  try {
4242
4265
  if (purls.length) {
4243
- alertsMap = await utils.getAlertsMapFromPurls(purls, getAlertsMapOptions({
4244
- limit: Math.max(limit, openPrs.length)
4245
- }));
4266
+ alertsMap = await utils.getAlertsMapFromPurls(purls, getFixAlertsMapOptions());
4246
4267
  } else {
4247
- const npmPath = path.resolve(fs$1.realpathSync(pkgEnvDetails.agentExecPath), '../..');
4248
- const config = new vendor.libExports$2({
4249
- argv: [],
4250
- cwd: process.cwd(),
4251
- definitions: vendor.definitionsExports.definitions,
4252
- // Lazily access constants.execPath.
4253
- execPath: constants.execPath,
4254
- env: {
4255
- ...process.env
4256
- },
4257
- flatten: vendor.definitionsExports.flatten,
4258
- npmPath,
4259
- platform: process.platform,
4260
- shorthands: vendor.definitionsExports.shorthands
4268
+ const flatConfig = await utils.getNpmConfig({
4269
+ npmVersion: pkgEnvDetails.agentVersion
4261
4270
  });
4262
- await config.load();
4263
- const flatConfig = {
4264
- __proto__: null,
4265
- ...config.flat
4266
- };
4267
- flatConfig.nodeVersion = constants.NODE_VERSION;
4268
- flatConfig.npmVersion = pkgEnvDetails.agentVersion.toString();
4269
- flatConfig.npmCommand = 'install';
4270
- const arb = new shadowNpmInject.Arborist({
4271
+ arb = new shadowNpmInject.Arborist({
4271
4272
  path: pkgEnvDetails.pkgPath,
4272
- ...flatConfig,
4273
- ...shadowNpmInject.SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES
4273
+ ...flatConfig
4274
4274
  });
4275
4275
  actualTree = await arb.reify();
4276
4276
  // Calling arb.reify() creates the arb.diff object, nulls-out arb.idealTree,
4277
4277
  // and populates arb.actualTree.
4278
- alertsMap = await shadowNpmInject.getAlertsMapFromArborist(arb, getAlertsMapOptions({
4279
- limit: Math.max(limit, openPrs.length)
4280
- }));
4278
+ alertsMap = await shadowNpmInject.getAlertsMapFromArborist(arb, getFixAlertsMapOptions());
4281
4279
  }
4282
4280
  } catch (e) {
4283
4281
  spinner?.stop();
4284
- debug.debugFn('catch: PURL API\n', e);
4282
+ debug.debugFn('error', 'caught: PURL API');
4283
+ debug.debugDir('inspect', {
4284
+ error: e
4285
+ });
4285
4286
  return {
4286
4287
  ok: false,
4287
4288
  message: 'API Error',
@@ -4290,7 +4291,7 @@ async function npmFix(pkgEnvDetails, fixConfig) {
4290
4291
  }
4291
4292
  let revertData;
4292
4293
  return await agentFix(pkgEnvDetails, actualTree, alertsMap, install$1, {
4293
- async beforeInstall(editablePkgJson) {
4294
+ async beforeInstall(editablePkgJson, packument, oldVersion, newVersion) {
4294
4295
  revertData = {
4295
4296
  ...(editablePkgJson.content.dependencies && {
4296
4297
  dependencies: {
@@ -4308,13 +4309,19 @@ async function npmFix(pkgEnvDetails, fixConfig) {
4308
4309
  }
4309
4310
  })
4310
4311
  };
4312
+ const idealTree = await arb.buildIdealTree();
4313
+ const node = shadowNpmInject.findPackageNode(idealTree, packument.name, oldVersion);
4314
+ if (node) {
4315
+ shadowNpmInject.updateNode(node, newVersion, packument.versions[newVersion]);
4316
+ await arb.reify();
4317
+ }
4311
4318
  },
4312
4319
  async revertInstall(editablePkgJson) {
4313
4320
  if (revertData) {
4314
4321
  editablePkgJson.update(revertData);
4315
4322
  }
4316
4323
  }
4317
- }, ciEnv, openPrs, fixConfig);
4324
+ }, fixConfig);
4318
4325
  }
4319
4326
 
4320
4327
  async function outputFixResult(result, outputKind) {
@@ -4356,7 +4363,7 @@ async function install(pkgEnvDetails, options) {
4356
4363
  // https://github.com/pnpm/pnpm/issues/6778
4357
4364
  '--config.confirmModulesPurge=false'],
4358
4365
  spinner,
4359
- stdio: debug.isDebug() ? 'inherit' : 'ignore'
4366
+ stdio: debug.isDebug('stdio') ? 'inherit' : 'ignore'
4360
4367
  });
4361
4368
  return await getActualTree(cwd);
4362
4369
  } catch {}
@@ -4365,7 +4372,6 @@ async function install(pkgEnvDetails, options) {
4365
4372
  async function pnpmFix(pkgEnvDetails, fixConfig) {
4366
4373
  const {
4367
4374
  cwd,
4368
- limit,
4369
4375
  purls,
4370
4376
  spinner
4371
4377
  } = fixConfig;
@@ -4403,18 +4409,15 @@ async function pnpmFix(pkgEnvDetails, fixConfig) {
4403
4409
  cause: 'Required pnpm-lock.yaml not found or usable'
4404
4410
  };
4405
4411
  }
4406
- const ciEnv = await getCiEnv();
4407
- const openPrs = ciEnv ? await getOpenPrsForEnvironment(ciEnv) : [];
4408
4412
  let alertsMap;
4409
4413
  try {
4410
- alertsMap = purls.length ? await utils.getAlertsMapFromPurls(purls, getAlertsMapOptions({
4411
- limit: Math.max(limit, openPrs.length)
4412
- })) : await utils.getAlertsMapFromPnpmLockfile(lockfile, getAlertsMapOptions({
4413
- limit: Math.max(limit, openPrs.length)
4414
- }));
4414
+ alertsMap = purls.length ? await utils.getAlertsMapFromPurls(purls, getFixAlertsMapOptions()) : await utils.getAlertsMapFromPnpmLockfile(lockfile, getFixAlertsMapOptions());
4415
4415
  } catch (e) {
4416
4416
  spinner?.stop();
4417
- debug.debugFn('catch: PURL API\n', e);
4417
+ debug.debugFn('error', 'caught: PURL API');
4418
+ debug.debugDir('inspect', {
4419
+ error: e
4420
+ });
4418
4421
  return {
4419
4422
  ok: false,
4420
4423
  message: 'API Error',
@@ -4425,14 +4428,14 @@ async function pnpmFix(pkgEnvDetails, fixConfig) {
4425
4428
  let revertOverrides;
4426
4429
  let revertOverridesSrc;
4427
4430
  return await agentFix(pkgEnvDetails, actualTree, alertsMap, install, {
4428
- async beforeInstall(editablePkgJson, name, oldVersion, newVersion, vulnerableVersionRange, options) {
4431
+ async beforeInstall(editablePkgJson, packument, oldVersion, newVersion, vulnerableVersionRange, options) {
4429
4432
  const isWorkspaceRoot = editablePkgJson.path === pkgEnvDetails.editablePkgJson.filename;
4430
4433
  // Get current overrides for revert logic.
4431
4434
  const {
4432
4435
  overrides: oldOverrides
4433
4436
  } = getOverridesDataPnpm(pkgEnvDetails, editablePkgJson.content);
4434
4437
  const oldPnpmSection = editablePkgJson.content[PNPM$7];
4435
- const overrideKey = `${name}@${vulnerableVersionRange}`;
4438
+ const overrideKey = `${packument.name}@${vulnerableVersionRange}`;
4436
4439
  revertOverrides = undefined;
4437
4440
  revertOverridesSrc = utils.extractOverridesFromPnpmLockSrc(lockSrc);
4438
4441
  if (isWorkspaceRoot) {
@@ -4496,7 +4499,7 @@ async function pnpmFix(pkgEnvDetails, fixConfig) {
4496
4499
  editablePkgJson.update(revertData);
4497
4500
  }
4498
4501
  }
4499
- }, ciEnv, openPrs, fixConfig);
4502
+ }, fixConfig);
4500
4503
  }
4501
4504
 
4502
4505
  const {
@@ -4532,7 +4535,8 @@ async function handleFix({
4532
4535
  ghsas = utils.cmdFlagValueToArray(/(?<=Vulnerabilities found: )[^\n]+/.exec(autoCResult.data)?.[0]);
4533
4536
  ghsasCount = ghsas.length;
4534
4537
  } else {
4535
- debug.debugFn('coana fail:', {
4538
+ debug.debugFn('error', 'fail: Coana CLI');
4539
+ debug.debugDir('inspect', {
4536
4540
  message: autoCResult.message,
4537
4541
  cause: autoCResult.cause
4538
4542
  });
@@ -4549,7 +4553,8 @@ async function handleFix({
4549
4553
  });
4550
4554
  spinner?.stop();
4551
4555
  if (!applyFixesCResult.ok) {
4552
- debug.debugFn('coana fail:', {
4556
+ debug.debugFn('error', 'fail: Coana CLI');
4557
+ debug.debugDir('inspect', {
4553
4558
  message: applyFixesCResult.message,
4554
4559
  cause: applyFixesCResult.cause
4555
4560
  });
@@ -4819,9 +4824,9 @@ async function setupTabCompletion(targetName) {
4819
4824
 
4820
4825
  // Target dir is something like ~/.local/share/socket/settings/completion (linux)
4821
4826
  const targetDir = path.dirname(targetPath);
4822
- debug.debugFn('target: path + dir', targetPath, targetDir);
4827
+ debug.debugFn('notice', 'target: path + dir', targetPath, targetDir);
4823
4828
  if (!fs$1.existsSync(targetDir)) {
4824
- debug.debugFn('create: target dir');
4829
+ debug.debugFn('notice', 'create: target dir');
4825
4830
  fs$1.mkdirSync(targetDir, {
4826
4831
  recursive: true
4827
4832
  });
@@ -5419,6 +5424,8 @@ const arrayToLower = arg => arg.map(toLower);
5419
5424
  // [choices: "appsec", "research", "operational", "threat-modeling", "license-compliance", "generic", "machine-learning",
5420
5425
  // "ml", "deep-learning", "ml-deep", "ml-tiny"] [default: "generic"]
5421
5426
  // --exclude Additional glob pattern(s) to ignore [array]
5427
+ // --export-proto Serialize and export BOM as protobuf binary. [boolean] [default: false]
5428
+ // --proto-bin-file Path for the serialized protobuf binary. [default: "bom.cdx"]
5422
5429
  // --include-formulation Generate formulation section with git metadata and build tools. Defaults to false.
5423
5430
  // [boolean] [default: false]
5424
5431
  // --include-crypto Include crypto libraries as components. [boolean] [default: false]
@@ -5474,7 +5481,7 @@ const yargsConfig = {
5474
5481
  //'deps-slices-file': 'deps.slices.json', // hidden
5475
5482
  //evidence: false,
5476
5483
  //'exclude-type': [],
5477
- //'export-proto': true, // hidden
5484
+ //'export-proto': false,
5478
5485
  //'fail-on-error': isSecureMode,
5479
5486
  //'feature-flags': [], // hidden
5480
5487
  //'include-crypto': false,
@@ -5485,7 +5492,7 @@ const yargsConfig = {
5485
5492
  //output: 'bom.json',
5486
5493
  //profile: 'generic',
5487
5494
  //'project-version': '',
5488
- //'proto-bin-file': 'bom.cdx', // hidden
5495
+ //'proto-bin-file': 'bom.cdx',
5489
5496
  //recurse: true,
5490
5497
  //'skip-dt-tls-check': false,
5491
5498
  //'semantics-slices-file': 'semantics.slices.json',
@@ -5537,9 +5544,7 @@ const yargsConfig = {
5537
5544
  }],
5538
5545
  boolean: ['auto-compositions', 'babel', 'banner',
5539
5546
  // hidden
5540
- 'deep', 'evidence', 'export-proto',
5541
- // hidden
5542
- 'fail-on-error', 'generate-key-and-sign', 'help', 'include-crypto', 'include-formulation', 'install-deps', 'json-pretty', 'print', 'recurse', 'required-only', 'resolve-class', 'skip-dt-tls-check', 'server', 'validate', 'version',
5547
+ 'deep', 'evidence', 'export-proto', 'fail-on-error', 'generate-key-and-sign', 'help', 'include-crypto', 'include-formulation', 'install-deps', 'json-pretty', 'print', 'recurse', 'required-only', 'resolve-class', 'skip-dt-tls-check', 'server', 'validate', 'version',
5543
5548
  // The --yes flag and -y alias map to the corresponding flag and alias of npx.
5544
5549
  // https://docs.npmjs.com/cli/v7/commands/npx#compatibility-with-older-npx-versions
5545
5550
  'yes'],
@@ -5553,9 +5558,7 @@ const yargsConfig = {
5553
5558
  // number
5554
5559
  'openapi-spec-file',
5555
5560
  // hidden
5556
- 'output', 'parent-project-id', 'profile', 'project-group', 'project-name', 'project-version', 'project-id', 'proto-bin-file',
5557
- // hidden
5558
- 'reachables-slices-file',
5561
+ 'output', 'parent-project-id', 'profile', 'project-group', 'project-name', 'project-version', 'project-id', 'proto-bin-file', 'reachables-slices-file',
5559
5562
  // hidden
5560
5563
  'semantics-slices-file',
5561
5564
  // hidden
@@ -5697,7 +5700,9 @@ async function run$B(argv, importMeta, {
5697
5700
  }
5698
5701
  const sockJson = await utils.readOrDefaultSocketJson(cwd);
5699
5702
  const detected = await detectManifestActions(sockJson, cwd);
5700
- debug.debugLog('[DEBUG]', detected);
5703
+ debug.debugDir('inspect', {
5704
+ detected
5705
+ });
5701
5706
  if (cli.flags['dryRun']) {
5702
5707
  logger.logger.log(DRY_RUN_BAILING_NOW$A);
5703
5708
  return;
@@ -5962,7 +5967,7 @@ async function run$z(argv, importMeta, {
5962
5967
  // If given path is absolute then cwd should not affect it.
5963
5968
  cwd = path.resolve(process.cwd(), cwd);
5964
5969
  const sockJson = await utils.readOrDefaultSocketJson(cwd);
5965
- debug.debugFn('override: socket.json gradle', sockJson?.defaults?.manifest?.gradle);
5970
+ debug.debugFn('inspect', 'override: socket.json gradle', sockJson?.defaults?.manifest?.gradle);
5966
5971
 
5967
5972
  // Set defaults for any flag/arg that is not given. Check socket.json first.
5968
5973
  if (!bin) {
@@ -6119,7 +6124,7 @@ async function run$y(argv, importMeta, {
6119
6124
  // If given path is absolute then cwd should not affect it.
6120
6125
  cwd = path.resolve(process.cwd(), cwd);
6121
6126
  const sockJson = await utils.readOrDefaultSocketJson(cwd);
6122
- debug.debugFn('override: socket.json gradle', sockJson?.defaults?.manifest?.gradle);
6127
+ debug.debugFn('inspect', 'override: socket.json gradle', sockJson?.defaults?.manifest?.gradle);
6123
6128
 
6124
6129
  // Set defaults for any flag/arg that is not given. Check socket.json first.
6125
6130
  if (!bin) {
@@ -6285,7 +6290,7 @@ async function run$x(argv, importMeta, {
6285
6290
  // If given path is absolute then cwd should not affect it.
6286
6291
  cwd = path.resolve(process.cwd(), cwd);
6287
6292
  const sockJson = await utils.readOrDefaultSocketJson(cwd);
6288
- debug.debugFn('override: socket.json sbt', sockJson?.defaults?.manifest?.sbt);
6293
+ debug.debugFn('inspect', 'override: socket.json sbt', sockJson?.defaults?.manifest?.sbt);
6289
6294
 
6290
6295
  // Set defaults for any flag/arg that is not given. Check socket.json first.
6291
6296
  if (!bin) {
@@ -6379,7 +6384,9 @@ async function outputManifestSetup(result) {
6379
6384
 
6380
6385
  async function setupManifestConfig(cwd, defaultOnReadError = false) {
6381
6386
  const detected = await detectManifestActions(null, cwd);
6382
- debug.debugLog('[DEBUG]', detected);
6387
+ debug.debugDir('inspect', {
6388
+ detected
6389
+ });
6383
6390
 
6384
6391
  // - repeat
6385
6392
  // - give the user an option to configure one of the supported targets
@@ -7602,7 +7609,10 @@ async function updateLockfile(pkgEnvDetails, options) {
7602
7609
  }
7603
7610
  } catch (e) {
7604
7611
  spinner?.stop();
7605
- debug.debugFn('fail: update\n', e);
7612
+ debug.debugFn('error', 'fail: update');
7613
+ debug.debugDir('inspect', {
7614
+ error: e
7615
+ });
7606
7616
  return {
7607
7617
  ok: false,
7608
7618
  message: 'Update failed',
@@ -8922,7 +8932,7 @@ function formatReportCard(artifact, color) {
8922
8932
  };
8923
8933
  const alertString = getAlertString(artifact.alerts, !color);
8924
8934
  if (!artifact.ecosystem) {
8925
- debug.debugFn('miss: artifact ecosystem', artifact);
8935
+ debug.debugFn('notice', 'miss: artifact ecosystem', artifact);
8926
8936
  }
8927
8937
  const purl = `pkg:${artifact.ecosystem}/${artifact.name}${artifact.version ? '@' + artifact.version : ''}`;
8928
8938
  return ['Package: ' + (color ? vendor.yoctocolorsCjsExports.bold(purl) : purl), '', ...Object.entries(scoreResult).map(score => `- ${score[0]}:`.padEnd(20, ' ') + ` ${formatScore(score[1], !color, true)}`), alertString].join('\n');
@@ -9700,19 +9710,22 @@ async function fetchListAllRepos({
9700
9710
  };
9701
9711
  }
9702
9712
  // eslint-disable-next-line no-await-in-loop
9703
- const result = await utils.handleApiCall(sockSdk.getOrgRepoList(orgSlug, {
9713
+ const orgRepoListCResult = await utils.handleApiCall(sockSdk.getOrgRepoList(orgSlug, {
9704
9714
  sort,
9705
9715
  direction,
9706
9716
  per_page: String(100),
9707
9717
  // max
9708
9718
  page: String(nextPage)
9709
9719
  }), 'list of repositories');
9710
- if (!result.ok) {
9711
- debug.debugFn('fail: fetch repo\n', result);
9712
- return result;
9720
+ if (!orgRepoListCResult.ok) {
9721
+ debug.debugFn('error', 'fail: fetch repo');
9722
+ debug.debugDir('inspect', {
9723
+ orgRepoListCResult
9724
+ });
9725
+ return orgRepoListCResult;
9713
9726
  }
9714
- result.data.results.forEach(row => rows.push(row));
9715
- nextPage = result.data.nextPage ?? -1;
9727
+ orgRepoListCResult.data.results.forEach(row => rows.push(row));
9728
+ nextPage = orgRepoListCResult.data.nextPage ?? -1;
9716
9729
  }
9717
9730
  return {
9718
9731
  ok: true,
@@ -11253,7 +11266,7 @@ async function scanOneRepo(repoSlug, {
11253
11266
  };
11254
11267
  }
11255
11268
  const tmpDir = fs$1.mkdtempSync(path.join(os.tmpdir(), repoSlug));
11256
- debug.debugFn('init: temp dir for scan root', tmpDir);
11269
+ debug.debugFn('notice', 'init: temp dir for scan root', tmpDir);
11257
11270
  const downloadResult = await testAndDownloadManifestFiles({
11258
11271
  files,
11259
11272
  tmpDir,
@@ -11366,9 +11379,9 @@ async function testAndDownloadManifestFile({
11366
11379
  repoApiUrl,
11367
11380
  tmpDir
11368
11381
  }) {
11369
- debug.debugFn('testing: file', file);
11382
+ debug.debugFn('notice', 'testing: file', file);
11370
11383
  if (!SUPPORTED_FILE_PATTERNS.some(regex => regex.test(file))) {
11371
- debug.debugFn(' - skip: not a known pattern');
11384
+ debug.debugFn('notice', ' - skip: not a known pattern');
11372
11385
  // Not an error.
11373
11386
  return {
11374
11387
  ok: true,
@@ -11377,7 +11390,7 @@ async function testAndDownloadManifestFile({
11377
11390
  }
11378
11391
  };
11379
11392
  }
11380
- debug.debugFn('found: manifest file, going to attempt to download it;', file);
11393
+ debug.debugFn('notice', 'found: manifest file, going to attempt to download it;', file);
11381
11394
  const result = await downloadManifestFile({
11382
11395
  file,
11383
11396
  tmpDir,
@@ -11399,18 +11412,18 @@ async function downloadManifestFile({
11399
11412
  repoApiUrl,
11400
11413
  tmpDir
11401
11414
  }) {
11402
- debug.debugFn('request: download url from GitHub');
11415
+ debug.debugFn('notice', 'request: download url from GitHub');
11403
11416
  const fileUrl = `${repoApiUrl}/contents/${file}?ref=${defaultBranch}`;
11404
- debug.debugFn('url: file', fileUrl);
11417
+ debug.debugFn('inspect', 'url: file', fileUrl);
11405
11418
  const downloadUrlResponse = await fetch(fileUrl, {
11406
11419
  method: 'GET',
11407
11420
  headers: {
11408
11421
  Authorization: `Bearer ${githubToken}`
11409
11422
  }
11410
11423
  });
11411
- debug.debugFn('complete: request');
11424
+ debug.debugFn('notice', 'complete: request');
11412
11425
  const downloadUrlText = await downloadUrlResponse.text();
11413
- debug.debugFn('response: raw download url', downloadUrlText);
11426
+ debug.debugFn('inspect', 'response: raw download url', downloadUrlText);
11414
11427
  let downloadUrl;
11415
11428
  try {
11416
11429
  downloadUrl = JSON.parse(downloadUrlText).download_url;
@@ -11423,7 +11436,7 @@ async function downloadManifestFile({
11423
11436
  };
11424
11437
  }
11425
11438
  const localPath = path.join(tmpDir, file);
11426
- debug.debugFn('download: manifest file started', downloadUrl, '->', localPath);
11439
+ debug.debugFn('notice', 'download: manifest file started', downloadUrl, '->', localPath);
11427
11440
 
11428
11441
  // Now stream the file to that file...
11429
11442
  const result = await streamDownloadWithFetch(localPath, downloadUrl);
@@ -11432,7 +11445,7 @@ async function downloadManifestFile({
11432
11445
  logger.logger.fail(`Failed to download manifest file, skipping to next file. File: ${file}`);
11433
11446
  return result;
11434
11447
  }
11435
- debug.debugFn('download: manifest file completed');
11448
+ debug.debugFn('notice', 'download: manifest file completed');
11436
11449
  return {
11437
11450
  ok: true,
11438
11451
  data: undefined
@@ -11484,8 +11497,9 @@ async function streamDownloadWithFetch(localPath, downloadUrl) {
11484
11497
  };
11485
11498
  } catch (error) {
11486
11499
  logger.logger.fail('An error was thrown while trying to download a manifest file... url:', downloadUrl);
11487
- debug.debugFn('Raw error:');
11488
- debug.debugFn(error);
11500
+ debug.debugFn('inspect', {
11501
+ error
11502
+ });
11489
11503
 
11490
11504
  // If an error occurs and fileStream was created, attempt to clean up.
11491
11505
  if (fs$1.existsSync(localPath)) {
@@ -11507,7 +11521,7 @@ async function streamDownloadWithFetch(localPath, downloadUrl) {
11507
11521
  // If error was due to bad HTTP status
11508
11522
  detailedError += ` (HTTP Status: ${response.status} ${response.statusText})`;
11509
11523
  }
11510
- debug.debugFn(detailedError);
11524
+ debug.debugFn('error', detailedError);
11511
11525
  return {
11512
11526
  ok: false,
11513
11527
  message: 'Download Failed',
@@ -11524,14 +11538,14 @@ async function getLastCommitDetails({
11524
11538
  }) {
11525
11539
  logger.logger.info(`Requesting last commit for default branch ${defaultBranch} for ${orgGithub}/${repoSlug}...`);
11526
11540
  const commitApiUrl = `${repoApiUrl}/commits?sha=${defaultBranch}&per_page=1`;
11527
- debug.debugFn('url: commit', commitApiUrl);
11541
+ debug.debugFn('inspect', 'url: commit', commitApiUrl);
11528
11542
  const commitResponse = await fetch(commitApiUrl, {
11529
11543
  headers: {
11530
11544
  Authorization: `Bearer ${githubToken}`
11531
11545
  }
11532
11546
  });
11533
11547
  const commitText = await commitResponse.text();
11534
- debug.debugFn('response: commit', commitText);
11548
+ debug.debugFn('inspect', 'response: commit', commitText);
11535
11549
  let lastCommit;
11536
11550
  try {
11537
11551
  lastCommit = JSON.parse(commitText)?.[0];
@@ -11618,7 +11632,7 @@ async function getRepoDetails({
11618
11632
  repoSlug
11619
11633
  }) {
11620
11634
  const repoApiUrl = `${githubApiUrl}/repos/${orgGithub}/${repoSlug}`;
11621
- debug.debugFn('url: repo', repoApiUrl);
11635
+ debug.debugFn('inspect', 'url: repo', repoApiUrl);
11622
11636
  const repoDetailsResponse = await fetch(repoApiUrl, {
11623
11637
  method: 'GET',
11624
11638
  headers: {
@@ -11627,7 +11641,7 @@ async function getRepoDetails({
11627
11641
  });
11628
11642
  logger.logger.success(`Request completed.`);
11629
11643
  const repoDetailsText = await repoDetailsResponse.text();
11630
- debug.debugFn('response: repo', repoDetailsText);
11644
+ debug.debugFn('inspect', 'response: repo', repoDetailsText);
11631
11645
  let repoDetails;
11632
11646
  try {
11633
11647
  repoDetails = JSON.parse(repoDetailsText);
@@ -11666,7 +11680,7 @@ async function getRepoBranchTree({
11666
11680
  }) {
11667
11681
  logger.logger.info(`Requesting default branch file tree; branch \`${defaultBranch}\`, repo \`${orgGithub}/${repoSlug}\`...`);
11668
11682
  const treeApiUrl = `${repoApiUrl}/git/trees/${defaultBranch}?recursive=1`;
11669
- debug.debugFn('url: tree', treeApiUrl);
11683
+ debug.debugFn('inspect', 'url: tree', treeApiUrl);
11670
11684
  const treeResponse = await fetch(treeApiUrl, {
11671
11685
  method: 'GET',
11672
11686
  headers: {
@@ -11674,7 +11688,7 @@ async function getRepoBranchTree({
11674
11688
  }
11675
11689
  });
11676
11690
  const treeText = await treeResponse.text();
11677
- debug.debugFn('response: tree', treeText);
11691
+ debug.debugFn('inspect', 'response: tree', treeText);
11678
11692
  let treeDetails;
11679
11693
  try {
11680
11694
  treeDetails = JSON.parse(treeText);
@@ -11703,7 +11717,7 @@ async function getRepoBranchTree({
11703
11717
  };
11704
11718
  }
11705
11719
  if (!treeDetails.tree || !Array.isArray(treeDetails.tree)) {
11706
- debug.debugFn('treeDetails.tree:', treeDetails.tree);
11720
+ debug.debugFn('inspect', 'treeDetails.tree:', treeDetails.tree);
11707
11721
  return {
11708
11722
  ok: false,
11709
11723
  message: `Tree response for default branch ${defaultBranch} for ${orgGithub}/${repoSlug} was not a list`
@@ -12983,7 +12997,10 @@ async function fetchScan(orgSlug, scanId) {
12983
12997
  return JSON.parse(line);
12984
12998
  } catch {
12985
12999
  ok = false;
12986
- debug.debugFn('fail: parse NDJSON\n', line);
13000
+ debug.debugFn('error', 'fail: parse NDJSON');
13001
+ debug.debugDir('inspect', {
13002
+ line
13003
+ });
12987
13004
  return null;
12988
13005
  }
12989
13006
  });
@@ -13863,7 +13880,10 @@ Do you want to install "safe npm" (this will create an alias to the socket-npm c
13863
13880
  }
13864
13881
  }
13865
13882
  } catch (e) {
13866
- debug.debugFn('fail: setup tab completion\n', e);
13883
+ debug.debugFn('error', 'fail: setup tab completion');
13884
+ debug.debugDir('inspect', {
13885
+ error: e
13886
+ });
13867
13887
  // Ignore. Skip tab completion setup.
13868
13888
  }
13869
13889
  if (!updatedTabCompletion) {
@@ -14177,8 +14197,10 @@ void (async () => {
14177
14197
  });
14178
14198
  } catch (e) {
14179
14199
  process.exitCode = 1;
14180
- debug.debugFn('Uncaught error (BAD!):');
14181
- debug.debugFn(e);
14200
+ debug.debugFn('error', 'Uncaught error (BAD!):');
14201
+ debug.debugDir('inspect', {
14202
+ error: e
14203
+ });
14182
14204
 
14183
14205
  // Try to parse the flags, find out if --json or --markdown is set.
14184
14206
  let isJson = false;
@@ -14220,12 +14242,13 @@ void (async () => {
14220
14242
  logger.logger.error('\n'); // Any-spinner-newline
14221
14243
  logger.logger.fail(utils.failMsgWithBadge(errorTitle, errorMessage));
14222
14244
  if (errorBody) {
14223
- // Explicitly use debugLog here.
14224
- debug.debugLog(errorBody);
14245
+ debug.debugDir('inspect', {
14246
+ errorBody
14247
+ });
14225
14248
  }
14226
14249
  }
14227
14250
  await utils.captureException(e);
14228
14251
  }
14229
14252
  })();
14230
- //# debugId=22ea4fe2-a3e7-46a5-b720-03c98211a8ec
14253
+ //# debugId=4ba13438-a655-4a29-bba0-7fa82f66b9c1
14231
14254
  //# sourceMappingURL=cli.js.map