diff --git a/src/cli.mts b/src/cli.mts index 850f83b4b..64a5956ca 100755 --- a/src/cli.mts +++ b/src/cli.mts @@ -8,7 +8,7 @@ import lookupRegistryAuthToken from 'registry-auth-token' import lookupRegistryUrl from 'registry-url' import updateNotifier from 'tiny-updater' -import { debugFn, debugLog } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' import { cmdAnalytics } from './commands/analytics/cmd-analytics.mts' @@ -186,8 +186,8 @@ void (async () => { ) } catch (e) { process.exitCode = 1 - debugFn('Uncaught error (BAD!):') - debugFn(e) + debugFn('error', 'Uncaught error (BAD!):') + debugDir('inspect', { error: e }) // Try to parse the flags, find out if --json or --markdown is set. let isJson = false @@ -231,8 +231,7 @@ void (async () => { logger.error('\n') // Any-spinner-newline logger.fail(failMsgWithBadge(errorTitle, errorMessage)) if (errorBody) { - // Explicitly use debugLog here. - debugLog(errorBody) + debugDir('inspect', { errorBody }) } } diff --git a/src/commands/audit-log/output-audit-log.mts b/src/commands/audit-log/output-audit-log.mts index 6e6497d09..0170f7e41 100644 --- a/src/commands/audit-log/output-audit-log.mts +++ b/src/commands/audit-log/output-audit-log.mts @@ -1,6 +1,6 @@ import { createRequire } from 'node:module' -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' import constants from '../../constants.mts' @@ -182,7 +182,8 @@ ${table} logger.fail( 'There was a problem converting the logs to Markdown, please try the `--json` flag', ) - debugFn('catch: unexpected\n', e) + debugFn('error', 'caught: unexpected error') + debugDir('inspect', { error: e }) return 'Failed to generate the markdown report' } } diff --git a/src/commands/ci/fetch-default-org-slug.mts b/src/commands/ci/fetch-default-org-slug.mts index d0a096d2a..631117038 100644 --- a/src/commands/ci/fetch-default-org-slug.mts +++ b/src/commands/ci/fetch-default-org-slug.mts @@ -11,7 +11,7 @@ export async function getDefaultOrgSlug(): Promise> { const defaultOrgResult = getConfigValueOrUndef('defaultOrg') if (defaultOrgResult) { - debugFn('use: default org', defaultOrgResult) + debugFn('notice', 'use: default org', defaultOrgResult) return { ok: true, data: defaultOrgResult } } @@ -51,7 +51,7 @@ export async function getDefaultOrgSlug(): Promise> { } } - debugFn('resolve: org', slug) + debugFn('notice', 'resolve: org', slug) return { ok: true, diff --git a/src/commands/fix/agent-fix.mts b/src/commands/fix/agent-fix.mts index 83c885a1f..1c6ff0ad8 100644 --- a/src/commands/fix/agent-fix.mts +++ b/src/commands/fix/agent-fix.mts @@ -5,7 +5,7 @@ import semver from 'semver' import { getManifestData } from '@socketsecurity/registry' import { arrayUnique } from '@socketsecurity/registry/lib/arrays' -import { debugFn, isDebug } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn, isDebug } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' import { runNpmScript } from '@socketsecurity/registry/lib/npm' import { @@ -134,15 +134,15 @@ export async function agentFix( spinner?.stop() logger.info('No fixable vulns found.') if (alertsMap.size) { - debugFn('inspect:', { alertsMap }) + debugDir('inspect', { alertsMap }) } else { - debugFn('inspect: { alertsMap: Map(0) {} }') + debugFn('inspect', '{ alertsMap: Map(0) {} }') } return { ok: true, data: { fixed: false } } } - if (isDebug()) { - debugFn('found: cves for', Array.from(infoByPartialPurl.keys())) + if (isDebug('notice')) { + debugFn('notice', 'found: cves for', Array.from(infoByPartialPurl.keys())) } // Lazily access constants.packumentCache. @@ -198,7 +198,7 @@ export async function agentFix( spinner?.indent() if (getManifestData(partialPurlObj.type, name)) { - debugFn(`found: Socket Optimize variant for ${name}`) + debugFn('notice', `found: Socket Optimize variant for ${name}`) } // eslint-disable-next-line no-await-in-loop const packument = await fetchPackagePackument(name) @@ -266,7 +266,7 @@ export async function agentFix( ) if (!oldVersions.length) { - debugFn(`skip: ${name} not found\n`) + debugFn('notice', `skip: ${name} not found\n`) // Skip to next package. cleanupInfoEntriesLoop() continue infoEntriesLoop @@ -283,7 +283,7 @@ export async function agentFix( let hasAnnouncedWorkspace = false let workspaceLogCallCount = logger.logCallCount if (isDebug()) { - debugFn(`check: workspace ${workspace}`) + debugFn('notice', `check: workspace ${workspace}`) hasAnnouncedWorkspace = true workspaceLogCallCount = logger.logCallCount } @@ -294,7 +294,7 @@ export async function agentFix( const node = findPackageNode(actualTree, name, oldVersion) if (!node) { - debugFn(`skip: ${oldId} not found`) + debugFn('notice', `skip: ${oldId} not found`) continue oldVersionsLoop } infosLoop: for (const { @@ -319,7 +319,7 @@ export async function agentFix( continue infosLoop } if (semver.gte(oldVersion, newVersion)) { - debugFn(`skip: ${oldId} is >= ${newVersion}`) + debugFn('notice', `skip: ${oldId} is >= ${newVersion}`) continue infosLoop } if ( @@ -328,7 +328,7 @@ export async function agentFix( b.workspace === branchWorkspace && b.newVersion === newVersion, ) ) { - debugFn(`skip: open PR found for ${name}@${newVersion}`) + debugFn('notice', `skip: open PR found for ${name}@${newVersion}`) if (++count >= limit) { cleanupInfoEntriesLoop() break infoEntriesLoop @@ -366,7 +366,7 @@ export async function agentFix( ) // eslint-disable-next-line no-await-in-loop if (!(await editablePkgJson.save({ ignoreWhitespace: true }))) { - debugFn(`skip: ${workspace}/package.json unchanged`) + debugFn('notice', `skip: ${workspace}/package.json unchanged`) // Reset things just in case. if (ciEnv) { // eslint-disable-next-line no-await-in-loop @@ -461,12 +461,12 @@ export async function agentFix( ) ) { skipPr = true - debugFn(`skip: branch "${branch}" exists`) + debugFn('notice', `skip: branch "${branch}" exists`) } // eslint-disable-next-line no-await-in-loop else if (await gitRemoteBranchExists(branch, cwd)) { skipPr = true - debugFn(`skip: remote branch "${branch}" exists`) + debugFn('notice', `skip: remote branch "${branch}" exists`) } else if ( // eslint-disable-next-line no-await-in-loop !(await gitCreateAndPushBranch( @@ -613,8 +613,7 @@ export async function agentFix( cause: `Update failed for ${oldId} in ${workspace}${error ? '; ' + error : ''}`, } } - debugFn('name:', name) - debugFn('increment: count', count + 1) + debugFn('notice', 'increment: count', count + 1) if (++count >= limit) { cleanupInfoEntriesLoop() break infoEntriesLoop diff --git a/src/commands/fix/fix-branch-helpers.mts b/src/commands/fix/fix-branch-helpers.mts index 2179136d5..bd5954b32 100644 --- a/src/commands/fix/fix-branch-helpers.mts +++ b/src/commands/fix/fix-branch-helpers.mts @@ -35,15 +35,16 @@ export function getActiveBranchesForPackage( } } - if (isDebug()) { + if (isDebug('notice')) { const fullName = resolvePackageName(partialPurlObj) if (activeBranches.length) { debugFn( + 'notice', `found: ${activeBranches.length} active branches for ${fullName}\n`, activeBranches, ) } else if (openPrs.length) { - debugFn(`miss: 0 active branches found for ${fullName}`) + debugFn('notice', `miss: 0 active branches found for ${fullName}`) } } diff --git a/src/commands/fix/fix-env-helpers.mts b/src/commands/fix/fix-env-helpers.mts index ca712b637..9b16254e3 100644 --- a/src/commands/fix/fix-env-helpers.mts +++ b/src/commands/fix/fix-env-helpers.mts @@ -17,7 +17,7 @@ async function getEnvRepoInfo( // Lazily access constants.ENV.GITHUB_REPOSITORY. const { GITHUB_REPOSITORY } = constants.ENV if (!GITHUB_REPOSITORY) { - debugFn('miss: GITHUB_REPOSITORY env var') + debugFn('notice', 'miss: GITHUB_REPOSITORY env var') } const ownerSlashRepo = GITHUB_REPOSITORY const slashIndex = ownerSlashRepo.indexOf('/') diff --git a/src/commands/fix/git.mts b/src/commands/fix/git.mts index cdf76a3b9..d1060c5d4 100644 --- a/src/commands/fix/git.mts +++ b/src/commands/fix/git.mts @@ -1,7 +1,7 @@ import semver from 'semver' import { PackageURL } from '@socketregistry/packageurl-js' -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { normalizePath } from '@socketsecurity/registry/lib/path' import { escapeRegExp } from '@socketsecurity/registry/lib/regexps' import { spawn } from '@socketsecurity/registry/lib/spawn' @@ -246,7 +246,8 @@ export async function gitCreateAndPushBranch( return true } catch (e) { debugFn( - `catch: git push --force --set-upstream origin ${branch} failed\n`, + 'error', + `caught: git push --force --set-upstream origin ${branch} failed\n`, e, ) } @@ -284,9 +285,11 @@ export async function gitRepoInfo( return { owner, repo } } } catch {} - debugFn('git: unmatched git remote URL format', remoteUrl) + debugFn('error', 'git: unmatched git remote URL format') + debugDir('inspect', { remoteUrl }) } catch (e) { - debugFn('catch: git remote get-url origin failed\n', e) + debugFn('error', 'caught: git remote get-url origin failed') + debugDir('inspect', { error: e }) } return null } @@ -315,7 +318,8 @@ export async function gitEnsureIdentity( try { await spawn('git', ['config', prop, value], stdioIgnoreOptions) } catch (e) { - debugFn(`catch: git config ${prop} ${value} failed\n`, e) + debugFn('error', `caught: git config ${prop} ${value} failed`) + debugDir('inspect', { error: e }) } } }), @@ -373,7 +377,8 @@ export async function gitUnstagedModifiedFiles( data: rawRelPaths.map(relPath => normalizePath(relPath)), } } catch (e) { - debugFn('catch: git diff --name-only failed\n', e) + debugFn('error', 'caught: git diff --name-only failed') + debugDir('inspect', { error: e }) return { ok: false, diff --git a/src/commands/fix/handle-fix.mts b/src/commands/fix/handle-fix.mts index af2bc4599..4a109dec2 100644 --- a/src/commands/fix/handle-fix.mts +++ b/src/commands/fix/handle-fix.mts @@ -1,4 +1,4 @@ -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' import { pluralize } from '@socketsecurity/registry/lib/words' @@ -59,7 +59,8 @@ export async function handleFix({ ) ghsasCount = ghsas.length } else { - debugFn('coana fail:', { + debugFn('error', 'fail: Coana CLI') + debugDir('inspect', { message: autoCResult.message, cause: autoCResult.cause, }) @@ -87,7 +88,8 @@ export async function handleFix({ spinner?.stop() if (!applyFixesCResult.ok) { - debugFn('coana fail:', { + debugFn('error', 'fail: Coana CLI') + debugDir('inspect', { message: applyFixesCResult.message, cause: applyFixesCResult.cause, }) diff --git a/src/commands/fix/npm-fix.mts b/src/commands/fix/npm-fix.mts index 90ce491ff..232b29d2f 100644 --- a/src/commands/fix/npm-fix.mts +++ b/src/commands/fix/npm-fix.mts @@ -1,4 +1,4 @@ -import { debugFn, isDebug } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn, isDebug } from '@socketsecurity/registry/lib/debug' import { agentFix } from './agent-fix.mts' import { getCiEnv, getOpenPrsForEnvironment } from './fix-env-helpers.mts' @@ -77,7 +77,8 @@ export async function npmFix( } } catch (e) { spinner?.stop() - debugFn('catch: PURL API\n', e) + debugFn('error', 'caught: PURL API') + debugDir('inspect', { error: e }) return { ok: false, message: 'API Error', diff --git a/src/commands/fix/open-pr.mts b/src/commands/fix/open-pr.mts index b2aeb7d59..7738a7d71 100644 --- a/src/commands/fix/open-pr.mts +++ b/src/commands/fix/open-pr.mts @@ -10,7 +10,7 @@ import { Octokit } from '@octokit/rest' import semver from 'semver' import { PackageURL } from '@socketregistry/packageurl-js' -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { readJson, writeJson } from '@socketsecurity/registry/lib/fs' import { spawn } from '@socketsecurity/registry/lib/spawn' import { isNonEmptyString } from '@socketsecurity/registry/lib/strings' @@ -37,7 +37,7 @@ function getOctokit() { // Lazily access constants.ENV.SOCKET_CLI_GITHUB_TOKEN. const { SOCKET_CLI_GITHUB_TOKEN } = constants.ENV if (!SOCKET_CLI_GITHUB_TOKEN) { - debugFn('miss: SOCKET_CLI_GITHUB_TOKEN env var') + debugFn('notice', 'miss: SOCKET_CLI_GITHUB_TOKEN env var') } _octokit = new Octokit({ auth: SOCKET_CLI_GITHUB_TOKEN, @@ -52,7 +52,7 @@ export function getOctokitGraphql(): typeof OctokitGraphql { // Lazily access constants.ENV.SOCKET_CLI_GITHUB_TOKEN. const { SOCKET_CLI_GITHUB_TOKEN } = constants.ENV if (!SOCKET_CLI_GITHUB_TOKEN) { - debugFn('miss: SOCKET_CLI_GITHUB_TOKEN env var') + debugFn('notice', 'miss: SOCKET_CLI_GITHUB_TOKEN env var') } _octokitGraphql = OctokitGraphql.defaults({ headers: { @@ -171,7 +171,7 @@ export async function cleanupOpenPrs( pull_number: prNum, state: 'closed', }) - debugFn(`close: ${prRef} for ${prToVersion}`) + debugFn('notice', `close: ${prRef} for ${prToVersion}`) // Remove entry from parent object. context.parent.splice(context.index, 1) // Mark cache to be saved. @@ -179,6 +179,7 @@ export async function cleanupOpenPrs( return null } catch (e) { debugFn( + 'error', `fail: close ${prRef} for ${prToVersion}\n`, (e as Error)?.message || 'unknown error', ) @@ -194,7 +195,7 @@ export async function cleanupOpenPrs( base: match.headRefName, head: match.baseRefName, }) - debugFn('update: stale', prRef) + debugFn('notice', 'update: stale', prRef) // Update entry entry. if (context.apiType === 'graphql') { context.entry.mergeStateStatus = 'CLEAN' @@ -205,7 +206,7 @@ export async function cleanupOpenPrs( cachesToSave.set(context.cacheKey, context.data) } catch (e) { const message = (e as Error)?.message || 'Unknown error' - debugFn(`fail: update ${prRef} - ${message}`) + debugFn('error', `fail: update ${prRef} - ${message}`) } } return match @@ -477,7 +478,7 @@ export async function openPr( .join('\n') message += `:\n${details}` } - debugFn(message) + debugFn('error', message) } return null } @@ -512,6 +513,7 @@ export async function setGitRemoteGithubRepoUrl( try { await spawn('git', ['remote', 'set-url', 'origin', url], stdioIgnoreOptions) } catch (e) { - debugFn('catch: unexpected\n', e) + debugFn('error', 'caught: unexpected error') + debugDir('inspect', { error: e }) } } diff --git a/src/commands/fix/pnpm-fix.mts b/src/commands/fix/pnpm-fix.mts index e1e913ea3..ee8be5895 100644 --- a/src/commands/fix/pnpm-fix.mts +++ b/src/commands/fix/pnpm-fix.mts @@ -1,6 +1,6 @@ import { promises as fs } from 'node:fs' -import { debugFn, isDebug } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn, isDebug } from '@socketsecurity/registry/lib/debug' import { hasKeys } from '@socketsecurity/registry/lib/objects' import { agentFix } from './agent-fix.mts' @@ -118,7 +118,8 @@ export async function pnpmFix( ) } catch (e) { spinner?.stop() - debugFn('catch: PURL API\n', e) + debugFn('error', 'caught: PURL API') + debugDir('inspect', { error: e }) return { ok: false, message: 'API Error', diff --git a/src/commands/install/setup-tab-completion.mts b/src/commands/install/setup-tab-completion.mts index a0eacfd23..b8185a17f 100644 --- a/src/commands/install/setup-tab-completion.mts +++ b/src/commands/install/setup-tab-completion.mts @@ -31,10 +31,10 @@ export async function setupTabCompletion(targetName: string): Promise< // Target dir is something like ~/.local/share/socket/settings/completion (linux) const targetDir = path.dirname(targetPath) - debugFn('target: path + dir', targetPath, targetDir) + debugFn('notice', 'target: path + dir', targetPath, targetDir) if (!fs.existsSync(targetDir)) { - debugFn('create: target dir') + debugFn('notice', 'create: target dir') fs.mkdirSync(targetDir, { recursive: true }) } diff --git a/src/commands/manifest/cmd-manifest-auto.mts b/src/commands/manifest/cmd-manifest-auto.mts index 6fbf65580..d1abbf38b 100644 --- a/src/commands/manifest/cmd-manifest-auto.mts +++ b/src/commands/manifest/cmd-manifest-auto.mts @@ -1,6 +1,6 @@ import path from 'node:path' -import { debugLog } from '@socketsecurity/registry/lib/debug' +import { debugDir } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' import { detectManifestActions } from './detect-manifest-actions.mts' @@ -87,7 +87,7 @@ async function run( const sockJson = await readOrDefaultSocketJson(cwd) const detected = await detectManifestActions(sockJson, cwd) - debugLog('[DEBUG]', detected) + debugDir('inspect', { detected }) if (cli.flags['dryRun']) { logger.log(DRY_RUN_BAILING_NOW) diff --git a/src/commands/manifest/cmd-manifest-gradle.mts b/src/commands/manifest/cmd-manifest-gradle.mts index 4d28790ea..37fbc1b5e 100644 --- a/src/commands/manifest/cmd-manifest-gradle.mts +++ b/src/commands/manifest/cmd-manifest-gradle.mts @@ -99,7 +99,11 @@ async function run( const sockJson = await readOrDefaultSocketJson(cwd) - debugFn('override: socket.json gradle', sockJson?.defaults?.manifest?.gradle) + debugFn( + 'inspect', + 'override: socket.json gradle', + sockJson?.defaults?.manifest?.gradle, + ) // Set defaults for any flag/arg that is not given. Check socket.json first. if (!bin) { diff --git a/src/commands/manifest/cmd-manifest-kotlin.mts b/src/commands/manifest/cmd-manifest-kotlin.mts index 5e680ae65..dc7975aa7 100644 --- a/src/commands/manifest/cmd-manifest-kotlin.mts +++ b/src/commands/manifest/cmd-manifest-kotlin.mts @@ -104,7 +104,11 @@ async function run( const sockJson = await readOrDefaultSocketJson(cwd) - debugFn('override: socket.json gradle', sockJson?.defaults?.manifest?.gradle) + debugFn( + 'inspect', + 'override: socket.json gradle', + sockJson?.defaults?.manifest?.gradle, + ) // Set defaults for any flag/arg that is not given. Check socket.json first. if (!bin) { diff --git a/src/commands/manifest/cmd-manifest-scala.mts b/src/commands/manifest/cmd-manifest-scala.mts index ff832d824..6f5474d3b 100644 --- a/src/commands/manifest/cmd-manifest-scala.mts +++ b/src/commands/manifest/cmd-manifest-scala.mts @@ -112,7 +112,11 @@ async function run( const sockJson = await readOrDefaultSocketJson(cwd) - debugFn('override: socket.json sbt', sockJson?.defaults?.manifest?.sbt) + debugFn( + 'inspect', + 'override: socket.json sbt', + sockJson?.defaults?.manifest?.sbt, + ) // Set defaults for any flag/arg that is not given. Check socket.json first. if (!bin) { diff --git a/src/commands/manifest/detect-manifest-actions.mts b/src/commands/manifest/detect-manifest-actions.mts index f04995931..80ae611ac 100644 --- a/src/commands/manifest/detect-manifest-actions.mts +++ b/src/commands/manifest/detect-manifest-actions.mts @@ -31,31 +31,40 @@ export async function detectManifestActions( } if (sockJson?.defaults?.manifest?.sbt?.disabled) { - debugLog('[DEBUG] - sbt auto-detection is disabled in socket.json') + debugLog( + 'notice', + '[DEBUG] - sbt auto-detection is disabled in socket.json', + ) } else if (existsSync(path.join(cwd, 'build.sbt'))) { - debugLog('[DEBUG] - Detected a Scala sbt build file') + debugLog('notice', '[DEBUG] - Detected a Scala sbt build file') output.sbt = true output.count += 1 } if (sockJson?.defaults?.manifest?.gradle?.disabled) { - debugLog('[DEBUG] - gradle auto-detection is disabled in socket.json') + debugLog( + 'notice', + '[DEBUG] - gradle auto-detection is disabled in socket.json', + ) } else if (existsSync(path.join(cwd, 'gradlew'))) { - debugLog('[DEBUG] - Detected a gradle build file') + debugLog('notice', '[DEBUG] - Detected a gradle build file') output.gradle = true output.count += 1 } if (sockJson?.defaults?.manifest?.conda?.disabled) { - debugLog('[DEBUG] - conda auto-detection is disabled in socket.json') + debugLog( + 'notice', + '[DEBUG] - conda auto-detection is disabled in socket.json', + ) } else { const envyml = path.join(cwd, 'environment.yml') const hasEnvyml = existsSync(envyml) const envyaml = path.join(cwd, 'environment.yaml') const hasEnvyaml = !hasEnvyml && existsSync(envyaml) if (hasEnvyml || hasEnvyaml) { - debugLog('[DEBUG] - Detected an environment.yml Conda file') + debugLog('notice', '[DEBUG] - Detected an environment.yml Conda file') output.conda = true output.count += 1 } diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index 0023ae475..3ba6a8e43 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -1,7 +1,7 @@ import fs from 'node:fs' import path from 'node:path' -import { debugLog } from '@socketsecurity/registry/lib/debug' +import { debugDir } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' import { input, select } from '@socketsecurity/registry/lib/prompts' @@ -16,7 +16,7 @@ export async function setupManifestConfig( defaultOnReadError = false, ): Promise> { const detected = await detectManifestActions(null, cwd) - debugLog('[DEBUG]', detected) + debugDir('inspect', { detected }) // - repeat // - give the user an option to configure one of the supported targets diff --git a/src/commands/optimize/update-lockfile.mts b/src/commands/optimize/update-lockfile.mts index 62a069525..a3f396fb6 100644 --- a/src/commands/optimize/update-lockfile.mts +++ b/src/commands/optimize/update-lockfile.mts @@ -1,4 +1,4 @@ -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { Spinner } from '@socketsecurity/registry/lib/spinner' import constants from '../../constants.mts' @@ -45,7 +45,8 @@ export async function updateLockfile( } catch (e) { spinner?.stop() - debugFn('fail: update\n', e) + debugFn('error', 'fail: update') + debugDir('inspect', { error: e }) return { ok: false, diff --git a/src/commands/package/output-purls-shallow-score.mts b/src/commands/package/output-purls-shallow-score.mts index a518182a8..da7cfa8ef 100644 --- a/src/commands/package/output-purls-shallow-score.mts +++ b/src/commands/package/output-purls-shallow-score.mts @@ -71,7 +71,7 @@ function formatReportCard(artifact: DedupedArtifact, color: boolean): string { } const alertString = getAlertString(artifact.alerts, !color) if (!artifact.ecosystem) { - debugFn('miss: artifact ecosystem', artifact) + debugFn('notice', 'miss: artifact ecosystem', artifact) } const purl = `pkg:${artifact.ecosystem}/${artifact.name}${artifact.version ? '@' + artifact.version : ''}` diff --git a/src/commands/repository/fetch-list-all-repos.mts b/src/commands/repository/fetch-list-all-repos.mts index f04fb44f4..c29d8d0f3 100644 --- a/src/commands/repository/fetch-list-all-repos.mts +++ b/src/commands/repository/fetch-list-all-repos.mts @@ -1,4 +1,4 @@ -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { handleApiCall } from '../../utils/api.mts' import { setupSdk } from '../../utils/sdk.mts' @@ -33,7 +33,7 @@ export async function fetchListAllRepos({ } } // eslint-disable-next-line no-await-in-loop - const result = await handleApiCall( + const orgRepoListCResult = await handleApiCall( sockSdk.getOrgRepoList(orgSlug, { sort, direction, @@ -42,13 +42,14 @@ export async function fetchListAllRepos({ }), 'list of repositories', ) - if (!result.ok) { - debugFn('fail: fetch repo\n', result) - return result + if (!orgRepoListCResult.ok) { + debugFn('error', 'fail: fetch repo') + debugDir('inspect', { orgRepoListCResult }) + return orgRepoListCResult } - result.data.results.forEach(row => rows.push(row)) - nextPage = result.data.nextPage ?? -1 + orgRepoListCResult.data.results.forEach(row => rows.push(row)) + nextPage = orgRepoListCResult.data.nextPage ?? -1 } return { diff --git a/src/commands/scan/create-scan-from-github.mts b/src/commands/scan/create-scan-from-github.mts index fc1ddae77..1e3db4951 100644 --- a/src/commands/scan/create-scan-from-github.mts +++ b/src/commands/scan/create-scan-from-github.mts @@ -228,7 +228,7 @@ async function scanOneRepo( } const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), repoSlug)) - debugFn('init: temp dir for scan root', tmpDir) + debugFn('notice', 'init: temp dir for scan root', tmpDir) const downloadResult = await testAndDownloadManifestFiles({ files, @@ -357,15 +357,19 @@ async function testAndDownloadManifestFile({ repoApiUrl: string githubToken: string }): Promise> { - debugFn('testing: file', file) + debugFn('notice', 'testing: file', file) if (!SUPPORTED_FILE_PATTERNS.some(regex => regex.test(file))) { - debugFn(' - skip: not a known pattern') + debugFn('notice', ' - skip: not a known pattern') // Not an error. return { ok: true, data: { isManifest: false } } } - debugFn('found: manifest file, going to attempt to download it;', file) + debugFn( + 'notice', + 'found: manifest file, going to attempt to download it;', + file, + ) const result = await downloadManifestFile({ file, @@ -391,10 +395,10 @@ async function downloadManifestFile({ repoApiUrl: string githubToken: string }): Promise> { - debugFn('request: download url from GitHub') + debugFn('notice', 'request: download url from GitHub') const fileUrl = `${repoApiUrl}/contents/${file}?ref=${defaultBranch}` - debugFn('url: file', fileUrl) + debugFn('inspect', 'url: file', fileUrl) const downloadUrlResponse = await fetch(fileUrl, { method: 'GET', @@ -402,10 +406,10 @@ async function downloadManifestFile({ Authorization: `Bearer ${githubToken}`, }, }) - debugFn('complete: request') + debugFn('notice', 'complete: request') const downloadUrlText = await downloadUrlResponse.text() - debugFn('response: raw download url', downloadUrlText) + debugFn('inspect', 'response: raw download url', downloadUrlText) let downloadUrl try { @@ -423,7 +427,13 @@ async function downloadManifestFile({ } const localPath = path.join(tmpDir, file) - debugFn('download: manifest file started', downloadUrl, '->', localPath) + debugFn( + 'notice', + 'download: manifest file started', + downloadUrl, + '->', + localPath, + ) // Now stream the file to that file... const result = await streamDownloadWithFetch(localPath, downloadUrl) @@ -435,7 +445,7 @@ async function downloadManifestFile({ return result } - debugFn('download: manifest file completed') + debugFn('notice', 'download: manifest file completed') return { ok: true, data: undefined } } @@ -487,8 +497,7 @@ async function streamDownloadWithFetch( 'An error was thrown while trying to download a manifest file... url:', downloadUrl, ) - debugFn('Raw error:') - debugFn(error) + debugFn('inspect', { error }) // If an error occurs and fileStream was created, attempt to clean up. if (fs.existsSync(localPath)) { @@ -512,7 +521,7 @@ async function streamDownloadWithFetch( // If error was due to bad HTTP status detailedError += ` (HTTP Status: ${response.status} ${response.statusText})` } - debugFn(detailedError) + debugFn('error', detailedError) return { ok: false, message: 'Download Failed', cause: detailedError } } } @@ -541,7 +550,7 @@ async function getLastCommitDetails({ ) const commitApiUrl = `${repoApiUrl}/commits?sha=${defaultBranch}&per_page=1` - debugFn('url: commit', commitApiUrl) + debugFn('inspect', 'url: commit', commitApiUrl) const commitResponse = await fetch(commitApiUrl, { headers: { @@ -550,7 +559,7 @@ async function getLastCommitDetails({ }) const commitText = await commitResponse.text() - debugFn('response: commit', commitText) + debugFn('inspect', 'response: commit', commitText) let lastCommit try { @@ -645,7 +654,7 @@ async function getRepoDetails({ CResult<{ defaultBranch: string; repoDetails: unknown; repoApiUrl: string }> > { const repoApiUrl = `${githubApiUrl}/repos/${orgGithub}/${repoSlug}` - debugFn('url: repo', repoApiUrl) + debugFn('inspect', 'url: repo', repoApiUrl) const repoDetailsResponse = await fetch(repoApiUrl, { method: 'GET', @@ -656,7 +665,7 @@ async function getRepoDetails({ logger.success(`Request completed.`) const repoDetailsText = await repoDetailsResponse.text() - debugFn('response: repo', repoDetailsText) + debugFn('inspect', 'response: repo', repoDetailsText) let repoDetails try { @@ -701,7 +710,7 @@ async function getRepoBranchTree({ ) const treeApiUrl = `${repoApiUrl}/git/trees/${defaultBranch}?recursive=1` - debugFn('url: tree', treeApiUrl) + debugFn('inspect', 'url: tree', treeApiUrl) const treeResponse = await fetch(treeApiUrl, { method: 'GET', @@ -711,7 +720,7 @@ async function getRepoBranchTree({ }) const treeText = await treeResponse.text() - debugFn('response: tree', treeText) + debugFn('inspect', 'response: tree', treeText) let treeDetails try { @@ -745,7 +754,7 @@ async function getRepoBranchTree({ } if (!treeDetails.tree || !Array.isArray(treeDetails.tree)) { - debugFn('treeDetails.tree:', treeDetails.tree) + debugFn('inspect', 'treeDetails.tree:', treeDetails.tree) return { ok: false, diff --git a/src/commands/scan/fetch-report-data.mts b/src/commands/scan/fetch-report-data.mts index 52b6e813a..078d3cf23 100644 --- a/src/commands/scan/fetch-report-data.mts +++ b/src/commands/scan/fetch-report-data.mts @@ -1,4 +1,4 @@ -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' import constants from '../../constants.mts' @@ -80,7 +80,8 @@ export async function fetchReportData( return JSON.parse(line) } catch { ok = false - debugFn('fail: parse NDJSON\n', line) + debugFn('error', 'fail: parse NDJSON') + debugDir('inspect', { line }) return } }) as unknown as SocketArtifact[] diff --git a/src/commands/scan/fetch-scan.mts b/src/commands/scan/fetch-scan.mts index b46036a47..9e259e504 100644 --- a/src/commands/scan/fetch-scan.mts +++ b/src/commands/scan/fetch-scan.mts @@ -1,4 +1,4 @@ -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { queryApiSafeText } from '../../utils/api.mts' @@ -28,7 +28,8 @@ export async function fetchScan( return JSON.parse(line) } catch { ok = false - debugFn('fail: parse NDJSON\n', line) + debugFn('error', 'fail: parse NDJSON') + debugDir('inspect', { line }) return null } }) as unknown as SocketArtifact[] diff --git a/src/commands/wrapper/postinstall-wrapper.mts b/src/commands/wrapper/postinstall-wrapper.mts index 4b830beb9..e624bc078 100644 --- a/src/commands/wrapper/postinstall-wrapper.mts +++ b/src/commands/wrapper/postinstall-wrapper.mts @@ -1,6 +1,6 @@ import fs, { existsSync } from 'node:fs' -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' import { confirm } from '@socketsecurity/registry/lib/prompts' @@ -48,7 +48,8 @@ Do you want to install "safe npm" (this will create an alias to the socket-npm c } } } catch (e) { - debugFn('fail: setup tab completion\n', e) + debugFn('error', 'fail: setup tab completion') + debugDir('inspect', { error: e }) // Ignore. Skip tab completion setup. } if (!updatedTabCompletion) { diff --git a/src/shadow/npm/arborist-helpers.mts b/src/shadow/npm/arborist-helpers.mts index 8963d6fdf..3a141c107 100644 --- a/src/shadow/npm/arborist-helpers.mts +++ b/src/shadow/npm/arborist-helpers.mts @@ -142,7 +142,11 @@ export function findPackageNodes( const { version: targetVersion } = node if (!targetVersion && Array.isArray(node.errors) && node.errors.length) { - debugFn(`miss: version for ${node.name} due to errors:\n`, node.errors) + debugFn( + 'notice', + `miss: version for ${node.name} due to errors:\n`, + node.errors, + ) } if ( node.name === name && @@ -246,7 +250,7 @@ export function getDetailsFromDiff( const details: PackageDetail[] = [] // `diff` is `null` when `npm install --package-lock-only` is passed. if (!diff) { - debugFn(`miss: diff is ${diff}`) + debugFn('notice', `miss: diff is ${diff}`) return details } @@ -285,7 +289,7 @@ export function getDetailsFromDiff( } } else { // TODO: This debug log has too much information. We should narrow it down. - // debugFn('skip: meta change diff\n', diff) + // debugFn('notice', 'skip: meta change diff\n', diff) } } else { keep = action !== DiffAction.remove diff --git a/src/utils/alerts-map.mts b/src/utils/alerts-map.mts index ee846466c..b93e5ab95 100644 --- a/src/utils/alerts-map.mts +++ b/src/utils/alerts-map.mts @@ -1,5 +1,5 @@ import { arrayUnique } from '@socketsecurity/registry/lib/arrays' -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' import { extractPurlsFromPnpmLockfile } from './pnpm.mts' @@ -72,7 +72,7 @@ export async function getAlertsMapFromPurls( const { spinner } = options const uniqPurls = arrayUnique(purls) - debugFn('inspect:', { purls: uniqPurls }) + debugDir('inspect', { purls: uniqPurls }) let { length: remaining } = uniqPurls const alertsByPurl: AlertsByPurl = new Map() @@ -131,7 +131,7 @@ export async function getAlertsMapFromPurls( batchResult.error, batchResult.cause ? `( ${batchResult.cause} )` : '', ) - debugFn('inspect:', { batchResult }) + debugDir('inspect', { batchResult }) break } remaining -= 1 diff --git a/src/utils/api.mts b/src/utils/api.mts index a926ca0a1..d0752d52e 100644 --- a/src/utils/api.mts +++ b/src/utils/api.mts @@ -1,4 +1,4 @@ -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' import { isNonEmptyString } from '@socketsecurity/registry/lib/strings' @@ -60,7 +60,8 @@ export async function handleApiCall( const message = `${e || 'No error message returned'}` const reason = `${e || 'No error message returned'}` - debugFn(`catch: ${fetchingDesc} error:\n`, e) + debugFn('error', `caught: ${fetchingDesc} error`) + debugDir('inspect', { error: e }) return { ok: false, @@ -73,11 +74,12 @@ export async function handleApiCall( // Note: TS can't narrow down the type of result due to generics if (result.success === false) { - const err = result as SocketSdkErrorType - const message = `${err.error || 'No error message returned'}` - const { cause: reason } = err + const error = result as SocketSdkErrorType + const message = `${error.error || 'No error message returned'}` + const { cause: reason } = error - debugFn(`fail: ${fetchingDesc} bad response:\n`, err) + debugFn('error', `fail: ${fetchingDesc} bad response`) + debugDir('inspect', { error }) return { ok: false, @@ -107,7 +109,8 @@ export async function handleApiCallNoSpinner( const message = `${e || 'No error message returned'}` const reason = `${e || 'No error message returned'}` - debugFn(`catch: ${description} error:\n`, e) + debugFn('error', `caught: ${description} error`) + debugDir('inspect', { error: e }) return { ok: false, @@ -118,15 +121,16 @@ export async function handleApiCallNoSpinner( // Note: TS can't narrow down the type of result due to generics if (result.success === false) { - const err = result as SocketSdkErrorType - const message = `${err.error || 'No error message returned'}` + const error = result as SocketSdkErrorType + const message = `${error.error || 'No error message returned'}` - debugFn(`fail: ${description} bad response:\n`, err) + debugFn('error', `fail: ${description} bad response`) + debugDir('inspect', { error }) return { ok: false, message: 'Socket API returned an error', - cause: `${message}${err.cause ? ` ( Reason: ${err.cause} )` : ''}`, + cause: `${message}${error.cause ? ` ( Reason: ${error.cause} )` : ''}`, data: { code: result.status, }, @@ -223,7 +227,8 @@ export async function queryApiSafeText( const cause = (e as undefined | { message: string })?.message - debugFn('catch: queryApi() error\n', e) + debugFn('error', 'caught: queryApi() error') + debugDir('inspect', { error: e }) return { ok: false, @@ -249,7 +254,8 @@ export async function queryApiSafeText( data, } } catch (e) { - debugFn('catch: await result.text() error\n', e) + debugFn('error', 'caught: await result.text() error') + debugDir('inspect', { error: e }) return { ok: false, diff --git a/src/utils/config.mts b/src/utils/config.mts index 43c1a0b48..c6c399f10 100644 --- a/src/utils/config.mts +++ b/src/utils/config.mts @@ -153,7 +153,7 @@ let _cachedConfig: LocalConfig | undefined let _readOnlyConfig = false export function overrideCachedConfig(jsonConfig: unknown): CResult { - debugFn('override: full config (not stored)') + debugFn('notice', 'override: full config (not stored)') let config try { @@ -199,7 +199,7 @@ export function overrideCachedConfig(jsonConfig: unknown): CResult { } export function overrideConfigApiToken(apiToken: unknown) { - debugFn('override: API token (not stored)') + debugFn('notice', 'override: API token (not stored)') // Set token to the local cached config and mark it read-only so it doesn't persist _cachedConfig = { diff --git a/src/utils/errors.mts b/src/utils/errors.mts index c2281bad6..1a3b1a33e 100644 --- a/src/utils/errors.mts +++ b/src/utils/errors.mts @@ -40,7 +40,7 @@ export function captureExceptionSync( if (!Sentry) { return '' } - debugFn('send: exception to Sentry') + debugFn('notice', 'send: exception to Sentry') return Sentry.captureException(exception, hint) as string } diff --git a/src/utils/package-environment.mts b/src/utils/package-environment.mts index ba97ce717..c9ff9089f 100644 --- a/src/utils/package-environment.mts +++ b/src/utils/package-environment.mts @@ -6,7 +6,7 @@ import semver from 'semver' import which from 'which' import { parse as parseBunLockb } from '@socketregistry/hyrious__bun.lockb/index.cjs' -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { Logger } from '@socketsecurity/registry/lib/logger' import { readPackageJson } from '@socketsecurity/registry/lib/packages' import { naturalCompare } from '@socketsecurity/registry/lib/sorts' @@ -232,7 +232,8 @@ async function getAgentVersion( ).stdout, ) ?? undefined } catch (e) { - debugFn('catch: unexpected\n', e) + debugFn('error', 'caught: unexpected error') + debugDir('inspect', { error: e }) } return result } diff --git a/src/utils/path-resolve.mts b/src/utils/path-resolve.mts index 64e3b6296..b761eb9b8 100644 --- a/src/utils/path-resolve.mts +++ b/src/utils/path-resolve.mts @@ -99,7 +99,7 @@ export async function getPackageFilesForScan( supportedFiles: SocketSdkReturnType<'getReportSupportedFiles'>['data'], config?: SocketYml | undefined, ): Promise { - debugFn(`resolve: ${inputPaths.length} paths`, inputPaths) + debugFn('notice', `resolve: ${inputPaths.length} paths`, inputPaths) // Lazily access constants.spinner. const { spinner } = constants @@ -113,10 +113,11 @@ export async function getPackageFilesForScan( socketConfig: config, }) - if (isDebug()) { + if (isDebug('notice')) { spinner.stop() debugFn( + 'notice', `Resolved ${inputPaths.length} paths to ${entries.length} local paths:\n`, entries, ) @@ -137,7 +138,7 @@ export async function getPackageFilesForScan( `Found ${packageFiles.length} local ${pluralize('file', packageFiles.length)}`, ) - debugFn('paths: absolute', packageFiles) + debugFn('inspect', 'paths: absolute', packageFiles) return packageFiles } diff --git a/src/utils/serialize-result-json.mts b/src/utils/serialize-result-json.mts index e5b5038fd..6ef55636d 100644 --- a/src/utils/serialize-result-json.mts +++ b/src/utils/serialize-result-json.mts @@ -1,4 +1,4 @@ -import { debugFn } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' import type { CResult } from '../types.mts' @@ -8,10 +8,10 @@ import type { CResult } from '../types.mts' export function serializeResultJson(data: CResult): string { if (typeof data !== 'object' || !data) { process.exitCode = 1 - debugFn('typeof data=', typeof data) + debugFn('inspect', 'typeof data=', typeof data) if (typeof data !== 'object' && data) { - debugFn('data:\n', data) + debugFn('inspect', 'data:\n', data) } // We should not allow the json value to be "null", or a boolean/number/string, @@ -31,13 +31,13 @@ export function serializeResultJson(data: CResult): string { try { return JSON.stringify(data, null, 2).trim() + '\n' } catch (e) { - debugFn('catch: unexpected\n', e) process.exitCode = 1 // This could be caused by circular references, which is an "us" problem const message = 'There was a problem converting the data set to JSON. Please try again without --json' logger.fail(message) + debugDir('inspect', { error: e }) return ( JSON.stringify({ ok: false, diff --git a/src/utils/socket-package-alert.mts b/src/utils/socket-package-alert.mts index 9cf28b289..fae2731df 100644 --- a/src/utils/socket-package-alert.mts +++ b/src/utils/socket-package-alert.mts @@ -3,7 +3,7 @@ import semver from 'semver' import colors from 'yoctocolors-cjs' import { getManifestData } from '@socketsecurity/registry' -import { debugFn, debugLog } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { hasOwn } from '@socketsecurity/registry/lib/objects' import { resolvePackageName } from '@socketsecurity/registry/lib/packages' import { naturalCompare } from '@socketsecurity/registry/lib/sorts' @@ -415,11 +415,11 @@ export function getCveInfoFromAlertsMap( } } - debugFn('fail: invalid SocketPackageAlert\n', alert) + debugFn('error', 'fail: invalid SocketPackageAlert') + debugDir('inspect', { alert }) if (error) { - // Explicitly use debugLog here. - debugLog((error as Error).message ?? error) + debugDir('inspect', { error: (error as Error).message ?? error }) } } } diff --git a/src/utils/socketjson.mts b/src/utils/socketjson.mts index d08951e17..96ceb1a86 100644 --- a/src/utils/socketjson.mts +++ b/src/utils/socketjson.mts @@ -1,7 +1,7 @@ import fs from 'node:fs' import path from 'node:path' -import { debugFn, debugLog } from '@socketsecurity/registry/lib/debug' +import { debugDir, debugFn } from '@socketsecurity/registry/lib/debug' import { logger } from '@socketsecurity/registry/lib/logger' import type { CResult } from '../types.mts' @@ -87,7 +87,7 @@ export async function readSocketJson( ): Promise> { const sockJsonPath = path.join(cwd, 'socket.json') if (!fs.existsSync(sockJsonPath)) { - debugFn(`miss: file not found ${sockJsonPath}`) + debugFn('notice', `miss: file not found ${sockJsonPath}`) return { ok: true, data: getDefaultSocketJson() } } @@ -95,8 +95,7 @@ export async function readSocketJson( try { json = await fs.promises.readFile(sockJsonPath, 'utf8') } catch (e) { - debugLog('[DEBUG] Raw error:') - debugLog(e) + debugDir('inspect', { error: e }) if (defaultOnError) { logger.warn('Warning: failed to read file, using default') @@ -114,7 +113,8 @@ export async function readSocketJson( try { obj = JSON.parse(json) } catch { - debugFn('fail: parse JSON\n', json) + debugFn('error', 'fail: parse JSON') + debugDir('inspect', { json }) if (defaultOnError) { logger.warn('Warning: failed to parse file, using default') @@ -147,8 +147,9 @@ export async function writeSocketJson( try { json = JSON.stringify(sockJson, null, 2) } catch (e) { - debugFn('fail: stringify JSON\n', e) - debugLog('[DEBUG] Object:\n', sockJson) + debugFn('error', 'fail: stringify JSON') + debugDir('inspect', { error: e }) + debugDir('inspect', { sockJson }) return { ok: false, message: 'Failed to serialize to JSON',