@socketsecurity/cli-with-sentry 0.14.65 → 0.14.66

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.
@@ -1 +1 @@
1
- {"version":3,"file":"shadow-npm-inject.js","sources":["../../src/utils/errors.ts","../../src/utils/fs.ts","../../src/utils/settings.ts","../../src/utils/sdk.ts","../../src/shadow/npm/arborist/lib/arborist/types.ts","../../src/shadow/npm/arborist/lib/dep-valid.ts","../../src/shadow/npm/proc-log/index.ts","../../src/shadow/npm/arborist/lib/override-set.ts","../../src/shadow/npm/arborist/lib/node.ts","../../src/shadow/npm/arborist/lib/edge.ts","../../src/utils/alert/artifact.ts","../../src/utils/alert/rules.ts","../../src/utils/objects.ts","../../src/utils/strings.ts","../../src/utils/alert/severity.ts","../../src/utils/color-or-markdown.ts","../../src/utils/socket-url.ts","../../src/utils/translations.ts","../../src/utils/socket-package-alert.ts","../../src/utils/lockfile/package-lock-json.ts","../../src/shadow/npm/arborist/lib/arborist/index.ts","../../src/shadow/npm/arborist/index.ts","../../src/shadow/npm/inject.ts"],"sourcesContent":["import { setTimeout as wait } from 'node:timers/promises'\n\nimport { debugLog } from '@socketsecurity/registry/lib/debug'\n\nimport constants from '../constants'\n\nconst {\n kInternalsSymbol,\n [kInternalsSymbol as unknown as 'Symbol(kInternalsSymbol)']: { getSentry }\n} = constants\n\ntype EventHintOrCaptureContext = { [key: string]: any } | Function\n\nexport class AuthError extends Error {}\n\nexport class InputError extends Error {\n public body: string | undefined\n\n constructor(message: string, body?: string) {\n super(message)\n this.body = body\n }\n}\n\nexport async function captureException(\n exception: unknown,\n hint?: EventHintOrCaptureContext | undefined\n): Promise<string> {\n const result = captureExceptionSync(exception, hint)\n // \"Sleep\" for a second, just in case, hopefully enough time to initiate fetch.\n await wait(1000)\n return result\n}\n\nexport function captureExceptionSync(\n exception: unknown,\n hint?: EventHintOrCaptureContext | undefined\n): string {\n const Sentry = getSentry()\n if (!Sentry) {\n return ''\n }\n debugLog('captureException: Sending exception to Sentry.')\n return Sentry.captureException(exception, hint) as string\n}\n\nexport function isErrnoException(\n value: unknown\n): value is NodeJS.ErrnoException {\n if (!(value instanceof Error)) {\n return false\n }\n return (value as NodeJS.ErrnoException).code !== undefined\n}\n","import { promises as fs, readFileSync as fsReadFileSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport constants from '../constants'\n\nimport type { Remap } from '@socketsecurity/registry/lib/objects'\nimport type { Abortable } from 'node:events'\nimport type {\n ObjectEncodingOptions,\n OpenMode,\n PathLike,\n PathOrFileDescriptor\n} from 'node:fs'\nimport type { FileHandle } from 'node:fs/promises'\n\nconst { abortSignal } = constants\n\nexport type FindUpOptions = {\n cwd?: string | undefined\n signal?: AbortSignal | undefined\n}\nexport async function findUp(\n name: string | string[],\n { cwd = process.cwd(), signal = abortSignal }: FindUpOptions\n): Promise<string | undefined> {\n let dir = path.resolve(cwd)\n const { root } = path.parse(dir)\n const names = [name].flat()\n while (dir && dir !== root) {\n for (const name of names) {\n if (signal?.aborted) {\n return undefined\n }\n const filePath = path.join(dir, name)\n try {\n // eslint-disable-next-line no-await-in-loop\n const stats = await fs.stat(filePath)\n if (stats.isFile()) {\n return filePath\n }\n } catch {}\n }\n dir = path.dirname(dir)\n }\n return undefined\n}\n\nexport type ReadFileOptions = Remap<\n ObjectEncodingOptions &\n Abortable & {\n flag?: OpenMode | undefined\n }\n>\n\nexport async function readFileBinary(\n filepath: PathLike | FileHandle,\n options?: ReadFileOptions | undefined\n): Promise<Buffer> {\n return (await fs.readFile(filepath, {\n signal: abortSignal,\n ...options,\n encoding: 'binary'\n } as ReadFileOptions)) as Buffer\n}\n\nexport async function readFileUtf8(\n filepath: PathLike | FileHandle,\n options?: ReadFileOptions | undefined\n): Promise<string> {\n return await fs.readFile(filepath, {\n signal: abortSignal,\n ...options,\n encoding: 'utf8'\n })\n}\n\nexport async function safeReadFile(\n filepath: PathLike | FileHandle,\n options?: 'utf8' | 'utf-8' | { encoding: 'utf8' | 'utf-8' } | undefined\n): Promise<string | undefined>\nexport async function safeReadFile(\n filepath: PathLike | FileHandle,\n options?: ReadFileOptions | NodeJS.BufferEncoding | undefined\n): Promise<Awaited<ReturnType<typeof fs.readFile>> | undefined> {\n try {\n return await fs.readFile(filepath, {\n encoding: 'utf8',\n signal: abortSignal,\n ...(typeof options === 'string' ? { encoding: options } : options)\n })\n } catch {}\n return undefined\n}\n\nexport function safeReadFileSync(\n filepath: PathOrFileDescriptor,\n options?: 'utf8' | 'utf-8' | { encoding: 'utf8' | 'utf-8' } | undefined\n): string | undefined\nexport function safeReadFileSync(\n filepath: PathOrFileDescriptor,\n options?:\n | {\n encoding?: NodeJS.BufferEncoding | undefined\n flag?: string | undefined\n }\n | NodeJS.BufferEncoding\n | undefined\n): ReturnType<typeof fsReadFileSync> | undefined {\n try {\n return fsReadFileSync(filepath, {\n encoding: 'utf8',\n ...(typeof options === 'string' ? { encoding: options } : options)\n })\n } catch {}\n return undefined\n}\n","import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport config from '@socketsecurity/config'\nimport { logger } from '@socketsecurity/registry/lib/logger'\n\nimport { safeReadFileSync } from './fs'\nimport constants from '../constants'\n\n// Default app data folder env var on Win\nconst LOCALAPPDATA = 'LOCALAPPDATA'\n// Default app data folder env var on Mac/Linux\nconst XDG_DATA_HOME = 'XDG_DATA_HOME'\nconst SOCKET_APP_DIR = 'socket/settings'\n\nconst supportedApiKeys: Set<keyof Settings> = new Set([\n 'apiBaseUrl',\n 'apiKey',\n 'apiProxy',\n 'enforcedOrgs'\n])\n\ninterface Settings {\n apiBaseUrl?: string | null | undefined\n // @deprecated\n apiKey?: string | null | undefined\n apiProxy?: string | null | undefined\n enforcedOrgs?: string[] | readonly string[] | null | undefined\n // apiToken is an alias for apiKey.\n apiToken?: string | null | undefined\n}\n\nlet settings: Settings | undefined\nlet settingsPath: string | undefined\nlet warnedSettingPathWin32Missing = false\nlet pendingSave = false\n\nfunction getSettings(): Settings {\n if (settings === undefined) {\n settings = {} as Settings\n const settingsPath = getSettingsPath()\n if (settingsPath) {\n const raw = safeReadFileSync(settingsPath)\n if (raw) {\n try {\n Object.assign(\n settings,\n JSON.parse(Buffer.from(raw, 'base64').toString())\n )\n } catch {\n logger.warn(`Failed to parse settings at ${settingsPath}`)\n }\n } else {\n fs.mkdirSync(path.dirname(settingsPath), { recursive: true })\n }\n }\n }\n return settings\n}\n\nfunction getSettingsPath(): string | undefined {\n // Get the OS app data folder:\n // - Win: %LOCALAPPDATA% or fail?\n // - Mac: %XDG_DATA_HOME% or fallback to \"~/Library/Application Support/\"\n // - Linux: %XDG_DATA_HOME% or fallback to \"~/.local/share/\"\n // Note: LOCALAPPDATA is typically: C:\\Users\\USERNAME\\AppData\n // Note: XDG stands for \"X Desktop Group\", nowadays \"freedesktop.org\"\n // On most systems that path is: $HOME/.local/share\n // Then append `socket/settings`, so:\n // - Win: %LOCALAPPDATA%\\socket\\settings or return undefined\n // - Mac: %XDG_DATA_HOME%/socket/settings or \"~/Library/Application Support/socket/settings\"\n // - Linux: %XDG_DATA_HOME%/socket/settings or \"~/.local/share/socket/settings\"\n\n if (settingsPath === undefined) {\n // Lazily access constants.WIN32.\n const { WIN32 } = constants\n let dataHome: string | undefined = WIN32\n ? process.env[LOCALAPPDATA]\n : process.env[XDG_DATA_HOME]\n if (!dataHome) {\n if (WIN32) {\n if (!warnedSettingPathWin32Missing) {\n warnedSettingPathWin32Missing = true\n logger.warn(`Missing %${LOCALAPPDATA}%`)\n }\n } else {\n dataHome = path.join(\n os.homedir(),\n ...(process.platform === 'darwin'\n ? ['Library', 'Application Support']\n : ['.local', 'share'])\n )\n }\n }\n settingsPath = dataHome ? path.join(dataHome, SOCKET_APP_DIR) : undefined\n }\n return settingsPath\n}\n\nfunction normalizeSettingsKey(key: keyof Settings): keyof Settings {\n const normalizedKey = key === 'apiToken' ? 'apiKey' : key\n if (!supportedApiKeys.has(normalizedKey as keyof Settings)) {\n throw new Error(`Invalid settings key: ${normalizedKey}`)\n }\n return normalizedKey as keyof Settings\n}\n\nexport function findSocketYmlSync() {\n let prevDir = null\n let dir = process.cwd()\n while (dir !== prevDir) {\n let ymlPath = path.join(dir, 'socket.yml')\n let yml = safeReadFileSync(ymlPath)\n if (yml === undefined) {\n ymlPath = path.join(dir, 'socket.yaml')\n yml = safeReadFileSync(ymlPath)\n }\n if (typeof yml === 'string') {\n try {\n return {\n path: ymlPath,\n parsed: config.parseSocketConfig(yml)\n }\n } catch {\n throw new Error(`Found file but was unable to parse ${ymlPath}`)\n }\n }\n prevDir = dir\n dir = path.join(dir, '..')\n }\n return null\n}\n\nexport function getSetting<Key extends keyof Settings>(\n key: Key\n): Settings[Key] {\n return getSettings()[normalizeSettingsKey(key) as Key]\n}\n\nexport function updateSetting<Key extends keyof Settings>(\n key: Key,\n value: Settings[Key]\n): void {\n const settings = getSettings()\n settings[normalizeSettingsKey(key) as Key] = value\n if (!pendingSave) {\n pendingSave = true\n process.nextTick(() => {\n pendingSave = false\n const settingsPath = getSettingsPath()\n if (settingsPath) {\n fs.writeFileSync(\n settingsPath,\n Buffer.from(JSON.stringify(settings)).toString('base64')\n )\n }\n })\n }\n}\n","import process from 'node:process'\n\nimport { HttpsProxyAgent } from 'hpagent'\n\nimport isInteractive from '@socketregistry/is-interactive/index.cjs'\nimport { SOCKET_PUBLIC_API_TOKEN } from '@socketsecurity/registry/lib/constants'\nimport { password } from '@socketsecurity/registry/lib/prompts'\nimport { isNonEmptyString } from '@socketsecurity/registry/lib/strings'\nimport { SocketSdk, createUserAgentFromPkgJson } from '@socketsecurity/sdk'\n\nimport { AuthError } from './errors'\nimport { getSetting } from './settings'\nimport constants from '../constants'\n\nconst { SOCKET_CLI_NO_API_TOKEN } = constants\n\n// The API server that should be used for operations.\nfunction getDefaultApiBaseUrl(): string | undefined {\n const baseUrl =\n process.env['SOCKET_SECURITY_API_BASE_URL'] || getSetting('apiBaseUrl')\n return isNonEmptyString(baseUrl) ? baseUrl : undefined\n}\n\n// The API server that should be used for operations.\nfunction getDefaultHttpProxy(): string | undefined {\n const apiProxy =\n process.env['SOCKET_SECURITY_API_PROXY'] || getSetting('apiProxy')\n return isNonEmptyString(apiProxy) ? apiProxy : undefined\n}\n\n// This API key should be stored globally for the duration of the CLI execution.\nlet _defaultToken: string | undefined\nexport function getDefaultToken(): string | undefined {\n // Lazily access constants.ENV[SOCKET_CLI_NO_API_TOKEN].\n if (constants.ENV[SOCKET_CLI_NO_API_TOKEN]) {\n _defaultToken = undefined\n } else {\n const key =\n process.env['SOCKET_SECURITY_API_TOKEN'] ||\n // Keep 'SOCKET_SECURITY_API_KEY' as an alias of 'SOCKET_SECURITY_API_TOKEN'.\n // TODO: Remove 'SOCKET_SECURITY_API_KEY' alias.\n process.env['SOCKET_SECURITY_API_KEY'] ||\n getSetting('apiToken') ||\n _defaultToken\n _defaultToken = isNonEmptyString(key) ? key : undefined\n }\n return _defaultToken\n}\n\nexport function getPublicToken(): string {\n return (\n (process.env['SOCKET_SECURITY_API_TOKEN'] || getDefaultToken()) ??\n SOCKET_PUBLIC_API_TOKEN\n )\n}\n\nexport async function setupSdk(\n apiToken: string | undefined = getDefaultToken(),\n apiBaseUrl: string | undefined = getDefaultApiBaseUrl(),\n proxy: string | undefined = getDefaultHttpProxy()\n): Promise<SocketSdk> {\n if (typeof apiToken !== 'string' && isInteractive()) {\n apiToken = await password({\n message:\n 'Enter your Socket.dev API key (not saved, use socket login to persist)'\n })\n _defaultToken = apiToken\n }\n if (!apiToken) {\n throw new AuthError('You need to provide an API key')\n }\n return new SocketSdk(apiToken, {\n agent: proxy ? new HttpsProxyAgent({ proxy }) : undefined,\n baseUrl: apiBaseUrl,\n userAgent: createUserAgentFromPkgJson({\n // The '@rollup/plugin-replace' will replace \"process.env['INLINED_SOCKET_CLI_NAME']\".\n name: process.env['INLINED_SOCKET_CLI_NAME'] as string,\n // The '@rollup/plugin-replace' will replace \"process.env['INLINED_SOCKET_CLI_VERSION']\".\n version: process.env['INLINED_SOCKET_CLI_VERSION'] as string,\n // The '@rollup/plugin-replace' will replace \"process.env['INLINED_SOCKET_CLI_HOMEPAGE']\".\n homepage: process.env['INLINED_SOCKET_CLI_HOMEPAGE'] as string\n })\n })\n}\n","import type { SafeNode } from '../node'\nimport type {\n Options as ArboristOptions,\n Advisory as BaseAdvisory,\n Arborist as BaseArborist,\n AuditReport as BaseAuditReport,\n Diff as BaseDiff,\n BuildIdealTreeOptions,\n ReifyOptions\n} from '@npmcli/arborist'\n\nexport type ArboristClass = ArboristInstance & {\n new (...args: any): ArboristInstance\n}\n\nexport type ArboristInstance = Omit<\n typeof BaseArborist,\n | 'actualTree'\n | 'auditReport'\n | 'buildIdealTree'\n | 'diff'\n | 'idealTree'\n | 'loadActual'\n | 'loadVirtual'\n | 'reify'\n> & {\n auditReport?: AuditReportInstance | null | undefined\n actualTree?: SafeNode | null | undefined\n diff: Diff | null\n idealTree?: SafeNode | null | undefined\n buildIdealTree(options?: BuildIdealTreeOptions): Promise<SafeNode>\n loadActual(options?: ArboristOptions): Promise<SafeNode>\n loadVirtual(options?: ArboristOptions): Promise<SafeNode>\n reify(options?: ArboristReifyOptions): Promise<SafeNode>\n}\n\nexport type ArboristReifyOptions = ReifyOptions & ArboristOptions\n\nexport type AuditReportInstance = Omit<BaseAuditReport, 'report'> & {\n report: { [dependency: string]: AuditAdvisory[] }\n}\n\nexport type AuditAdvisory = Omit<BaseAdvisory, 'id'> & {\n id: number\n cwe: string[]\n cvss: {\n score: number\n vectorString: string\n }\n vulnerable_versions: string\n}\n\nexport enum DiffAction {\n add = 'ADD',\n change = 'CHANGE',\n remove = 'REMOVE'\n}\n\nexport type Diff = Omit<\n BaseDiff,\n | 'actual'\n | 'children'\n | 'filterSet'\n | 'ideal'\n | 'leaves'\n | 'removed'\n | 'shrinkwrapInflated'\n | 'unchanged'\n> & {\n actual: SafeNode\n children: Diff[]\n filterSet: Set<SafeNode>\n ideal: SafeNode\n leaves: SafeNode[]\n parent: Diff | null\n removed: SafeNode[]\n shrinkwrapInflated: Set<SafeNode>\n unchanged: SafeNode[]\n}\n","import { getArboristDepValidPath } from '../../paths'\n\nimport type { SafeNode } from './node'\n\nexport const depValid: (\n child: SafeNode,\n requested: string,\n accept: string | undefined,\n requester: SafeNode\n) => boolean = require(getArboristDepValidPath())\n","import constants from '../../../constants'\nimport { getNpmRequire } from '../paths'\n\nconst { UNDEFINED_TOKEN } = constants\n\ninterface RequireKnownModules {\n npmlog: typeof import('npmlog')\n // The DefinitelyTyped definition of 'proc-log' does NOT have the log method.\n // The return type of the log method is the same as `typeof import('proc-log')`.\n 'proc-log': typeof import('proc-log')\n}\n\ntype RequireTransformer<T extends keyof RequireKnownModules> = (\n mod: RequireKnownModules[T]\n) => RequireKnownModules[T]\n\nfunction tryRequire<T extends keyof RequireKnownModules>(\n req: NodeJS.Require,\n ...ids: Array<T | [T, RequireTransformer<T>]>\n): RequireKnownModules[T] | undefined {\n for (const data of ids) {\n let id: string | undefined\n let transformer: RequireTransformer<T> | undefined\n if (Array.isArray(data)) {\n id = data[0]\n transformer = data[1] as RequireTransformer<T>\n } else {\n id = data as keyof RequireKnownModules\n transformer = mod => mod\n }\n try {\n // Check that the transformed value isn't `undefined` because older\n // versions of packages like 'proc-log' may not export a `log` method.\n const exported = transformer(req(id))\n if (exported !== undefined) {\n return exported\n }\n } catch {}\n }\n return undefined\n}\n\nexport type Logger =\n | typeof import('npmlog')\n | typeof import('proc-log')\n | undefined\n\nlet _log: Logger | {} | undefined = UNDEFINED_TOKEN\nexport function getLogger(): Logger {\n if (_log === UNDEFINED_TOKEN) {\n _log = tryRequire(\n getNpmRequire(),\n [\n 'proc-log/lib/index.js' as 'proc-log',\n // The proc-log DefinitelyTyped definition is incorrect. The type definition\n // is really that of its export log.\n mod => (mod as any).log as RequireKnownModules['proc-log']\n ],\n 'npmlog/lib/log.js' as 'npmlog'\n )\n }\n return _log as Logger | undefined\n}\n","import npa from 'npm-package-arg'\nimport semver from 'semver'\n\nimport { getArboristOverrideSetClassPath } from '../../paths'\nimport { getLogger } from '../../proc-log'\n\nimport type { SafeEdge } from './edge'\nimport type { SafeNode } from './node'\nimport type { AliasResult, RegistryResult } from 'npm-package-arg'\n\ninterface OverrideSetClass {\n children: Map<string, SafeOverrideSet>\n key: string | undefined\n keySpec: string | undefined\n name: string | undefined\n parent: SafeOverrideSet | undefined\n value: string | undefined\n version: string | undefined\n // eslint-disable-next-line @typescript-eslint/no-misused-new\n new (...args: any[]): OverrideSetClass\n get isRoot(): boolean\n get ruleset(): Map<string, SafeOverrideSet>\n ancestry(): Generator<SafeOverrideSet>\n childrenAreEqual(otherOverrideSet: SafeOverrideSet | undefined): boolean\n getEdgeRule(edge: SafeEdge): SafeOverrideSet\n getNodeRule(node: SafeNode): SafeOverrideSet\n getMatchingRule(node: SafeNode): SafeOverrideSet | null\n isEqual(otherOverrideSet: SafeOverrideSet | undefined): boolean\n}\n\nconst OverrideSet: OverrideSetClass = require(getArboristOverrideSetClassPath())\n\n// Implementation code not related to patch https://github.com/npm/cli/pull/8089\n// is based on https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/override-set.js:\nexport class SafeOverrideSet extends OverrideSet {\n // Patch adding doOverrideSetsConflict is based on\n // https://github.com/npm/cli/pull/8089.\n static doOverrideSetsConflict(\n first: SafeOverrideSet | undefined,\n second: SafeOverrideSet | undefined\n ) {\n // If override sets contain one another then we can try to use the more\n // specific one. If neither one is more specific, then we consider them to\n // be in conflict.\n return this.findSpecificOverrideSet(first, second) === undefined\n }\n\n // Patch adding findSpecificOverrideSet is based on\n // https://github.com/npm/cli/pull/8089.\n static findSpecificOverrideSet(\n first: SafeOverrideSet | undefined,\n second: SafeOverrideSet | undefined\n ) {\n for (\n let overrideSet = second;\n overrideSet;\n overrideSet = overrideSet.parent\n ) {\n if (overrideSet.isEqual(first)) {\n return second\n }\n }\n for (\n let overrideSet = first;\n overrideSet;\n overrideSet = overrideSet.parent\n ) {\n if (overrideSet.isEqual(second)) {\n return first\n }\n }\n // The override sets are incomparable. Neither one contains the other.\n const log = getLogger()\n log?.silly('Conflicting override sets', first, second)\n return undefined\n }\n\n // Patch adding childrenAreEqual is based on\n // https://github.com/npm/cli/pull/8089.\n override childrenAreEqual(otherOverrideSet: SafeOverrideSet) {\n if (this.children.size !== otherOverrideSet.children.size) {\n return false\n }\n for (const { 0: key, 1: childOverrideSet } of this.children) {\n const otherChildOverrideSet = otherOverrideSet.children.get(key)\n if (!otherChildOverrideSet) {\n return false\n }\n if (childOverrideSet.value !== otherChildOverrideSet.value) {\n return false\n }\n if (!childOverrideSet.childrenAreEqual(otherChildOverrideSet)) {\n return false\n }\n }\n return true\n }\n\n override getEdgeRule(edge: SafeEdge): SafeOverrideSet {\n for (const rule of this.ruleset.values()) {\n if (rule.name !== edge.name) {\n continue\n }\n // If keySpec is * we found our override.\n if (rule.keySpec === '*') {\n return rule\n }\n // Patch replacing\n // let spec = npa(`${edge.name}@${edge.spec}`)\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // We need to use the rawSpec here, because the spec has the overrides\n // applied to it already. The rawSpec can be undefined, so we need to use\n // the fallback value of spec if it is.\n let spec = npa(`${edge.name}@${edge.rawSpec || edge.spec}`)\n if (spec.type === 'alias') {\n spec = (spec as AliasResult).subSpec\n }\n if (spec.type === 'git') {\n if (spec.gitRange && semver.intersects(spec.gitRange, rule.keySpec!)) {\n return rule\n }\n continue\n }\n if (spec.type === 'range' || spec.type === 'version') {\n if (\n semver.intersects((spec as RegistryResult).fetchSpec, rule.keySpec!)\n ) {\n return rule\n }\n continue\n }\n // If we got this far, the spec type is one of tag, directory or file\n // which means we have no real way to make version comparisons, so we\n // just accept the override.\n return rule\n }\n return this\n }\n\n // Patch adding isEqual is based on\n // https://github.com/npm/cli/pull/8089.\n override isEqual(otherOverrideSet: SafeOverrideSet | undefined): boolean {\n if (this === otherOverrideSet) {\n return true\n }\n if (!otherOverrideSet) {\n return false\n }\n if (\n this.key !== otherOverrideSet.key ||\n this.value !== otherOverrideSet.value\n ) {\n return false\n }\n if (!this.childrenAreEqual(otherOverrideSet)) {\n return false\n }\n if (!this.parent) {\n return !otherOverrideSet.parent\n }\n return this.parent.isEqual(otherOverrideSet.parent)\n }\n}\n","import semver from 'semver'\n\nimport { SafeOverrideSet } from './override-set'\nimport { getArboristNodeClassPath } from '../../paths'\nimport { getLogger } from '../../proc-log'\n\nimport type { SafeEdge } from './edge'\nimport type { Node as BaseNode, Link } from '@npmcli/arborist'\n\ntype NodeClass = Omit<\n BaseNode,\n | 'addEdgeIn'\n | 'addEdgeOut'\n | 'canDedupe'\n | 'canReplace'\n | 'canReplaceWith'\n | 'children'\n | 'deleteEdgeIn'\n | 'edgesIn'\n | 'edgesOut'\n | 'from'\n | 'hasShrinkwrap'\n | 'inDepBundle'\n | 'inShrinkwrap'\n | 'integrity'\n | 'isTop'\n | 'matches'\n | 'meta'\n | 'name'\n | 'overrides'\n | 'packageName'\n | 'parent'\n | 'recalculateOutEdgesOverrides'\n | 'resolve'\n | 'resolveParent'\n | 'root'\n | 'updateOverridesEdgeInAdded'\n | 'updateOverridesEdgeInRemoved'\n | 'version'\n | 'versions'\n> & {\n name: string\n version: string\n children: Map<string, SafeNode | Link>\n edgesIn: Set<SafeEdge>\n edgesOut: Map<string, SafeEdge>\n from: SafeNode | null\n hasShrinkwrap: boolean\n inShrinkwrap: boolean | undefined\n integrity?: string | null\n isTop: boolean | undefined\n meta: BaseNode['meta'] & {\n addEdge(edge: SafeEdge): void\n }\n overrides: SafeOverrideSet | undefined\n versions: string[]\n get inDepBundle(): boolean\n get packageName(): string | null\n get parent(): SafeNode | null\n set parent(value: SafeNode | null)\n get resolveParent(): SafeNode | null\n get root(): SafeNode | null\n set root(value: SafeNode | null)\n new (...args: any): NodeClass\n addEdgeIn(edge: SafeEdge): void\n addEdgeOut(edge: SafeEdge): void\n canDedupe(preferDedupe?: boolean): boolean\n canReplace(node: SafeNode, ignorePeers?: string[]): boolean\n canReplaceWith(node: SafeNode, ignorePeers?: string[]): boolean\n deleteEdgeIn(edge: SafeEdge): void\n matches(node: SafeNode): boolean\n recalculateOutEdgesOverrides(): void\n resolve(name: string): SafeNode\n updateOverridesEdgeInAdded(\n otherOverrideSet: SafeOverrideSet | undefined\n ): boolean\n updateOverridesEdgeInRemoved(otherOverrideSet: SafeOverrideSet): boolean\n}\n\nconst Node: NodeClass = require(getArboristNodeClassPath())\n\n// Implementation code not related to patch https://github.com/npm/cli/pull/8089\n// is based on https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/node.js:\nexport class SafeNode extends Node {\n // Return true if it's safe to remove this node, because anything that is\n // depending on it would be fine with the thing that they would resolve to if\n // it was removed, or nothing is depending on it in the first place.\n override canDedupe(preferDedupe = false) {\n // Not allowed to mess with shrinkwraps or bundles.\n if (this.inDepBundle || this.inShrinkwrap) {\n return false\n }\n // It's a top level pkg, or a dep of one.\n if (!this.resolveParent?.resolveParent) {\n return false\n }\n // No one wants it, remove it.\n if (this.edgesIn.size === 0) {\n return true\n }\n const other = this.resolveParent.resolveParent.resolve(this.name)\n // Nothing else, need this one.\n if (!other) {\n return false\n }\n // If it's the same thing, then always fine to remove.\n if (other.matches(this)) {\n return true\n }\n // If the other thing can't replace this, then skip it.\n if (!other.canReplace(this)) {\n return false\n }\n // Patch replacing\n // if (preferDedupe || semver.gte(other.version, this.version)) {\n // return true\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // If we prefer dedupe, or if the version is equal, take the other.\n if (preferDedupe || semver.eq(other.version, this.version)) {\n return true\n }\n // If our current version isn't the result of an override, then prefer to\n // take the greater version.\n if (!this.overridden && semver.gt(other.version, this.version)) {\n return true\n }\n return false\n }\n\n // Is it safe to replace one node with another? check the edges to\n // make sure no one will get upset. Note that the node might end up\n // having its own unmet dependencies, if the new node has new deps.\n // Note that there are cases where Arborist will opt to insert a node\n // into the tree even though this function returns false! This is\n // necessary when a root dependency is added or updated, or when a\n // root dependency brings peer deps along with it. In that case, we\n // will go ahead and create the invalid state, and then try to resolve\n // it with more tree construction, because it's a user request.\n override canReplaceWith(node: SafeNode, ignorePeers?: string[]): boolean {\n if (this.name !== node.name || this.packageName !== node.packageName) {\n return false\n }\n // Patch replacing\n // if (node.overrides !== this.overrides) {\n // return false\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // If this node has no dependencies, then it's irrelevant to check the\n // override rules of the replacement node.\n if (this.edgesOut.size) {\n // XXX need to check for two root nodes?\n if (node.overrides) {\n if (!node.overrides.isEqual(this.overrides)) {\n return false\n }\n } else {\n if (this.overrides) {\n return false\n }\n }\n }\n // To satisfy the patch we ensure `node.overrides === this.overrides`\n // so that the condition we want to replace,\n // if (this.overrides !== node.overrides) {\n // , is not hit.`\n const oldOverrideSet = this.overrides\n let result = true\n if (oldOverrideSet !== node.overrides) {\n this.overrides = node.overrides\n }\n try {\n result = super.canReplaceWith(node, ignorePeers)\n this.overrides = oldOverrideSet\n } catch (e) {\n this.overrides = oldOverrideSet\n throw e\n }\n return result\n }\n\n // Patch adding deleteEdgeIn is based on https://github.com/npm/cli/pull/8089.\n override deleteEdgeIn(edge: SafeEdge) {\n this.edgesIn.delete(edge)\n const { overrides } = edge\n if (overrides) {\n this.updateOverridesEdgeInRemoved(overrides)\n }\n }\n\n override addEdgeIn(edge: SafeEdge): void {\n // Patch replacing\n // if (edge.overrides) {\n // this.overrides = edge.overrides\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // We need to handle the case where the new edge in has an overrides field\n // which is different from the current value.\n if (!this.overrides || !this.overrides.isEqual(edge.overrides)) {\n this.updateOverridesEdgeInAdded(edge.overrides)\n }\n this.edgesIn.add(edge)\n // Try to get metadata from the yarn.lock file.\n this.root.meta?.addEdge(edge)\n }\n\n // @ts-ignore: Incorrectly typed as a property instead of an accessor.\n override get overridden() {\n // Patch replacing\n // return !!(this.overrides && this.overrides.value && this.overrides.name === this.name)\n // is based on https://github.com/npm/cli/pull/8089.\n if (\n !this.overrides ||\n !this.overrides.value ||\n this.overrides.name !== this.name\n ) {\n return false\n }\n // The overrides rule is for a package with this name, but some override\n // rules only apply to specific versions. To make sure this package was\n // actually overridden, we check whether any edge going in had the rule\n // applied to it, in which case its overrides set is different than its\n // source node.\n for (const edge of this.edgesIn) {\n if (\n edge.overrides &&\n edge.overrides.name === this.name &&\n edge.overrides.value === this.version\n ) {\n if (!edge.overrides.isEqual(edge.from?.overrides)) {\n return true\n }\n }\n }\n return false\n }\n\n override set parent(newParent: SafeNode) {\n // Patch removing\n // if (parent.overrides) {\n // this.overrides = parent.overrides.getNodeRule(this)\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // The \"parent\" setter is a really large and complex function. To satisfy\n // the patch we hold on to the old overrides value and set `this.overrides`\n // to `undefined` so that the condition we want to remove is not hit.\n const { overrides } = this\n if (overrides) {\n this.overrides = undefined\n }\n try {\n super.parent = newParent\n this.overrides = overrides\n } catch (e) {\n this.overrides = overrides\n throw e\n }\n }\n\n // Patch adding recalculateOutEdgesOverrides is based on\n // https://github.com/npm/cli/pull/8089.\n override recalculateOutEdgesOverrides() {\n // For each edge out propagate the new overrides through.\n for (const edge of this.edgesOut.values()) {\n edge.reload(true)\n if (edge.to) {\n edge.to.updateOverridesEdgeInAdded(edge.overrides)\n }\n }\n }\n\n // @ts-ignore: Incorrectly typed to accept null.\n override set root(newRoot: SafeNode) {\n // Patch removing\n // if (!this.overrides && this.parent && this.parent.overrides) {\n // this.overrides = this.parent.overrides.getNodeRule(this)\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // The \"root\" setter is a really large and complex function. To satisfy the\n // patch we add a dummy value to `this.overrides` so that the condition we\n // want to remove is not hit.\n if (!this.overrides) {\n this.overrides = new SafeOverrideSet({ overrides: '' })\n }\n try {\n super.root = newRoot\n this.overrides = undefined\n } catch (e) {\n this.overrides = undefined\n throw e\n }\n }\n\n // Patch adding updateOverridesEdgeInAdded is based on\n // https://github.com/npm/cli/pull/7025.\n //\n // This logic isn't perfect either. When we have two edges in that have\n // different override sets, then we have to decide which set is correct. This\n // function assumes the more specific override set is applicable, so if we have\n // dependencies A->B->C and A->C and an override set that specifies what happens\n // for C under A->B, this will work even if the new A->C edge comes along and\n // tries to change the override set. The strictly correct logic is not to allow\n // two edges with different overrides to point to the same node, because even\n // if this node can satisfy both, one of its dependencies might need to be\n // different depending on the edge leading to it. However, this might cause a\n // lot of duplication, because the conflict in the dependencies might never\n // actually happen.\n override updateOverridesEdgeInAdded(\n otherOverrideSet: SafeOverrideSet | undefined\n ) {\n if (!otherOverrideSet) {\n // Assuming there are any overrides at all, the overrides field is never\n // undefined for any node at the end state of the tree. So if the new edge's\n // overrides is undefined it will be updated later. So we can wait with\n // updating the node's overrides field.\n return false\n }\n if (!this.overrides) {\n this.overrides = otherOverrideSet\n this.recalculateOutEdgesOverrides()\n return true\n }\n if (this.overrides.isEqual(otherOverrideSet)) {\n return false\n }\n const newOverrideSet = SafeOverrideSet.findSpecificOverrideSet(\n this.overrides,\n otherOverrideSet\n )\n if (newOverrideSet) {\n if (this.overrides.isEqual(newOverrideSet)) {\n return false\n }\n this.overrides = newOverrideSet\n this.recalculateOutEdgesOverrides()\n return true\n }\n // This is an error condition. We can only get here if the new override set\n // is in conflict with the existing.\n const log = getLogger()\n log?.silly('Conflicting override sets', this.name)\n return false\n }\n\n // Patch adding updateOverridesEdgeInRemoved is based on\n // https://github.com/npm/cli/pull/7025.\n override updateOverridesEdgeInRemoved(otherOverrideSet: SafeOverrideSet) {\n // If this edge's overrides isn't equal to this node's overrides,\n // then removing it won't change newOverrideSet later.\n if (!this.overrides || !this.overrides.isEqual(otherOverrideSet)) {\n return false\n }\n let newOverrideSet\n for (const edge of this.edgesIn) {\n const { overrides: edgeOverrides } = edge\n if (newOverrideSet && edgeOverrides) {\n newOverrideSet = SafeOverrideSet.findSpecificOverrideSet(\n edgeOverrides,\n newOverrideSet\n )\n } else {\n newOverrideSet = edgeOverrides\n }\n }\n if (this.overrides.isEqual(newOverrideSet)) {\n return false\n }\n this.overrides = newOverrideSet\n if (newOverrideSet) {\n // Optimization: If there's any override set at all, then no non-extraneous\n // node has an empty override set. So if we temporarily have no override set\n // (for example, we removed all the edges in), there's no use updating all\n // the edges out right now. Let's just wait until we have an actual override\n // set later.\n this.recalculateOutEdgesOverrides()\n }\n return true\n }\n}\n","import { depValid } from './dep-valid'\nimport { SafeNode } from './node'\nimport { SafeOverrideSet } from './override-set'\nimport { getArboristEdgeClassPath } from '../../paths'\n\nimport type { Edge as BaseEdge, DependencyProblem } from '@npmcli/arborist'\n\ntype EdgeClass = Omit<\n BaseEdge,\n | 'accept'\n | 'detach'\n | 'optional'\n | 'overrides'\n | 'peer'\n | 'peerConflicted'\n | 'rawSpec'\n | 'reload'\n | 'satisfiedBy'\n | 'spec'\n | 'to'\n> & {\n optional: boolean\n overrides: SafeOverrideSet | undefined\n peer: boolean\n peerConflicted: boolean\n rawSpec: string\n get accept(): string | undefined\n get spec(): string\n get to(): SafeNode | null\n new (...args: any): EdgeClass\n detach(): void\n reload(hard?: boolean): void\n satisfiedBy(node: SafeNode): boolean\n}\n\nexport type EdgeOptions = {\n type: string\n name: string\n spec: string\n from: SafeNode\n accept?: string | undefined\n overrides?: SafeOverrideSet | undefined\n to?: SafeNode | undefined\n}\n\nexport type ErrorStatus = DependencyProblem | 'OK'\n\nexport type Explanation = {\n type: string\n name: string\n spec: string\n bundled: boolean\n overridden: boolean\n error: ErrorStatus | undefined\n rawSpec: string | undefined\n from: object | undefined\n} | null\n\nexport const Edge: EdgeClass = require(getArboristEdgeClassPath())\n\n// The Edge class makes heavy use of private properties which subclasses do NOT\n// have access to. So we have to recreate any functionality that relies on those\n// private properties and use our own \"safe\" prefixed non-conflicting private\n// properties. Implementation code not related to patch https://github.com/npm/cli/pull/8089\n// is based on https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/edge.js.\n//\n// The npm application\n// Copyright (c) npm, Inc. and Contributors\n// Licensed on the terms of The Artistic License 2.0\n//\n// An edge in the dependency graph.\n// Represents a dependency relationship of some kind.\nexport class SafeEdge extends Edge {\n #safeError: ErrorStatus | null\n #safeExplanation: Explanation | undefined\n #safeFrom: SafeNode | null\n #safeTo: SafeNode | null\n\n constructor(options: EdgeOptions) {\n const { from } = options\n // Defer to supper to validate options and assign non-private values.\n super(options)\n if (from.constructor !== SafeNode) {\n Reflect.setPrototypeOf(from, SafeNode.prototype)\n }\n this.#safeError = null\n this.#safeExplanation = null\n this.#safeFrom = from\n this.#safeTo = null\n this.reload(true)\n }\n\n override get bundled() {\n return !!this.#safeFrom?.package?.bundleDependencies?.includes(this.name)\n }\n\n override get error() {\n if (!this.#safeError) {\n if (!this.#safeTo) {\n if (this.optional) {\n this.#safeError = null\n } else {\n this.#safeError = 'MISSING'\n }\n } else if (\n this.peer &&\n this.#safeFrom === this.#safeTo.parent &&\n // Patch adding \"?.\" use based on\n // https://github.com/npm/cli/pull/8089.\n !this.#safeFrom?.isTop\n ) {\n this.#safeError = 'PEER LOCAL'\n } else if (!this.satisfiedBy(this.#safeTo)) {\n this.#safeError = 'INVALID'\n }\n // Patch adding \"else if\" condition is based on\n // https://github.com/npm/cli/pull/8089.\n else if (\n this.overrides &&\n this.#safeTo.edgesOut.size &&\n SafeOverrideSet.doOverrideSetsConflict(\n this.overrides,\n this.#safeTo.overrides\n )\n ) {\n // Any inconsistency between the edge's override set and the target's\n // override set is potentially problematic. But we only say the edge is\n // in error if the override sets are plainly conflicting. Note that if\n // the target doesn't have any dependencies of their own, then this\n // inconsistency is irrelevant.\n this.#safeError = 'INVALID'\n } else {\n this.#safeError = 'OK'\n }\n }\n if (this.#safeError === 'OK') {\n return null\n }\n return this.#safeError\n }\n\n // @ts-ignore: Incorrectly typed as a property instead of an accessor.\n override get from() {\n return this.#safeFrom\n }\n\n // @ts-ignore: Incorrectly typed as a property instead of an accessor.\n override get spec(): string {\n if (\n this.overrides?.value &&\n this.overrides.value !== '*' &&\n this.overrides.name === this.name\n ) {\n if (this.overrides.value.startsWith('$')) {\n const ref = this.overrides.value.slice(1)\n // We may be a virtual root, if we are we want to resolve reference\n // overrides from the real root, not the virtual one.\n //\n // Patch adding \"?.\" use based on\n // https://github.com/npm/cli/pull/8089.\n const pkg = this.#safeFrom?.sourceReference\n ? this.#safeFrom?.sourceReference.root.package\n : this.#safeFrom?.root?.package\n if (pkg?.devDependencies?.[ref]) {\n return pkg.devDependencies[ref] as string\n }\n if (pkg?.optionalDependencies?.[ref]) {\n return pkg.optionalDependencies[ref] as string\n }\n if (pkg?.dependencies?.[ref]) {\n return pkg.dependencies[ref] as string\n }\n if (pkg?.peerDependencies?.[ref]) {\n return pkg.peerDependencies[ref] as string\n }\n throw new Error(`Unable to resolve reference ${this.overrides.value}`)\n }\n return this.overrides.value\n }\n return this.rawSpec\n }\n\n // @ts-ignore: Incorrectly typed as a property instead of an accessor.\n override get to() {\n return this.#safeTo\n }\n\n override detach() {\n this.#safeExplanation = null\n // Patch replacing\n // if (this.#to) {\n // this.#to.edgesIn.delete(this)\n // }\n // this.#from.edgesOut.delete(this.#name)\n // is based on https://github.com/npm/cli/pull/8089.\n this.#safeTo?.deleteEdgeIn(this)\n this.#safeFrom?.edgesOut.delete(this.name)\n this.#safeTo = null\n this.#safeError = 'DETACHED'\n this.#safeFrom = null\n }\n\n // Return the edge data, and an explanation of how that edge came to be here.\n // @ts-ignore: Edge#explain is defined with an unused `seen = []` param.\n override explain() {\n if (!this.#safeExplanation) {\n const explanation: Explanation = {\n type: this.type,\n name: this.name,\n spec: this.spec,\n bundled: false,\n overridden: false,\n error: undefined,\n from: undefined,\n rawSpec: undefined\n }\n if (this.rawSpec !== this.spec) {\n explanation.rawSpec = this.rawSpec\n explanation.overridden = true\n }\n if (this.bundled) {\n explanation.bundled = this.bundled\n }\n if (this.error) {\n explanation.error = this.error\n }\n if (this.#safeFrom) {\n explanation.from = this.#safeFrom.explain()\n }\n this.#safeExplanation = explanation\n }\n return this.#safeExplanation\n }\n\n override reload(hard = false) {\n this.#safeExplanation = null\n // Patch replacing\n // if (this.#from.overrides) {\n // is based on https://github.com/npm/cli/pull/8089.\n let needToUpdateOverrideSet = false\n let newOverrideSet\n let oldOverrideSet\n if (this.#safeFrom?.overrides) {\n newOverrideSet = this.#safeFrom.overrides.getEdgeRule(this)\n if (newOverrideSet && !newOverrideSet.isEqual(this.overrides)) {\n // If there's a new different override set we need to propagate it to\n // the nodes. If we're deleting the override set then there's no point\n // propagating it right now since it will be filled with another value\n // later.\n needToUpdateOverrideSet = true\n oldOverrideSet = this.overrides\n this.overrides = newOverrideSet\n }\n } else {\n this.overrides = undefined\n }\n // Patch adding \"?.\" use based on\n // https://github.com/npm/cli/pull/8089.\n const newTo = this.#safeFrom?.resolve(this.name)\n if (newTo !== this.#safeTo) {\n // Patch replacing\n // this.#to.edgesIn.delete(this)\n // is based on https://github.com/npm/cli/pull/8089.\n this.#safeTo?.deleteEdgeIn(this)\n this.#safeTo = (newTo as SafeNode) ?? null\n this.#safeError = null\n this.#safeTo?.addEdgeIn(this)\n } else if (hard) {\n this.#safeError = null\n }\n // Patch adding \"else if\" condition based on\n // https://github.com/npm/cli/pull/8089.\n else if (needToUpdateOverrideSet && this.#safeTo) {\n // Propagate the new override set to the target node.\n this.#safeTo.updateOverridesEdgeInRemoved(oldOverrideSet!)\n this.#safeTo.updateOverridesEdgeInAdded(newOverrideSet)\n }\n }\n\n override satisfiedBy(node: SafeNode) {\n // Patch replacing\n // if (node.name !== this.#name) {\n // return false\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n if (node.name !== this.name || !this.#safeFrom) {\n return false\n }\n // NOTE: this condition means we explicitly do not support overriding\n // bundled or shrinkwrapped dependencies\n if (node.hasShrinkwrap || node.inShrinkwrap || node.inBundle) {\n return depValid(node, this.rawSpec, this.accept, this.#safeFrom)\n }\n // Patch replacing\n // return depValid(node, this.spec, this.#accept, this.#from)\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // If there's no override we just use the spec.\n if (!this.overrides?.keySpec) {\n return depValid(node, this.spec, this.accept, this.#safeFrom)\n }\n // There's some override. If the target node satisfies the overriding spec\n // then it's okay.\n if (depValid(node, this.spec, this.accept, this.#safeFrom)) {\n return true\n }\n // If it doesn't, then it should at least satisfy the original spec.\n if (!depValid(node, this.rawSpec, this.accept, this.#safeFrom)) {\n return false\n }\n // It satisfies the original spec, not the overriding spec. We need to make\n // sure it doesn't use the overridden spec.\n // For example:\n // we might have an ^8.0.0 rawSpec, and an override that makes\n // keySpec=8.23.0 and the override value spec=9.0.0.\n // If the node is 9.0.0, then it's okay because it's consistent with spec.\n // If the node is 8.24.0, then it's okay because it's consistent with the rawSpec.\n // If the node is 8.23.0, then it's not okay because even though it's consistent\n // with the rawSpec, it's also consistent with the keySpec.\n // So we're looking for ^8.0.0 or 9.0.0 and not 8.23.0.\n return !depValid(node, this.overrides.keySpec, this.accept, this.#safeFrom)\n }\n}\n","import constants from '../../constants'\n\nimport type { Remap } from '@socketsecurity/registry/lib/objects'\nimport type { components } from '@socketsecurity/sdk/types/api'\n\nexport type ArtifactAlertCve = Remap<\n Omit<CompactSocketArtifactAlert, 'type'> & {\n type: CveAlertType\n }\n>\n\nexport type ArtifactAlertCveFixable = Remap<\n Omit<CompactSocketArtifactAlert, 'props' | 'type'> & {\n type: CveAlertType\n props: {\n firstPatchedVersionIdentifier: string\n vulnerableVersionRange: string\n [key: string]: any\n }\n }\n>\n\nexport type ArtifactAlertUpgrade = Remap<\n Omit<CompactSocketArtifactAlert, 'type'> & {\n type: 'socketUpgradeAvailable'\n }\n>\n\nexport type CveAlertType = 'cve' | 'mediumCVE' | 'mildCVE' | 'criticalCVE'\n\nexport type CompactSocketArtifactAlert = Remap<\n Omit<\n SocketArtifactAlert,\n 'action' | 'actionPolicyIndex' | 'category' | 'end' | 'file' | 'start'\n >\n>\n\nexport type CompactSocketArtifact = Remap<\n Omit<SocketArtifact, 'alerts' | 'batchIndex' | 'size'> & {\n alerts: CompactSocketArtifactAlert[]\n }\n>\n\nexport type SocketArtifact = components['schemas']['SocketArtifact']\n\nexport type SocketArtifactAlert = Remap<\n Omit<components['schemas']['SocketAlert'], 'props'> & {\n props?: any | undefined\n }\n>\n\nconst {\n ALERT_TYPE_CRITICAL_CVE,\n ALERT_TYPE_CVE,\n ALERT_TYPE_MEDIUM_CVE,\n ALERT_TYPE_MILD_CVE\n} = constants\n\nexport function isArtifactAlertCve(\n alert: CompactSocketArtifactAlert\n): alert is ArtifactAlertCve {\n const { type } = alert\n return (\n type === ALERT_TYPE_CVE ||\n type === ALERT_TYPE_MEDIUM_CVE ||\n type === ALERT_TYPE_MILD_CVE ||\n type === ALERT_TYPE_CRITICAL_CVE\n )\n}\n","import { isObject } from '@socketsecurity/registry/lib/objects'\n\nimport { isErrnoException } from '../errors'\nimport { getPublicToken, setupSdk } from '../sdk'\nimport { findSocketYmlSync, getSetting } from '../settings'\n\nimport type { SocketSdkResultType } from '@socketsecurity/sdk'\n\ntype AlertUxLookup = ReturnType<typeof createAlertUXLookup>\n\ntype AlertUxLookupSettings = Parameters<AlertUxLookup>[0]\n\ntype AlertUxLookupResult = ReturnType<AlertUxLookup>\n\ntype NonNormalizedRule =\n | NonNullable<\n NonNullable<\n NonNullable<\n (SocketSdkResultType<'postSettings'> & {\n success: true\n })['data']['entries'][number]['settings'][string]\n >['issueRules']\n >\n >[string]\n | boolean\n\ntype NonNormalizedResolvedRule =\n | (NonNullable<\n NonNullable<\n (SocketSdkResultType<'postSettings'> & {\n success: true\n })['data']['defaults']['issueRules']\n >[string]\n > & { action: string })\n | boolean\n\ntype RuleActionUX = { block: boolean; display: boolean }\n\nconst ERROR_UX: RuleActionUX = {\n block: true,\n display: true\n}\n\nconst IGNORE_UX: RuleActionUX = {\n block: false,\n display: false\n}\n\nconst WARN_UX: RuleActionUX = {\n block: false,\n display: true\n}\n\n// Iterates over all entries with ordered issue rule for deferral. Iterates over\n// all issue rules and finds the first defined value that does not defer otherwise\n// uses the defaultValue. Takes the value and converts into a UX workflow.\nfunction resolveAlertRuleUX(\n orderedRulesCollection: Iterable<Iterable<NonNormalizedRule>>,\n defaultValue: NonNormalizedResolvedRule\n): RuleActionUX {\n if (\n defaultValue === true ||\n defaultValue === null ||\n defaultValue === undefined\n ) {\n defaultValue = { action: 'error' }\n } else if (defaultValue === false) {\n defaultValue = { action: 'ignore' }\n }\n let block = false\n let display = false\n let needDefault = true\n iterate_entries: for (const rules of orderedRulesCollection) {\n for (const rule of rules) {\n if (ruleValueDoesNotDefer(rule)) {\n needDefault = false\n const narrowingFilter = uxForDefinedNonDeferValue(rule)\n block = block || narrowingFilter.block\n display = display || narrowingFilter.display\n continue iterate_entries\n }\n }\n const narrowingFilter = uxForDefinedNonDeferValue(defaultValue)\n block = block || narrowingFilter.block\n display = display || narrowingFilter.display\n }\n if (needDefault) {\n const narrowingFilter = uxForDefinedNonDeferValue(defaultValue)\n block = block || narrowingFilter.block\n display = display || narrowingFilter.display\n }\n return { block, display }\n}\n\n// Negative form because it is narrowing the type.\nfunction ruleValueDoesNotDefer(\n rule: NonNormalizedRule\n): rule is NonNormalizedResolvedRule {\n if (rule === undefined) {\n return false\n }\n if (isObject(rule)) {\n const { action } = rule\n if (action === undefined || action === 'defer') {\n return false\n }\n }\n return true\n}\n\n// Handles booleans for backwards compatibility.\nfunction uxForDefinedNonDeferValue(\n ruleValue: NonNormalizedResolvedRule\n): RuleActionUX {\n if (typeof ruleValue === 'boolean') {\n return ruleValue ? ERROR_UX : IGNORE_UX\n }\n const { action } = ruleValue\n if (action === 'warn') {\n return WARN_UX\n } else if (action === 'ignore') {\n return IGNORE_UX\n }\n return ERROR_UX\n}\n\ntype SettingsType = (SocketSdkResultType<'postSettings'> & {\n success: true\n})['data']\n\nexport function createAlertUXLookup(settings: SettingsType): (context: {\n package: { name: string; version: string }\n alert: { type: string }\n}) => RuleActionUX {\n const cachedUX: Map<keyof typeof settings.defaults.issueRules, RuleActionUX> =\n new Map()\n return context => {\n const { type } = context.alert\n let ux = cachedUX.get(type)\n if (ux) {\n return ux\n }\n const orderedRulesCollection: NonNormalizedRule[][] = []\n for (const settingsEntry of settings.entries) {\n const orderedRules: NonNormalizedRule[] = []\n let target = settingsEntry.start\n while (target !== null) {\n const resolvedTarget = settingsEntry.settings[target]\n if (!resolvedTarget) {\n break\n }\n const issueRuleValue = resolvedTarget.issueRules?.[type]\n if (typeof issueRuleValue !== 'undefined') {\n orderedRules.push(issueRuleValue)\n }\n target = resolvedTarget.deferTo ?? null\n }\n orderedRulesCollection.push(orderedRules)\n }\n const defaultValue = settings.defaults.issueRules[type] as\n | { action: 'error' | 'ignore' | 'warn' }\n | boolean\n | undefined\n let resolvedDefaultValue: NonNormalizedResolvedRule = {\n action: 'error'\n }\n if (defaultValue === false) {\n resolvedDefaultValue = { action: 'ignore' }\n } else if (defaultValue && defaultValue !== true) {\n resolvedDefaultValue = { action: defaultValue.action ?? 'error' }\n }\n ux = resolveAlertRuleUX(orderedRulesCollection, resolvedDefaultValue)\n cachedUX.set(type, ux)\n return ux\n }\n}\n\nlet _uxLookup: AlertUxLookup | undefined\nexport async function uxLookup(\n settings: AlertUxLookupSettings\n): Promise<AlertUxLookupResult> {\n if (_uxLookup === undefined) {\n const { orgs, settings } = await (async () => {\n try {\n const sockSdk = await setupSdk(getPublicToken())\n const orgResult = await sockSdk.getOrganizations()\n if (!orgResult.success) {\n throw new Error(\n `Failed to fetch Socket organization info: ${orgResult.error.message}`\n )\n }\n const orgs: Array<\n Exclude<(typeof orgResult.data.organizations)[string], undefined>\n > = []\n for (const org of Object.values(orgResult.data.organizations)) {\n if (org) {\n orgs.push(org)\n }\n }\n const result = await sockSdk.postSettings(\n orgs.map(org => ({ organization: org.id }))\n )\n if (!result.success) {\n throw new Error(\n `Failed to fetch API key settings: ${result.error.message}`\n )\n }\n return {\n orgs,\n settings: result.data\n }\n } catch (e) {\n const cause = isObject(e) && 'cause' in e ? e['cause'] : undefined\n if (\n isErrnoException(cause) &&\n (cause.code === 'ENOTFOUND' || cause.code === 'ECONNREFUSED')\n ) {\n throw new Error(\n 'Unable to connect to socket.dev, ensure internet connectivity before retrying',\n {\n cause: e\n }\n )\n }\n throw e\n }\n })()\n // Remove any organizations not being enforced.\n const enforcedOrgs = getSetting('enforcedOrgs') ?? []\n for (const { 0: i, 1: org } of orgs.entries()) {\n if (!enforcedOrgs.includes(org.id)) {\n settings.entries.splice(i, 1)\n }\n }\n const socketYml = findSocketYmlSync()\n if (socketYml) {\n settings.entries.push({\n start: socketYml.path,\n settings: {\n [socketYml.path]: {\n deferTo: null,\n // TODO: TypeScript complains about the type not matching. We should\n // figure out why are providing\n // issueRules: { [issueName: string]: boolean }\n // but expecting\n // issueRules: { [issueName: string]: { action: 'defer' | 'error' | 'ignore' | 'monitor' | 'warn' } }\n issueRules: socketYml.parsed.issueRules as unknown as {\n [key: string]: {\n action: 'defer' | 'error' | 'ignore' | 'monitor' | 'warn'\n }\n }\n }\n }\n })\n }\n _uxLookup = createAlertUXLookup(settings)\n }\n return _uxLookup(settings)\n}\n","export function pick<T extends Record<string, any>, K extends keyof T>(\n input: T,\n keys: K[] | readonly K[]\n): Pick<T, K> {\n const result: Partial<Pick<T, K>> = {}\n for (const key of keys) {\n result[key] = input[key]\n }\n return result as Pick<T, K>\n}\n","export function stringJoinWithSeparateFinalSeparator(\n list: string[],\n separator: string = ' and '\n): string {\n const values = list.filter(Boolean)\n const { length } = values\n if (!length) {\n return ''\n }\n if (length === 1) {\n return values[0]!\n }\n const finalValue = values.pop()\n return `${values.join(', ')}${separator}${finalValue}`\n}\n","import { pick } from '../objects'\nimport { stringJoinWithSeparateFinalSeparator } from '../strings'\n\nimport type { SocketSdkReturnType } from '@socketsecurity/sdk'\n\nexport type SocketSdkAlertList =\n SocketSdkReturnType<'getIssuesByNPMPackage'>['data']\n\nexport type SocketSdkAlert = SocketSdkAlertList[number]['value'] extends\n | infer U\n | undefined\n ? U\n : never\n\nexport enum SEVERITY {\n critical = 'critical',\n high = 'high',\n middle = 'middle',\n low = 'low'\n}\n\n// Ordered from most severe to least.\nconst SEVERITIES_BY_ORDER: Array<SocketSdkAlert['severity']> = [\n 'critical',\n 'high',\n 'middle',\n 'low'\n]\n\nfunction getDesiredSeverities(\n lowestToInclude: SocketSdkAlert['severity'] | undefined\n): Array<SocketSdkAlert['severity']> {\n const result: Array<SocketSdkAlert['severity']> = []\n for (const severity of SEVERITIES_BY_ORDER) {\n result.push(severity)\n if (severity === lowestToInclude) {\n break\n }\n }\n return result\n}\n\nexport function formatSeverityCount(\n severityCount: Record<SocketSdkAlert['severity'], number>\n): string {\n const summary: string[] = []\n for (const severity of SEVERITIES_BY_ORDER) {\n if (severityCount[severity]) {\n summary.push(`${severityCount[severity]} ${severity}`)\n }\n }\n return stringJoinWithSeparateFinalSeparator(summary)\n}\n\nexport function getSeverityCount(\n issues: SocketSdkAlertList,\n lowestToInclude: SocketSdkAlert['severity'] | undefined\n): Record<SocketSdkAlert['severity'], number> {\n const severityCount = pick(\n { low: 0, middle: 0, high: 0, critical: 0 },\n getDesiredSeverities(lowestToInclude)\n ) as Record<SocketSdkAlert['severity'], number>\n\n for (const issue of issues) {\n const { value } = issue\n if (!value) {\n continue\n }\n if (severityCount[value.severity] !== undefined) {\n severityCount[value.severity] += 1\n }\n }\n return severityCount\n}\n","import terminalLink from 'terminal-link'\nimport colors from 'yoctocolors-cjs'\n\nimport indentString from '@socketregistry/indent-string/index.cjs'\n\nexport class ColorOrMarkdown {\n public useMarkdown: boolean\n\n constructor(useMarkdown: boolean) {\n this.useMarkdown = !!useMarkdown\n }\n\n bold(text: string): string {\n return this.useMarkdown ? `**${text}**` : colors.bold(`${text}`)\n }\n\n header(text: string, level = 1): string {\n return this.useMarkdown\n ? `\\n${''.padStart(level, '#')} ${text}\\n`\n : colors.underline(`\\n${level === 1 ? colors.bold(text) : text}\\n`)\n }\n\n hyperlink(\n text: string,\n url: string | undefined,\n {\n fallback = true,\n fallbackToUrl\n }: {\n fallback?: boolean | undefined\n fallbackToUrl?: boolean | undefined\n } = {}\n ) {\n if (url) {\n return this.useMarkdown\n ? `[${text}](${url})`\n : terminalLink(text, url, {\n fallback: fallbackToUrl ? (_text, url) => url : fallback\n })\n }\n return text\n }\n\n indent(\n ...args: Parameters<typeof indentString>\n ): ReturnType<typeof indentString> {\n return indentString(...args)\n }\n\n italic(text: string): string {\n return this.useMarkdown ? `_${text}_` : colors.italic(`${text}`)\n }\n\n json(value: any): string {\n return this.useMarkdown\n ? '```json\\n' + JSON.stringify(value) + '\\n```'\n : JSON.stringify(value)\n }\n\n list(items: string[]): string {\n const indentedContent = items.map(item => this.indent(item).trimStart())\n return this.useMarkdown\n ? `* ${indentedContent.join('\\n* ')}\\n`\n : `${indentedContent.join('\\n')}\\n`\n }\n}\n","export function getSocketDevAlertUrl(alertType: string): string {\n return `https://socket.dev/alerts/${alertType}`\n}\n\nexport function getSocketDevPackageOverviewUrl(\n eco: string,\n name: string,\n version?: string | undefined\n): string {\n return `https://socket.dev/${eco}/package/${name}${version ? `/overview/${version}` : ''}`\n}\n","import path from 'node:path'\n\nimport constants from '../constants'\n\nlet _translations: typeof import('../../translations.json') | undefined\n\nexport function getTranslations() {\n if (_translations === undefined) {\n _translations = require(\n // Lazily access constants.rootPath.\n path.join(constants.rootPath, 'translations.json')\n )\n }\n return _translations!\n}\n","import semver from 'semver'\n\nimport { PackageURL } from '@socketregistry/packageurl-js'\nimport { getManifestData } from '@socketsecurity/registry'\nimport { hasOwn } from '@socketsecurity/registry/lib/objects'\nimport { resolvePackageName } from '@socketsecurity/registry/lib/packages'\nimport { naturalCompare } from '@socketsecurity/registry/lib/sorts'\n\nimport { CompactSocketArtifact, isArtifactAlertCve } from './alert/artifact'\nimport { uxLookup } from './alert/rules'\nimport { SEVERITY } from './alert/severity'\nimport { ColorOrMarkdown } from './color-or-markdown'\nimport { getSocketDevPackageOverviewUrl } from './socket-url'\nimport { getTranslations } from './translations'\nimport constants from '../constants'\n\nimport type { Spinner } from '@socketsecurity/registry/lib/spinner'\n\nexport type SocketPackageAlert = {\n key: string\n type: string\n block: boolean\n critical: boolean\n display: boolean\n fixable: boolean\n raw: any\n upgrade: boolean\n}\n\nexport type AlertsByPkgId = Map<string, SocketPackageAlert[]>\n\nconst {\n ALERT_FIX_TYPE_CVE,\n ALERT_FIX_TYPE_UPGRADE,\n CVE_ALERT_PROPS_FIRST_PATCHED_VERSION_IDENTIFIER,\n NPM\n} = constants\n\nconst format = new ColorOrMarkdown(false)\n\ntype AlertIncludeFilter = {\n critical?: boolean | undefined\n cve?: boolean | undefined\n existing?: boolean | undefined\n unfixable?: boolean | undefined\n upgrade?: boolean | undefined\n}\n\ntype AddSocketArtifactAlertToAlertsMapOptions = {\n consolidate?: boolean | undefined\n include?: AlertIncludeFilter | undefined\n overrides?: { [key: string]: string } | undefined\n spinner?: Spinner | undefined\n}\n\nexport async function addArtifactToAlertsMap(\n artifact: CompactSocketArtifact,\n alertsByPkgId: AlertsByPkgId,\n options?: AddSocketArtifactAlertToAlertsMapOptions | undefined\n) {\n // Make TypeScript happy.\n if (!artifact.name || !artifact.version || !artifact.alerts?.length) {\n return\n }\n\n const {\n consolidate = false,\n include: _include,\n overrides\n } = {\n __proto__: null,\n ...options\n } as AddSocketArtifactAlertToAlertsMapOptions\n\n const include = {\n __proto__: null,\n critical: true,\n cve: true,\n existing: false,\n unfixable: true,\n upgrade: false,\n ..._include\n } as AlertIncludeFilter\n\n const name = resolvePackageName(artifact)\n const { version } = artifact\n const pkgId = `${name}@${version}`\n const major = semver.major(version)\n let sockPkgAlerts = []\n for (const alert of artifact.alerts) {\n // eslint-disable-next-line no-await-in-loop\n const ux = await uxLookup({\n package: { name, version },\n alert: { type: alert.type }\n })\n const fixType = alert.fix?.type ?? ''\n const critical = alert.severity === SEVERITY.critical\n const cve = isArtifactAlertCve(alert)\n const fixableCve = fixType === ALERT_FIX_TYPE_CVE\n const fixableUpgrade = fixType === ALERT_FIX_TYPE_UPGRADE\n const fixable = fixableCve || fixableUpgrade\n const upgrade = fixableUpgrade && !hasOwn(overrides, name)\n if (\n (include.cve && cve) ||\n (include.unfixable && !fixable) ||\n (include.critical && critical) ||\n (include.upgrade && upgrade)\n ) {\n sockPkgAlerts.push({\n name,\n version,\n key: alert.key,\n type: alert.type,\n block: ux.block,\n critical,\n display: ux.display,\n fixable,\n raw: alert,\n upgrade\n })\n }\n }\n if (!sockPkgAlerts.length) {\n return\n }\n if (consolidate) {\n const highestForCve = new Map<\n number,\n { alert: SocketPackageAlert; version: string }\n >()\n const highestForUpgrade = new Map<\n number,\n { alert: SocketPackageAlert; version: string }\n >()\n const unfixableAlerts: SocketPackageAlert[] = []\n for (const sockPkgAlert of sockPkgAlerts) {\n const alert = sockPkgAlert.raw\n const fixType = alert.fix?.type ?? ''\n if (fixType === ALERT_FIX_TYPE_CVE) {\n const patchedVersion =\n alert.props[CVE_ALERT_PROPS_FIRST_PATCHED_VERSION_IDENTIFIER]\n const patchedMajor = semver.major(patchedVersion)\n const oldHighest = highestForCve.get(patchedMajor)\n const highest = oldHighest?.version ?? '0.0.0'\n if (semver.gt(patchedVersion, highest)) {\n highestForCve.set(patchedMajor, {\n alert: sockPkgAlert,\n version: patchedVersion\n })\n }\n } else if (fixType === ALERT_FIX_TYPE_UPGRADE) {\n const oldHighest = highestForUpgrade.get(major)\n const highest = oldHighest?.version ?? '0.0.0'\n if (semver.gt(version, highest)) {\n highestForUpgrade.set(major, { alert: sockPkgAlert, version })\n }\n } else {\n unfixableAlerts.push(sockPkgAlert)\n }\n }\n sockPkgAlerts = [\n ...unfixableAlerts,\n ...[...highestForCve.values()].map(d => d.alert),\n ...[...highestForUpgrade.values()].map(d => d.alert)\n ]\n }\n if (!sockPkgAlerts.length) {\n return\n }\n sockPkgAlerts.sort((a, b) => naturalCompare(a.type, b.type))\n alertsByPkgId.set(pkgId, sockPkgAlerts)\n}\n\ntype CveExcludeFilter = {\n upgrade?: boolean | undefined\n}\n\ntype CveInfoByPkgId = Map<\n string,\n Array<{\n firstPatchedVersionIdentifier: string\n vulnerableVersionRange: string\n }>\n>\n\ntype GetCveInfoByPackageOptions = {\n exclude?: CveExcludeFilter | undefined\n}\n\nexport function getCveInfoByAlertsMap(\n alertsMap: AlertsByPkgId,\n options?: GetCveInfoByPackageOptions | undefined\n): CveInfoByPkgId | null {\n const exclude = {\n upgrade: true,\n ...({ __proto__: null, ...options } as GetCveInfoByPackageOptions).exclude\n }\n let infoByPkg: CveInfoByPkgId | null = null\n for (const [pkgId, sockPkgAlerts] of alertsMap) {\n const purlObj = PackageURL.fromString(`pkg:npm/${pkgId}`)\n const name = resolvePackageName(purlObj)\n for (const sockPkgAlert of sockPkgAlerts) {\n const alert = sockPkgAlert.raw\n if (\n alert.fix?.type !== ALERT_FIX_TYPE_CVE ||\n (exclude.upgrade && getManifestData(NPM, name))\n ) {\n continue\n }\n if (!infoByPkg) {\n infoByPkg = new Map()\n }\n let infos = infoByPkg.get(name)\n if (!infos) {\n infos = []\n infoByPkg.set(name, infos)\n }\n const { firstPatchedVersionIdentifier, vulnerableVersionRange } =\n alert.props\n infos.push({\n firstPatchedVersionIdentifier,\n vulnerableVersionRange: new semver.Range(\n vulnerableVersionRange\n ).format()\n })\n }\n }\n return infoByPkg\n}\n\ntype LogAlertsMapOptions = {\n output?: NodeJS.WriteStream | undefined\n}\n\nexport function logAlertsMap(\n alertsMap: AlertsByPkgId,\n options: LogAlertsMapOptions\n) {\n const { output = process.stderr } = {\n __proto__: null,\n ...options\n } as LogAlertsMapOptions\n const translations = getTranslations()\n for (const [pkgId, alerts] of alertsMap) {\n const purlObj = PackageURL.fromString(`pkg:npm/${pkgId}`)\n const lines = new Set()\n for (const alert of alerts) {\n const { type } = alert\n const attributes = [\n ...(alert.fixable ? ['fixable'] : []),\n ...(alert.block ? [] : ['non-blocking'])\n ]\n const maybeAttributes = attributes.length\n ? ` (${attributes.join('; ')})`\n : ''\n // Based data from { pageProps: { alertTypes } } of:\n // https://socket.dev/_next/data/94666139314b6437ee4491a0864e72b264547585/en-US.json\n const info = (translations.alerts as any)[type]\n const title = info?.title ?? type\n const maybeDesc = info?.description ? ` - ${info.description}` : ''\n // TODO: emoji seems to mis-align terminals sometimes\n lines.add(` ${title}${maybeAttributes}${maybeDesc}`)\n }\n output.write(\n `(socket) ${format.hyperlink(\n pkgId,\n getSocketDevPackageOverviewUrl(\n NPM,\n resolvePackageName(purlObj),\n purlObj.version\n )\n )} contains risks:\\n`\n )\n for (const line of lines) {\n output.write(`${line}\\n`)\n }\n }\n}\n","import semver from 'semver'\n\nimport { PackageURL } from '@socketregistry/packageurl-js'\nimport { getManifestData } from '@socketsecurity/registry'\nimport { arrayUnique } from '@socketsecurity/registry/lib/arrays'\nimport { debugLog } from '@socketsecurity/registry/lib/debug'\nimport { hasOwn } from '@socketsecurity/registry/lib/objects'\nimport { fetchPackagePackument } from '@socketsecurity/registry/lib/packages'\n\nimport constants from '../../constants'\nimport { SafeArborist } from '../../shadow/npm/arborist/lib/arborist'\nimport { DiffAction } from '../../shadow/npm/arborist/lib/arborist/types'\nimport { Edge } from '../../shadow/npm/arborist/lib/edge'\nimport { getPublicToken, setupSdk } from '../../utils/sdk'\nimport { CompactSocketArtifact } from '../alert/artifact'\nimport { addArtifactToAlertsMap } from '../socket-package-alert'\n\nimport type { Diff } from '../../shadow/npm/arborist/lib/arborist/types'\nimport type { SafeEdge } from '../../shadow/npm/arborist/lib/edge'\nimport type { SafeNode } from '../../shadow/npm/arborist/lib/node'\nimport type { AlertsByPkgId } from '../socket-package-alert'\nimport type { Spinner } from '@socketsecurity/registry/lib/spinner'\n\ntype Packument = Exclude<\n Awaited<ReturnType<typeof fetchPackagePackument>>,\n null\n>\n\nconst { LOOP_SENTINEL, NPM, NPM_REGISTRY_URL } = constants\n\ntype DiffQueryIncludeFilter = {\n unchanged?: boolean | undefined\n unknownOrigin?: boolean | undefined\n}\n\ntype DiffQueryOptions = {\n include?: DiffQueryIncludeFilter | undefined\n}\n\ntype PackageDetail = {\n node: SafeNode\n existing?: SafeNode | undefined\n}\n\nfunction getDetailsFromDiff(\n diff_: Diff | null,\n options?: DiffQueryOptions | undefined\n): PackageDetail[] {\n const details: PackageDetail[] = []\n // `diff_` is `null` when `npm install --package-lock-only` is passed.\n if (!diff_) {\n return details\n }\n\n const include = {\n __proto__: null,\n unchanged: false,\n unknownOrigin: false,\n ...({ __proto__: null, ...options } as DiffQueryOptions).include\n } as DiffQueryIncludeFilter\n\n const queue: Diff[] = [...diff_.children]\n let pos = 0\n let { length: queueLength } = queue\n while (pos < queueLength) {\n if (pos === LOOP_SENTINEL) {\n throw new Error('Detected infinite loop while walking Arborist diff')\n }\n const diff = queue[pos++]!\n const { action } = diff\n if (action) {\n // The `pkgNode`, i.e. the `ideal` node, will be `undefined` if the diff\n // action is 'REMOVE'\n // The `oldNode`, i.e. the `actual` node, will be `undefined` if the diff\n // action is 'ADD'.\n const { actual: oldNode, ideal: pkgNode } = diff\n let existing: SafeNode | undefined\n let keep = false\n if (action === DiffAction.change) {\n if (pkgNode?.package.version !== oldNode?.package.version) {\n keep = true\n if (\n oldNode?.package.name &&\n oldNode.package.name === pkgNode?.package.name\n ) {\n existing = oldNode\n }\n } else {\n debugLog('SKIPPING META CHANGE ON', diff)\n }\n } else {\n keep = action !== DiffAction.remove\n }\n if (keep && pkgNode?.resolved && (!oldNode || oldNode.resolved)) {\n if (\n include.unknownOrigin ||\n getUrlOrigin(pkgNode.resolved) === NPM_REGISTRY_URL\n ) {\n details.push({\n node: pkgNode,\n existing\n })\n }\n }\n }\n for (const child of diff.children) {\n queue[queueLength++] = child\n }\n }\n if (include.unchanged) {\n const { unchanged } = diff_!\n for (let i = 0, { length } = unchanged; i < length; i += 1) {\n const pkgNode = unchanged[i]!\n if (\n include.unknownOrigin ||\n getUrlOrigin(pkgNode.resolved!) === NPM_REGISTRY_URL\n ) {\n details.push({\n node: pkgNode,\n existing: pkgNode\n })\n }\n }\n }\n return details\n}\n\nfunction getUrlOrigin(input: string): string {\n try {\n return URL.parse(input)?.origin ?? ''\n } catch {}\n return ''\n}\n\nexport function findBestPatchVersion(\n node: SafeNode,\n availableVersions: string[],\n vulnerableVersionRange?: string,\n _firstPatchedVersionIdentifier?: string | undefined\n): string | null {\n const manifestData = getManifestData(NPM, node.name)\n let eligibleVersions\n if (manifestData && manifestData.name === manifestData.package) {\n const major = semver.major(manifestData.version)\n eligibleVersions = availableVersions.filter(v => semver.major(v) === major)\n } else {\n const major = semver.major(node.version)\n eligibleVersions = availableVersions.filter(\n v =>\n // Filter for versions that are within the current major version and\n // are NOT in the vulnerable range.\n semver.major(v) === major &&\n (!vulnerableVersionRange ||\n !semver.satisfies(v, vulnerableVersionRange))\n )\n }\n return semver.maxSatisfying(eligibleVersions, '*')\n}\n\nexport function findPackageNodes(\n tree: SafeNode,\n packageName: string\n): SafeNode[] {\n const queue: Array<{ node: typeof tree }> = [{ node: tree }]\n const matches: SafeNode[] = []\n let sentinel = 0\n while (queue.length) {\n if (sentinel++ === LOOP_SENTINEL) {\n throw new Error('Detected infinite loop in findPackageNodes')\n }\n const { node: currentNode } = queue.pop()!\n const node = currentNode.children.get(packageName)\n if (node) {\n matches.push(node as unknown as SafeNode)\n }\n const children = [...currentNode.children.values()]\n for (let i = children.length - 1; i >= 0; i -= 1) {\n queue.push({ node: children[i] as unknown as SafeNode })\n }\n }\n return matches\n}\n\ntype AlertIncludeFilter = {\n critical?: boolean | undefined\n cve?: boolean | undefined\n existing?: boolean | undefined\n unfixable?: boolean | undefined\n upgrade?: boolean | undefined\n}\n\ntype GetAlertsMapFromArboristOptions = {\n consolidate?: boolean | undefined\n include?: AlertIncludeFilter | undefined\n spinner?: Spinner | undefined\n}\n\nexport async function getAlertsMapFromArborist(\n arb: SafeArborist,\n options?: GetAlertsMapFromArboristOptions | undefined\n): Promise<AlertsByPkgId> {\n const { include: _include, spinner } = {\n __proto__: null,\n consolidate: false,\n ...options\n } as GetAlertsMapFromArboristOptions\n\n const include = {\n __proto__: null,\n critical: true,\n cve: true,\n existing: false,\n unfixable: true,\n upgrade: false,\n ..._include\n } as AlertIncludeFilter\n\n const needInfoOn = getDetailsFromDiff(arb.diff, {\n include: {\n unchanged: include.existing\n }\n })\n const pkgIds = arrayUnique(needInfoOn.map(d => d.node.pkgid))\n let { length: remaining } = pkgIds\n const alertsByPkgId: AlertsByPkgId = new Map()\n if (!remaining) {\n return alertsByPkgId\n }\n\n const getText = () => `Looking up data for ${remaining} packages`\n\n spinner?.start(getText())\n\n let overrides: { [key: string]: string } | undefined\n const overridesMap = (\n arb.actualTree ??\n arb.idealTree ??\n (await arb.loadActual())\n )?.overrides?.children\n if (overridesMap) {\n overrides = Object.fromEntries(\n [...overridesMap.entries()].map(([key, overrideSet]) => {\n return [key, overrideSet.value!]\n })\n )\n }\n\n const socketSdk = await setupSdk(getPublicToken())\n\n const toAlertsMapOptions = {\n overrides,\n ...options\n }\n\n for await (const batchPackageFetchResult of socketSdk.batchPackageStream(\n {\n alerts: 'true',\n compact: 'true',\n fixable: include.unfixable ? 'false' : 'true'\n },\n {\n components: pkgIds.map(id => ({ purl: `pkg:npm/${id}` }))\n }\n )) {\n if (batchPackageFetchResult.success) {\n await addArtifactToAlertsMap(\n batchPackageFetchResult.data as CompactSocketArtifact,\n alertsByPkgId,\n toAlertsMapOptions\n )\n }\n remaining -= 1\n if (spinner && remaining > 0) {\n spinner.start()\n spinner.setText(getText())\n }\n }\n\n spinner?.stop()\n\n return alertsByPkgId\n}\n\nexport function updateNode(\n node: SafeNode,\n packument: Packument,\n vulnerableVersionRange?: string,\n firstPatchedVersionIdentifier?: string | undefined\n): boolean {\n const availableVersions = Object.keys(packument.versions)\n // Find the highest non-vulnerable version within the same major range\n const targetVersion = findBestPatchVersion(\n node,\n availableVersions,\n vulnerableVersionRange,\n firstPatchedVersionIdentifier\n )\n const targetPackument = targetVersion\n ? packument.versions[targetVersion]\n : undefined\n // Check !targetVersion to make TypeScript happy.\n if (!targetVersion || !targetPackument) {\n // No suitable patch version found.\n return false\n }\n // Use Object.defineProperty to override the version.\n Object.defineProperty(node, 'version', {\n configurable: true,\n enumerable: true,\n get: () => targetVersion\n })\n node.package.version = targetVersion\n // Update resolved and clear integrity for the new version.\n const purlObj = PackageURL.fromString(`pkg:npm/${node.name}`)\n node.resolved = `${NPM_REGISTRY_URL}/${node.name}/-/${purlObj.name}-${targetVersion}.tgz`\n const { integrity } = targetPackument.dist\n if (integrity) {\n node.integrity = integrity\n } else {\n delete node.integrity\n }\n if ('deprecated' in targetPackument) {\n node.package['deprecated'] = targetPackument.deprecated as string\n } else {\n delete node.package['deprecated']\n }\n const newDeps = { ...targetPackument.dependencies }\n const { dependencies: oldDeps } = node.package\n node.package.dependencies = newDeps\n if (oldDeps) {\n for (const oldDepName of Object.keys(oldDeps)) {\n if (!hasOwn(newDeps, oldDepName)) {\n node.edgesOut.get(oldDepName)?.detach()\n }\n }\n }\n for (const newDepName of Object.keys(newDeps)) {\n if (!hasOwn(oldDeps, newDepName)) {\n node.addEdgeOut(\n new Edge({\n from: node,\n name: newDepName,\n spec: newDeps[newDepName],\n type: 'prod'\n }) as unknown as SafeEdge\n )\n }\n }\n return true\n}\n","import process from 'node:process'\n\nimport { logger } from '@socketsecurity/registry/lib/logger'\nimport { confirm } from '@socketsecurity/registry/lib/prompts'\n\nimport constants from '../../../../../constants'\nimport { getAlertsMapFromArborist } from '../../../../../utils/lockfile/package-lock-json'\nimport { logAlertsMap } from '../../../../../utils/socket-package-alert'\nimport { getArboristClassPath } from '../../../paths'\n\nimport type { ArboristClass, ArboristReifyOptions } from './types'\nimport type { SafeNode } from '../node'\n\nconst {\n NPM,\n NPX,\n SOCKET_CLI_SAFE_WRAPPER,\n kInternalsSymbol,\n [kInternalsSymbol as unknown as 'Symbol(kInternalsSymbol)']: { getIpc }\n} = constants\n\nexport const SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES = {\n __proto__: null,\n audit: false,\n dryRun: true,\n fund: false,\n ignoreScripts: true,\n progress: false,\n save: false,\n saveBundle: false,\n silent: true\n}\n\nexport const kCtorArgs = Symbol('ctorArgs')\n\nexport const kRiskyReify = Symbol('riskyReify')\n\nexport const Arborist: ArboristClass = require(getArboristClassPath())\n\n// Implementation code not related to our custom behavior is based on\n// https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/arborist/index.js:\nexport class SafeArborist extends Arborist {\n constructor(...ctorArgs: ConstructorParameters<ArboristClass>) {\n super(\n {\n path:\n (ctorArgs.length ? ctorArgs[0]?.path : undefined) ?? process.cwd(),\n ...(ctorArgs.length ? ctorArgs[0] : undefined),\n ...SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES\n },\n ...ctorArgs.slice(1)\n )\n ;(this as any)[kCtorArgs] = ctorArgs\n }\n\n async [kRiskyReify](\n ...args: Parameters<InstanceType<ArboristClass>['reify']>\n ): Promise<SafeNode> {\n const ctorArgs = (this as any)[kCtorArgs]\n const arb = new Arborist(\n {\n ...(ctorArgs.length ? ctorArgs[0] : undefined),\n progress: false\n },\n ...ctorArgs.slice(1)\n )\n const ret = await (arb.reify as (...args: any[]) => Promise<SafeNode>)(\n {\n ...(args.length ? args[0] : undefined),\n progress: false\n },\n ...args.slice(1)\n )\n Object.assign(this, arb)\n return ret\n }\n\n // @ts-ignore Incorrectly typed.\n override async reify(\n this: SafeArborist,\n ...args: Parameters<InstanceType<ArboristClass>['reify']>\n ): Promise<SafeNode> {\n const options = {\n __proto__: null,\n ...(args.length ? args[0] : undefined)\n } as ArboristReifyOptions\n const safeWrapperName = options.dryRun\n ? undefined\n : await getIpc(SOCKET_CLI_SAFE_WRAPPER)\n const isSafeNpm = safeWrapperName === NPM\n const isSafeNpx = safeWrapperName === NPX\n if (!safeWrapperName || (isSafeNpx && options['yes'])) {\n return await this[kRiskyReify](...args)\n }\n\n // Lazily access constants.spinner.\n const { spinner } = constants\n await super.reify(\n {\n ...options,\n ...SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES,\n progress: false\n },\n // @ts-ignore: TS gets grumpy about rest parameters.\n ...args.slice(1)\n )\n const alertsMap = await getAlertsMapFromArborist(this, {\n spinner,\n include: {\n existing: isSafeNpx,\n unfixable: isSafeNpm\n }\n })\n if (alertsMap.size) {\n logAlertsMap(alertsMap, { output: process.stderr })\n if (\n !(await confirm({\n message: 'Accept risks of installing these packages?',\n default: false\n }))\n ) {\n throw new Error('Socket npm exiting due to risks')\n }\n } else {\n logger.success('Socket npm found no risks!')\n }\n return await this[kRiskyReify](...args)\n }\n}\n","import {\n getArboristClassPath,\n getArboristEdgeClassPath,\n getArboristNodeClassPath,\n getArboristOverrideSetClassPath\n} from '../paths'\nimport { SafeArborist } from './lib/arborist'\nimport { SafeEdge } from './lib/edge'\nimport { SafeNode } from './lib/node'\nimport { SafeOverrideSet } from './lib/override-set'\n\nexport function installSafeArborist() {\n // Override '@npmcli/arborist' module exports with patched variants based on\n // https://github.com/npm/cli/pull/8089.\n const cache: { [key: string]: any } = require.cache\n cache[getArboristClassPath()] = { exports: SafeArborist }\n cache[getArboristEdgeClassPath()] = { exports: SafeEdge }\n cache[getArboristNodeClassPath()] = { exports: SafeNode }\n cache[getArboristOverrideSetClassPath()] = { exports: SafeOverrideSet }\n}\n","import { installSafeArborist } from './arborist'\n\ninstallSafeArborist()\n"],"names":["getSentry","constructor","abortSignal","cwd","signal","root","dir","encoding","logger","recursive","WIN32","warnedSettingPathWin32Missing","dataHome","settingsPath","yml","path","parsed","prevDir","settings","pendingSave","SOCKET_CLI_NO_API_TOKEN","_defaultToken","message","agent","proxy","baseUrl","name","version","homepage","DiffAction","UNDEFINED_TOKEN","id","transformer","mod","canDedupe","canReplaceWith","overrides","recalculateOutEdgesOverrides","edge","newOverrideSet","from","detach","explain","bundled","overridden","error","rawSpec","explanation","reload","needToUpdateOverrideSet","ALERT_TYPE_MILD_CVE","type","block","display","defaultValue","action","iterate_entries","needDefault","orderedRules","target","orderedRulesCollection","resolvedDefaultValue","ux","cachedUX","orgs","cause","deferTo","issueRules","_uxLookup","result","length","SEVERITY","low","middle","high","critical","value","severityCount","header","hyperlink","fallback","fallbackToUrl","_translations","NPM","consolidate","include","__proto__","cve","existing","upgrade","package","alert","raw","highestForCve","highestForUpgrade","unfixableAlerts","sockPkgAlerts","alertsByPkgId","infoByPkg","infos","vulnerableVersionRange","output","NPM_REGISTRY_URL","unchanged","unknownOrigin","actual","ideal","keep","debugLog","node","queue","eligibleVersions","matches","spinner","unfixable","alerts","compact","fixable","components","remaining","Object","configurable","enumerable","integrity","dependencies","spec","getIpc","audit","dryRun","fund","ignoreScripts","progress","save","saveBundle","silent","default","cache","exports","installSafeArborist"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA;;AAEE;AAA+DA;AAAU;AAC3E;AAIO;AAEA;AAGLC;;;AAGA;AACF;AAEO;AAIL;AACA;;AAEA;AACF;AAEO;AAIL;;AAEE;AACF;;AAEA;AACF;AAEO;AAGL;AACE;AACF;AACA;AACF;;ACrCA;AAAQC;AAAY;AAMb;AAEHC;AAAqBC;AAAoC;AAE3D;;AACQC;AAAK;;AAEb;AACE;;AAEI;AACF;;;AAGE;;AAEA;AACE;AACF;;AAEJ;AACAC;AACF;AACA;AACF;AASO;AAIL;AACEF;AACA;AACAG;AACF;AACF;AAEO;AAIL;AACEH;AACA;AACAG;AACF;AACF;AAMO;;AAKH;AACEA;AACAH;AACA;AAAoCG;AAAkB;AACxD;;AAEF;AACF;AAMO;;;AAYDA;AACA;AAAoCA;AAAkB;AACxD;;AAEF;AACF;;ACzGA;AACA;AACA;AACA;AACA;AAEA;AAiBA;AACA;AACA;AACA;AAEA;;;AAGI;AACA;AACE;AACA;;;AAME;AACEC;AACF;AACF;;AAC6CC;AAAgB;AAC7D;AACF;AACF;AACA;AACF;AAEA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGE;;AACQC;AAAM;AACd;;AAIE;;AAEIC;AACAH;AACF;AACF;AACEI;AAMF;AACF;AACAC;AACF;AACA;AACF;AAEA;;AAEE;AACE;AACF;AACA;AACF;AAEO;;AAEL;;;AAGE;;;AAGEC;AACF;AACA;;;AAGMC;AACAC;;AAEJ;AACE;AACF;AACF;AACAC;;AAEF;AACA;AACF;AAEO;;AAIP;AAEO;AAIL;AACAC;;AAEEC;;AAEEA;AACA;AACA;;AAKA;AACF;AACF;AACF;;AClJA;AAAQC;AAAwB;;AAEhC;AACA;AACE;AAEA;AACF;;AAEA;AACA;AACE;AAEA;AACF;;AAEA;AACA;AACO;AACL;AACA;AACEC;AACF;AACE;AAEE;AACA;;;AAKJ;AACA;AACF;AAEO;AACL;AAIF;AAEO;;;AAODC;AAEF;AACAD;AACF;;AAEE;AACF;AACA;AACEE;AAAqCC;;AACrCC;;AAEE;AACAC;AACA;AACAC;AACA;AACAC;;AAEJ;AACF;;AC/BYC;;;;AAAU;AAAA;;AChDf;;ACDP;AAAQC;AAAgB;AAaxB;AAIE;AACE;AACA;AACA;AACEC;AACAC;AACF;AACED;;AAEF;;AAEE;AACA;;;AAGE;AACF;;AAEJ;AACA;AACF;AAOA;AACO;;;AAMC;AACA;AACAE;AAIN;AACA;AACF;;AChCA;;AAEA;AACA;AACO;AACL;AACA;AACA;AAIE;AACA;AACA;;AAEF;;AAEA;AACA;AACA;AAIE;AAKE;AACE;AACF;AACF;AACA;AAKE;AACE;AACF;AACF;AACA;AACA;;AAEA;AACF;;AAEA;AACA;;;AAGI;AACF;AACA;AAAa;AAAQ;AAAoB;;;AAGrC;AACF;AACA;AACE;AACF;AACA;AACE;AACF;AACF;AACA;AACF;;;AAII;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACE;AACE;AACF;AACA;AACF;;AAEE;AAGE;AACF;AACA;AACF;AACA;AACA;AACA;AACA;AACF;AACA;AACF;;AAEA;AACA;;;AAGI;AACF;;AAEE;AACF;AACA;AAIE;AACF;AACA;AACE;AACF;AACA;;AAEA;;AAEF;AACF;;ACpFA;;AAEA;AACA;AACO;AACL;AACA;AACA;AACSC;AACP;AACA;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;;AAEE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACE;AACF;AACA;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACSC;AACP;AACE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;;;AAGI;AACF;AACF;;AAEI;AACF;AACF;AACF;AACA;AACA;AACA;AACA;AACA;;AAEA;AACE;AACF;;;;;;AAME;AACF;AACA;AACF;;AAEA;;AAEE;;AACQC;AAAU;AAClB;AACE;AACF;AACF;;AAGE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AACF;AACA;AACA;;AAEF;;AAEA;;AAEE;AACA;AACA;;AAME;AACF;AACA;AACA;AACA;AACA;AACA;AACA;;AAMI;AACE;AACF;AACF;AACF;AACA;AACF;;AAGE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACQA;AAAU;AAClB;;AAEA;;;;;;AAME;AACF;AACF;;AAEA;AACA;AACSC;AACP;;AAEEC;;;AAGA;AACF;AACF;;AAEA;;AAEE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AAAuCF;AAAc;AACvD;;;;;;AAME;AACF;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAKI;AACA;AACA;AACA;AACA;AACF;AACA;;;AAGE;AACF;;AAEE;AACF;;AAKA;;AAEI;AACF;;;AAGA;AACF;AACA;AACA;AACA;;AAEA;AACF;;AAEA;AACA;;AAEE;AACA;AACA;AACE;AACF;AACA;AACA;;AACUA;AAAyB;;;AAMjC;AACEG;AACF;AACF;;AAEE;AACF;;AAEA;AACE;AACA;AACA;AACA;AACA;;AAEF;AACA;AACF;AACF;;ACrUO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACL;AACA;AACA;AACA;;;AAGUC;AAAK;AACb;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACF;;AAGE;AACF;;AAGE;AACE;;AAEI;AACF;AACE;AACF;AACF;AAGE;AACA;AACA;AAEA;AACF;AACE;AACF;AACA;AACA;AAAA;AASE;AACA;AACA;AACA;AACA;AACA;AACF;AACE;AACF;AACF;AACA;AACE;AACF;;AAEF;;AAEA;;;AAGA;;AAEA;;;;;AASM;AACA;AACA;AACA;AACA;;AAIA;AACE;AACF;AACA;AACE;AACF;AACA;AACE;AACF;AACA;AACE;AACF;;AAEF;AACA;AACF;;AAEF;;AAEA;;;AAGA;AAESC;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACF;;AAEA;AACA;AACSC;AACP;AACE;;;;AAIEC;AACAC;AACAC;AACAL;AACAM;;AAEF;AACEC;;AAEF;;AAEEA;AACF;;AAEEA;AACF;AACA;;AAEA;AACA;AACF;;AAEF;AAESC;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA;;;AAGI;AACA;AACA;AACA;AACAC;;;AAGF;AACF;;AAEA;AACA;AACA;AACA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACF;AACA;AACA;AAAA;AAEE;AACA;AACA;AACF;AACF;;AAGE;AACA;AACA;AACA;AACA;AACA;AACE;AACF;AACA;AACA;;AAEE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF;AACF;;AC/QA;;;;AAIEC;AACF;AAEO;;AAGGC;AAAK;AACb;AAMF;;AC9BA;AACEC;AACAC;AACF;AAEA;AACED;AACAC;AACF;AAEA;AACED;AACAC;AACF;;AAEA;AACA;AACA;AACA;;AASIC;AAAiBC;;AACnB;AACED;AAAiBC;;AACnB;;;;AAIAC;AACE;AACE;AACEC;AACA;AACAL;AACAC;AACA;AACF;AACF;AACA;AACAD;AACAC;AACF;AACA;AACE;AACAD;AACAC;AACF;;;AACgBA;;AAClB;;AAEA;AACA;;AAII;AACF;AACA;;AACUE;AAAO;AACf;AACE;AACF;AACF;AACA;AACF;;AAEA;AACA;AAGE;AACE;AACF;;AACQA;AAAO;;AAEb;AACF;AACE;AACF;AACA;AACF;AAMO;AAIL;AAEA;;AACUJ;;AACR;AACA;AACE;AACF;;AAEA;;AAEE;;AAEE;;AAEE;AACF;AACA;AACA;AACEO;AACF;AACAC;AACF;AACAC;AACF;;AAKA;AACEL;;;AAGAM;AAAyBN;;AAC3B;AACEM;AAAyBN;;AAC3B;AACAO;AACAC;AACA;;AAEJ;AAEA;AACO;;;;AAIW7C;;;;AAGV;AACA;;AAIA;;AAIA;AACE;AACE8C;AACF;AACF;AACA;;;AAGA;;AAIA;;;;;;AAMA;AACA;AAIE;AAGIC;AACF;AAEJ;AACA;AACF;AACF;AACA;AACA;AACA;AAAa;AAAM;AAAO;;;AAGxB;AACF;AACA;AACA;AACE/C;;AAEEA;;AAEIgD;AACA;AACA;AACA;AACA;AACA;AACAC;AAKF;AACF;AACF;AACF;AACAC;AACF;;AAEF;;AClQO;;AAKL;AACEC;AACF;AACA;AACF;;ACTO;AAIL;;AACQC;AAAO;;AAEb;AACF;;;AAGA;AACA;;AAEF;;ACAYC;;;;;AAAQ;AAAA;;AAOpB;AACA;AAOA;;AAIE;AACEF;;AAEE;AACF;AACF;AACA;AACF;AAEO;;AAIL;AACE;;AAEA;AACF;;AAEF;AAEO;;AAKDG;AAAQC;AAAWC;AAASC;AAAY;AAI5C;;AACUC;AAAM;;AAEZ;AACF;;AAEEC;AACF;AACF;AACA;AACF;;ACpEO;;AAIH;AACF;;AAGE;AACF;AAEAC;AACE;AAGF;AAEAC;AAIIC;AACAC;;AAMF;AACE;;AAII;AACN;AACA;AACF;;AAKE;AACF;;AAGE;AACF;;;AAMA;;AAGE;;AAIF;AACF;;ACjEO;;AAEP;AAEO;AAKL;AACF;;ACNA;AAEO;;AAEHC;AACE;;AAGJ;AACA;AACF;;ACiBA;;;;AAIEC;AACF;AAEA;AAiBO;AAKL;AACA;AACE;AACF;;AAGEC;AACAC;AACAjD;AACF;AACEkD;;;AAIF;AACEA;AACAX;AACAY;AACAC;AAEAC;;;AAIF;;AACQ9D;AAAQ;AAChB;AACA;;AAEA;AACE;AACA;AACE+D;;AAAiB/D;;AACjBgE;;AAA0B;AAC5B;;;AAGA;AACA;AACA;AACA;;;;;;;;;;;;AAiBIC;AACAH;AACF;AACF;AACF;AACA;AACE;AACF;AACA;AACE;AAIA;;AAKA;AACE;;;AAGE;AAEA;AACA;AACA;;AAEEI;AACEF;AACAhE;AACF;AACF;AACF;AACE;AACA;;AAEEmE;AAA+BH;AAAqBhE;AAAQ;AAC9D;AACF;AACEoE;AACF;AACF;AACAC;AAKF;AACA;AACE;AACF;AACAA;AACAC;AACF;AAkBO;AAIL;AACER;;AACMH;;AAA4B;;;;;AAKlC;AACA;AACE;AACA;AAIE;AACF;;AAEEY;AACF;AACA;;AAEEC;AACAD;AACF;;;AACuCE;;;;;AAOvC;AACF;AACF;AACA;AACF;AAMO;;;AAI2B;AAC9Bd;;;AAGF;;;AAGE;AACA;;AACUnC;AAAK;;AAKb;AAGA;AACA;AACA;AACA;AACA;AACA;;AAEF;;AAWA;AACEkD;AACF;AACF;AACF;;ACzPA;;;AAA4BC;AAAiB;AAgB7C;;AAKE;;AAEE;AACF;AAEA;AACEhB;AACAiB;AACAC;;AACMlB;;AAA4B;;AAGpC;;;AAEMhB;AAAoB;;;AAGtB;AACF;AACA;;AACQf;AAAO;AACf;AACE;AACA;AACA;AACA;;AACQkD;AAAiBC;AAAe;AACxC;;AAEA;;AAEIC;AACA;AAIEnB;AACF;AACF;AACEoB;AACF;AACF;AACED;AACF;AACA;AACE;;AAKIE;AACArB;AACF;AACF;AACF;AACF;AACA;AACEsB;AACF;AACF;;;AAEUP;AAAU;AAClB;AAAkBjC;;AAChB;AACA;;AAKIuC;AACArB;AACF;AACF;AACF;AACF;AACA;AACF;AAEA;;;;AAIE;AACF;AAEO;;AAOL;;;AAGEuB;AACF;;AAEEA;AAEI;AACA;;AAKN;AACA;AACF;AAEO;;AAI0CF;AAAW;;;;AAIxD;AACE;AACF;;AACQA;AAAkB;;AAE1B;AACEG;AACF;;AAEA;;;AACwD;AACxD;AACF;AACA;AACF;AAgBO;;AAIG3B;AAAmB4B;AAAQ;AACjC3B;AACAF;;AAIF;AACEE;AACAX;AAGAuC;AACAzB;;AAIF;AACEJ;;AAEA;AACF;AACA;;AACMf;AAAkB;AACxB;;AAEE;AACF;AAEA;AAEA2C;AAEA;;AAMA;;AAGM;AACF;AAEJ;;AAIA;;;;AAKA;AAEIE;AACAC;AACAC;AACF;AAEEC;;AAAsD;AACxD;;;AAQA;AACAC;AACA;;AAEEN;AACF;AACF;;AAIA;AACF;AAEO;;AAOL;;;AAUA;AACA;AACE;AACA;AACF;AACA;AACAO;AACEC;AACAC;;AAEF;AACAb;AACA;;AAEAA;;AACQc;;AACR;;AAEA;;AAEA;;;AAGA;AACE;AACF;AACA;AAAkB;;;AACVC;;AACRf;AACA;;AAEI;;AAEA;AACF;AACF;;AAEE;AACEA;AAEIrE;AACAd;AACAmG;AACA1E;AACF;AAEJ;AACF;AACA;AACF;;AChVA;;;;;AAKE;AAA+D2E;AAAO;AACxE;AAEO;AACLxC;AACAyC;AACAC;AACAC;AACAC;AACAC;AACAC;AACAC;AACAC;AACF;AAEO;AAEA;AAEA;;AAEP;AACA;AACO;;AAEH;AAEIvH;;;;AAOF;AACJ;AAEA;AAGE;AACA;;AAGIoH;;AAIJ;;AAGIA;;AAIJX;AACA;AACF;;AAEA;AACA;AAIE;AACElC;;;AAGF;AAGA;AACA;;;AAGA;;AAEA;;AACQ2B;AAAQ;;AAGZ;AACA;AACAkB;;AAEF;AACA;AAEF;;AAEE9C;AACEG;AACA0B;AACF;AACF;;;;AAEmD;;AAG7C5F;AACAiH;;AAGF;AACF;AACF;AACE/H;AACF;;AAEF;AACF;;ACrHO;AACL;AACA;AACA;AACAgI;AAAkCC;;AAClCD;AAAsCC;;AACtCD;AAAsCC;;AACtCD;AAA6CC;;AAC/C;;ACjBAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;","debugId":"10ac7b59-9e2e-4a6a-88ed-ed401e2c65fd"}
1
+ {"version":3,"file":"shadow-npm-inject.js","sources":["../../src/utils/errors.ts","../../src/utils/fs.ts","../../src/utils/settings.ts","../../src/utils/sdk.ts","../../src/shadow/npm/arborist/lib/arborist/types.ts","../../src/shadow/npm/arborist/lib/dep-valid.ts","../../src/shadow/npm/proc-log/index.ts","../../src/shadow/npm/arborist/lib/override-set.ts","../../src/shadow/npm/arborist/lib/node.ts","../../src/shadow/npm/arborist/lib/edge.ts","../../src/utils/alert/artifact.ts","../../src/utils/alert/fix.ts","../../src/utils/alert/rules.ts","../../src/utils/objects.ts","../../src/utils/strings.ts","../../src/utils/alert/severity.ts","../../src/utils/color-or-markdown.ts","../../src/utils/socket-url.ts","../../src/utils/translations.ts","../../src/utils/socket-package-alert.ts","../../src/utils/lockfile/package-lock-json.ts","../../src/shadow/npm/arborist/lib/arborist/index.ts","../../src/shadow/npm/arborist/index.ts","../../src/shadow/npm/inject.ts"],"sourcesContent":["import { setTimeout as wait } from 'node:timers/promises'\n\nimport { debugLog } from '@socketsecurity/registry/lib/debug'\n\nimport constants from '../constants'\n\nconst {\n kInternalsSymbol,\n [kInternalsSymbol as unknown as 'Symbol(kInternalsSymbol)']: { getSentry }\n} = constants\n\ntype EventHintOrCaptureContext = { [key: string]: any } | Function\n\nexport class AuthError extends Error {}\n\nexport class InputError extends Error {\n public body: string | undefined\n\n constructor(message: string, body?: string) {\n super(message)\n this.body = body\n }\n}\n\nexport async function captureException(\n exception: unknown,\n hint?: EventHintOrCaptureContext | undefined\n): Promise<string> {\n const result = captureExceptionSync(exception, hint)\n // \"Sleep\" for a second, just in case, hopefully enough time to initiate fetch.\n await wait(1000)\n return result\n}\n\nexport function captureExceptionSync(\n exception: unknown,\n hint?: EventHintOrCaptureContext | undefined\n): string {\n const Sentry = getSentry()\n if (!Sentry) {\n return ''\n }\n debugLog('captureException: Sending exception to Sentry.')\n return Sentry.captureException(exception, hint) as string\n}\n\nexport function isErrnoException(\n value: unknown\n): value is NodeJS.ErrnoException {\n if (!(value instanceof Error)) {\n return false\n }\n return (value as NodeJS.ErrnoException).code !== undefined\n}\n","import { promises as fs, readFileSync as fsReadFileSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport constants from '../constants'\n\nimport type { Remap } from '@socketsecurity/registry/lib/objects'\nimport type { Abortable } from 'node:events'\nimport type {\n ObjectEncodingOptions,\n OpenMode,\n PathLike,\n PathOrFileDescriptor\n} from 'node:fs'\nimport type { FileHandle } from 'node:fs/promises'\n\nconst { abortSignal } = constants\n\nexport type FindUpOptions = {\n cwd?: string | undefined\n signal?: AbortSignal | undefined\n}\nexport async function findUp(\n name: string | string[],\n { cwd = process.cwd(), signal = abortSignal }: FindUpOptions\n): Promise<string | undefined> {\n let dir = path.resolve(cwd)\n const { root } = path.parse(dir)\n const names = [name].flat()\n while (dir && dir !== root) {\n for (const name of names) {\n if (signal?.aborted) {\n return undefined\n }\n const filePath = path.join(dir, name)\n try {\n // eslint-disable-next-line no-await-in-loop\n const stats = await fs.stat(filePath)\n if (stats.isFile()) {\n return filePath\n }\n } catch {}\n }\n dir = path.dirname(dir)\n }\n return undefined\n}\n\nexport type ReadFileOptions = Remap<\n ObjectEncodingOptions &\n Abortable & {\n flag?: OpenMode | undefined\n }\n>\n\nexport async function readFileBinary(\n filepath: PathLike | FileHandle,\n options?: ReadFileOptions | undefined\n): Promise<Buffer> {\n return (await fs.readFile(filepath, {\n signal: abortSignal,\n ...options,\n encoding: 'binary'\n } as ReadFileOptions)) as Buffer\n}\n\nexport async function readFileUtf8(\n filepath: PathLike | FileHandle,\n options?: ReadFileOptions | undefined\n): Promise<string> {\n return await fs.readFile(filepath, {\n signal: abortSignal,\n ...options,\n encoding: 'utf8'\n })\n}\n\nexport async function safeReadFile(\n filepath: PathLike | FileHandle,\n options?: 'utf8' | 'utf-8' | { encoding: 'utf8' | 'utf-8' } | undefined\n): Promise<string | undefined>\nexport async function safeReadFile(\n filepath: PathLike | FileHandle,\n options?: ReadFileOptions | NodeJS.BufferEncoding | undefined\n): Promise<Awaited<ReturnType<typeof fs.readFile>> | undefined> {\n try {\n return await fs.readFile(filepath, {\n encoding: 'utf8',\n signal: abortSignal,\n ...(typeof options === 'string' ? { encoding: options } : options)\n })\n } catch {}\n return undefined\n}\n\nexport function safeReadFileSync(\n filepath: PathOrFileDescriptor,\n options?: 'utf8' | 'utf-8' | { encoding: 'utf8' | 'utf-8' } | undefined\n): string | undefined\nexport function safeReadFileSync(\n filepath: PathOrFileDescriptor,\n options?:\n | {\n encoding?: NodeJS.BufferEncoding | undefined\n flag?: string | undefined\n }\n | NodeJS.BufferEncoding\n | undefined\n): ReturnType<typeof fsReadFileSync> | undefined {\n try {\n return fsReadFileSync(filepath, {\n encoding: 'utf8',\n ...(typeof options === 'string' ? { encoding: options } : options)\n })\n } catch {}\n return undefined\n}\n","import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\n\nimport config from '@socketsecurity/config'\nimport { logger } from '@socketsecurity/registry/lib/logger'\n\nimport { safeReadFileSync } from './fs'\nimport constants from '../constants'\n\n// Default app data folder env var on Win\nconst LOCALAPPDATA = 'LOCALAPPDATA'\n// Default app data folder env var on Mac/Linux\nconst XDG_DATA_HOME = 'XDG_DATA_HOME'\nconst SOCKET_APP_DIR = 'socket/settings'\n\nconst supportedApiKeys: Set<keyof Settings> = new Set([\n 'apiBaseUrl',\n 'apiKey',\n 'apiProxy',\n 'enforcedOrgs'\n])\n\ninterface Settings {\n apiBaseUrl?: string | null | undefined\n // @deprecated\n apiKey?: string | null | undefined\n apiProxy?: string | null | undefined\n enforcedOrgs?: string[] | readonly string[] | null | undefined\n // apiToken is an alias for apiKey.\n apiToken?: string | null | undefined\n}\n\nlet settings: Settings | undefined\nlet settingsPath: string | undefined\nlet warnedSettingPathWin32Missing = false\nlet pendingSave = false\n\nfunction getSettings(): Settings {\n if (settings === undefined) {\n settings = {} as Settings\n const settingsPath = getSettingsPath()\n if (settingsPath) {\n const raw = safeReadFileSync(settingsPath)\n if (raw) {\n try {\n Object.assign(\n settings,\n JSON.parse(Buffer.from(raw, 'base64').toString())\n )\n } catch {\n logger.warn(`Failed to parse settings at ${settingsPath}`)\n }\n } else {\n fs.mkdirSync(path.dirname(settingsPath), { recursive: true })\n }\n }\n }\n return settings\n}\n\nfunction getSettingsPath(): string | undefined {\n // Get the OS app data folder:\n // - Win: %LOCALAPPDATA% or fail?\n // - Mac: %XDG_DATA_HOME% or fallback to \"~/Library/Application Support/\"\n // - Linux: %XDG_DATA_HOME% or fallback to \"~/.local/share/\"\n // Note: LOCALAPPDATA is typically: C:\\Users\\USERNAME\\AppData\n // Note: XDG stands for \"X Desktop Group\", nowadays \"freedesktop.org\"\n // On most systems that path is: $HOME/.local/share\n // Then append `socket/settings`, so:\n // - Win: %LOCALAPPDATA%\\socket\\settings or return undefined\n // - Mac: %XDG_DATA_HOME%/socket/settings or \"~/Library/Application Support/socket/settings\"\n // - Linux: %XDG_DATA_HOME%/socket/settings or \"~/.local/share/socket/settings\"\n\n if (settingsPath === undefined) {\n // Lazily access constants.WIN32.\n const { WIN32 } = constants\n let dataHome: string | undefined = WIN32\n ? process.env[LOCALAPPDATA]\n : process.env[XDG_DATA_HOME]\n if (!dataHome) {\n if (WIN32) {\n if (!warnedSettingPathWin32Missing) {\n warnedSettingPathWin32Missing = true\n logger.warn(`Missing %${LOCALAPPDATA}%`)\n }\n } else {\n dataHome = path.join(\n os.homedir(),\n ...(process.platform === 'darwin'\n ? ['Library', 'Application Support']\n : ['.local', 'share'])\n )\n }\n }\n settingsPath = dataHome ? path.join(dataHome, SOCKET_APP_DIR) : undefined\n }\n return settingsPath\n}\n\nfunction normalizeSettingsKey(key: keyof Settings): keyof Settings {\n const normalizedKey = key === 'apiToken' ? 'apiKey' : key\n if (!supportedApiKeys.has(normalizedKey as keyof Settings)) {\n throw new Error(`Invalid settings key: ${normalizedKey}`)\n }\n return normalizedKey as keyof Settings\n}\n\nexport function findSocketYmlSync() {\n let prevDir = null\n let dir = process.cwd()\n while (dir !== prevDir) {\n let ymlPath = path.join(dir, 'socket.yml')\n let yml = safeReadFileSync(ymlPath)\n if (yml === undefined) {\n ymlPath = path.join(dir, 'socket.yaml')\n yml = safeReadFileSync(ymlPath)\n }\n if (typeof yml === 'string') {\n try {\n return {\n path: ymlPath,\n parsed: config.parseSocketConfig(yml)\n }\n } catch {\n throw new Error(`Found file but was unable to parse ${ymlPath}`)\n }\n }\n prevDir = dir\n dir = path.join(dir, '..')\n }\n return null\n}\n\nexport function getSetting<Key extends keyof Settings>(\n key: Key\n): Settings[Key] {\n return getSettings()[normalizeSettingsKey(key) as Key]\n}\n\nexport function updateSetting<Key extends keyof Settings>(\n key: Key,\n value: Settings[Key]\n): void {\n const settings = getSettings()\n settings[normalizeSettingsKey(key) as Key] = value\n if (!pendingSave) {\n pendingSave = true\n process.nextTick(() => {\n pendingSave = false\n const settingsPath = getSettingsPath()\n if (settingsPath) {\n fs.writeFileSync(\n settingsPath,\n Buffer.from(JSON.stringify(settings)).toString('base64')\n )\n }\n })\n }\n}\n","import process from 'node:process'\n\nimport { HttpsProxyAgent } from 'hpagent'\n\nimport isInteractive from '@socketregistry/is-interactive/index.cjs'\nimport { SOCKET_PUBLIC_API_TOKEN } from '@socketsecurity/registry/lib/constants'\nimport { password } from '@socketsecurity/registry/lib/prompts'\nimport { isNonEmptyString } from '@socketsecurity/registry/lib/strings'\nimport { SocketSdk, createUserAgentFromPkgJson } from '@socketsecurity/sdk'\n\nimport { AuthError } from './errors'\nimport { getSetting } from './settings'\nimport constants from '../constants'\n\nconst { SOCKET_CLI_NO_API_TOKEN } = constants\n\n// The API server that should be used for operations.\nfunction getDefaultApiBaseUrl(): string | undefined {\n const baseUrl =\n process.env['SOCKET_SECURITY_API_BASE_URL'] || getSetting('apiBaseUrl')\n return isNonEmptyString(baseUrl) ? baseUrl : undefined\n}\n\n// The API server that should be used for operations.\nfunction getDefaultHttpProxy(): string | undefined {\n const apiProxy =\n process.env['SOCKET_SECURITY_API_PROXY'] || getSetting('apiProxy')\n return isNonEmptyString(apiProxy) ? apiProxy : undefined\n}\n\n// This API key should be stored globally for the duration of the CLI execution.\nlet _defaultToken: string | undefined\nexport function getDefaultToken(): string | undefined {\n // Lazily access constants.ENV[SOCKET_CLI_NO_API_TOKEN].\n if (constants.ENV[SOCKET_CLI_NO_API_TOKEN]) {\n _defaultToken = undefined\n } else {\n const key =\n process.env['SOCKET_SECURITY_API_TOKEN'] ||\n // Keep 'SOCKET_SECURITY_API_KEY' as an alias of 'SOCKET_SECURITY_API_TOKEN'.\n // TODO: Remove 'SOCKET_SECURITY_API_KEY' alias.\n process.env['SOCKET_SECURITY_API_KEY'] ||\n getSetting('apiToken') ||\n _defaultToken\n _defaultToken = isNonEmptyString(key) ? key : undefined\n }\n return _defaultToken\n}\n\nexport function getPublicToken(): string {\n return (\n (process.env['SOCKET_SECURITY_API_TOKEN'] || getDefaultToken()) ??\n SOCKET_PUBLIC_API_TOKEN\n )\n}\n\nexport async function setupSdk(\n apiToken: string | undefined = getDefaultToken(),\n apiBaseUrl: string | undefined = getDefaultApiBaseUrl(),\n proxy: string | undefined = getDefaultHttpProxy()\n): Promise<SocketSdk> {\n if (typeof apiToken !== 'string' && isInteractive()) {\n apiToken = await password({\n message:\n 'Enter your Socket.dev API key (not saved, use socket login to persist)'\n })\n _defaultToken = apiToken\n }\n if (!apiToken) {\n throw new AuthError('You need to provide an API key')\n }\n return new SocketSdk(apiToken, {\n agent: proxy ? new HttpsProxyAgent({ proxy }) : undefined,\n baseUrl: apiBaseUrl,\n userAgent: createUserAgentFromPkgJson({\n // The '@rollup/plugin-replace' will replace \"process.env['INLINED_SOCKET_CLI_NAME']\".\n name: process.env['INLINED_SOCKET_CLI_NAME'] as string,\n // The '@rollup/plugin-replace' will replace \"process.env['INLINED_SOCKET_CLI_VERSION']\".\n version: process.env['INLINED_SOCKET_CLI_VERSION'] as string,\n // The '@rollup/plugin-replace' will replace \"process.env['INLINED_SOCKET_CLI_HOMEPAGE']\".\n homepage: process.env['INLINED_SOCKET_CLI_HOMEPAGE'] as string\n })\n })\n}\n","import type { SafeNode } from '../node'\nimport type {\n Options as ArboristOptions,\n Advisory as BaseAdvisory,\n Arborist as BaseArborist,\n AuditReport as BaseAuditReport,\n Diff as BaseDiff,\n BuildIdealTreeOptions,\n ReifyOptions\n} from '@npmcli/arborist'\n\nexport type ArboristClass = ArboristInstance & {\n new (...args: any): ArboristInstance\n}\n\nexport type ArboristInstance = Omit<\n typeof BaseArborist,\n | 'actualTree'\n | 'auditReport'\n | 'buildIdealTree'\n | 'diff'\n | 'idealTree'\n | 'loadActual'\n | 'loadVirtual'\n | 'reify'\n> & {\n auditReport?: AuditReportInstance | null | undefined\n actualTree?: SafeNode | null | undefined\n diff: Diff | null\n idealTree?: SafeNode | null | undefined\n buildIdealTree(options?: BuildIdealTreeOptions): Promise<SafeNode>\n loadActual(options?: ArboristOptions): Promise<SafeNode>\n loadVirtual(options?: ArboristOptions): Promise<SafeNode>\n reify(options?: ArboristReifyOptions): Promise<SafeNode>\n}\n\nexport type ArboristReifyOptions = ReifyOptions & ArboristOptions\n\nexport type AuditReportInstance = Omit<BaseAuditReport, 'report'> & {\n report: { [dependency: string]: AuditAdvisory[] }\n}\n\nexport type AuditAdvisory = Omit<BaseAdvisory, 'id'> & {\n id: number\n cwe: string[]\n cvss: {\n score: number\n vectorString: string\n }\n vulnerable_versions: string\n}\n\nexport enum DiffAction {\n add = 'ADD',\n change = 'CHANGE',\n remove = 'REMOVE'\n}\n\nexport type Diff = Omit<\n BaseDiff,\n | 'actual'\n | 'children'\n | 'filterSet'\n | 'ideal'\n | 'leaves'\n | 'removed'\n | 'shrinkwrapInflated'\n | 'unchanged'\n> & {\n actual: SafeNode\n children: Diff[]\n filterSet: Set<SafeNode>\n ideal: SafeNode\n leaves: SafeNode[]\n parent: Diff | null\n removed: SafeNode[]\n shrinkwrapInflated: Set<SafeNode>\n unchanged: SafeNode[]\n}\n","import { getArboristDepValidPath } from '../../paths'\n\nimport type { SafeNode } from './node'\n\nexport const depValid: (\n child: SafeNode,\n requested: string,\n accept: string | undefined,\n requester: SafeNode\n) => boolean = require(getArboristDepValidPath())\n","import constants from '../../../constants'\nimport { getNpmRequire } from '../paths'\n\nconst { UNDEFINED_TOKEN } = constants\n\ninterface RequireKnownModules {\n npmlog: typeof import('npmlog')\n // The DefinitelyTyped definition of 'proc-log' does NOT have the log method.\n // The return type of the log method is the same as `typeof import('proc-log')`.\n 'proc-log': typeof import('proc-log')\n}\n\ntype RequireTransformer<T extends keyof RequireKnownModules> = (\n mod: RequireKnownModules[T]\n) => RequireKnownModules[T]\n\nfunction tryRequire<T extends keyof RequireKnownModules>(\n req: NodeJS.Require,\n ...ids: Array<T | [T, RequireTransformer<T>]>\n): RequireKnownModules[T] | undefined {\n for (const data of ids) {\n let id: string | undefined\n let transformer: RequireTransformer<T> | undefined\n if (Array.isArray(data)) {\n id = data[0]\n transformer = data[1] as RequireTransformer<T>\n } else {\n id = data as keyof RequireKnownModules\n transformer = mod => mod\n }\n try {\n // Check that the transformed value isn't `undefined` because older\n // versions of packages like 'proc-log' may not export a `log` method.\n const exported = transformer(req(id))\n if (exported !== undefined) {\n return exported\n }\n } catch {}\n }\n return undefined\n}\n\nexport type Logger =\n | typeof import('npmlog')\n | typeof import('proc-log')\n | undefined\n\nlet _log: Logger | {} | undefined = UNDEFINED_TOKEN\nexport function getLogger(): Logger {\n if (_log === UNDEFINED_TOKEN) {\n _log = tryRequire(\n getNpmRequire(),\n [\n 'proc-log/lib/index.js' as 'proc-log',\n // The proc-log DefinitelyTyped definition is incorrect. The type definition\n // is really that of its export log.\n mod => (mod as any).log as RequireKnownModules['proc-log']\n ],\n 'npmlog/lib/log.js' as 'npmlog'\n )\n }\n return _log as Logger | undefined\n}\n","import npa from 'npm-package-arg'\nimport semver from 'semver'\n\nimport { getArboristOverrideSetClassPath } from '../../paths'\nimport { getLogger } from '../../proc-log'\n\nimport type { SafeEdge } from './edge'\nimport type { SafeNode } from './node'\nimport type { AliasResult, RegistryResult } from 'npm-package-arg'\n\ninterface OverrideSetClass {\n children: Map<string, SafeOverrideSet>\n key: string | undefined\n keySpec: string | undefined\n name: string | undefined\n parent: SafeOverrideSet | undefined\n value: string | undefined\n version: string | undefined\n // eslint-disable-next-line @typescript-eslint/no-misused-new\n new (...args: any[]): OverrideSetClass\n get isRoot(): boolean\n get ruleset(): Map<string, SafeOverrideSet>\n ancestry(): Generator<SafeOverrideSet>\n childrenAreEqual(otherOverrideSet: SafeOverrideSet | undefined): boolean\n getEdgeRule(edge: SafeEdge): SafeOverrideSet\n getNodeRule(node: SafeNode): SafeOverrideSet\n getMatchingRule(node: SafeNode): SafeOverrideSet | null\n isEqual(otherOverrideSet: SafeOverrideSet | undefined): boolean\n}\n\nconst OverrideSet: OverrideSetClass = require(getArboristOverrideSetClassPath())\n\n// Implementation code not related to patch https://github.com/npm/cli/pull/8089\n// is based on https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/override-set.js:\nexport class SafeOverrideSet extends OverrideSet {\n // Patch adding doOverrideSetsConflict is based on\n // https://github.com/npm/cli/pull/8089.\n static doOverrideSetsConflict(\n first: SafeOverrideSet | undefined,\n second: SafeOverrideSet | undefined\n ) {\n // If override sets contain one another then we can try to use the more\n // specific one. If neither one is more specific, then we consider them to\n // be in conflict.\n return this.findSpecificOverrideSet(first, second) === undefined\n }\n\n // Patch adding findSpecificOverrideSet is based on\n // https://github.com/npm/cli/pull/8089.\n static findSpecificOverrideSet(\n first: SafeOverrideSet | undefined,\n second: SafeOverrideSet | undefined\n ) {\n for (\n let overrideSet = second;\n overrideSet;\n overrideSet = overrideSet.parent\n ) {\n if (overrideSet.isEqual(first)) {\n return second\n }\n }\n for (\n let overrideSet = first;\n overrideSet;\n overrideSet = overrideSet.parent\n ) {\n if (overrideSet.isEqual(second)) {\n return first\n }\n }\n // The override sets are incomparable. Neither one contains the other.\n const log = getLogger()\n log?.silly('Conflicting override sets', first, second)\n return undefined\n }\n\n // Patch adding childrenAreEqual is based on\n // https://github.com/npm/cli/pull/8089.\n override childrenAreEqual(otherOverrideSet: SafeOverrideSet) {\n if (this.children.size !== otherOverrideSet.children.size) {\n return false\n }\n for (const { 0: key, 1: childOverrideSet } of this.children) {\n const otherChildOverrideSet = otherOverrideSet.children.get(key)\n if (!otherChildOverrideSet) {\n return false\n }\n if (childOverrideSet.value !== otherChildOverrideSet.value) {\n return false\n }\n if (!childOverrideSet.childrenAreEqual(otherChildOverrideSet)) {\n return false\n }\n }\n return true\n }\n\n override getEdgeRule(edge: SafeEdge): SafeOverrideSet {\n for (const rule of this.ruleset.values()) {\n if (rule.name !== edge.name) {\n continue\n }\n // If keySpec is * we found our override.\n if (rule.keySpec === '*') {\n return rule\n }\n // Patch replacing\n // let spec = npa(`${edge.name}@${edge.spec}`)\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // We need to use the rawSpec here, because the spec has the overrides\n // applied to it already. The rawSpec can be undefined, so we need to use\n // the fallback value of spec if it is.\n let spec = npa(`${edge.name}@${edge.rawSpec || edge.spec}`)\n if (spec.type === 'alias') {\n spec = (spec as AliasResult).subSpec\n }\n if (spec.type === 'git') {\n if (spec.gitRange && semver.intersects(spec.gitRange, rule.keySpec!)) {\n return rule\n }\n continue\n }\n if (spec.type === 'range' || spec.type === 'version') {\n if (\n semver.intersects((spec as RegistryResult).fetchSpec, rule.keySpec!)\n ) {\n return rule\n }\n continue\n }\n // If we got this far, the spec type is one of tag, directory or file\n // which means we have no real way to make version comparisons, so we\n // just accept the override.\n return rule\n }\n return this\n }\n\n // Patch adding isEqual is based on\n // https://github.com/npm/cli/pull/8089.\n override isEqual(otherOverrideSet: SafeOverrideSet | undefined): boolean {\n if (this === otherOverrideSet) {\n return true\n }\n if (!otherOverrideSet) {\n return false\n }\n if (\n this.key !== otherOverrideSet.key ||\n this.value !== otherOverrideSet.value\n ) {\n return false\n }\n if (!this.childrenAreEqual(otherOverrideSet)) {\n return false\n }\n if (!this.parent) {\n return !otherOverrideSet.parent\n }\n return this.parent.isEqual(otherOverrideSet.parent)\n }\n}\n","import semver from 'semver'\n\nimport { SafeOverrideSet } from './override-set'\nimport { getArboristNodeClassPath } from '../../paths'\nimport { getLogger } from '../../proc-log'\n\nimport type { SafeEdge } from './edge'\nimport type { Node as BaseNode, Link } from '@npmcli/arborist'\n\ntype NodeClass = Omit<\n BaseNode,\n | 'addEdgeIn'\n | 'addEdgeOut'\n | 'canDedupe'\n | 'canReplace'\n | 'canReplaceWith'\n | 'children'\n | 'deleteEdgeIn'\n | 'edgesIn'\n | 'edgesOut'\n | 'from'\n | 'hasShrinkwrap'\n | 'inDepBundle'\n | 'inShrinkwrap'\n | 'integrity'\n | 'isTop'\n | 'matches'\n | 'meta'\n | 'name'\n | 'overrides'\n | 'packageName'\n | 'parent'\n | 'recalculateOutEdgesOverrides'\n | 'resolve'\n | 'resolveParent'\n | 'root'\n | 'updateOverridesEdgeInAdded'\n | 'updateOverridesEdgeInRemoved'\n | 'version'\n | 'versions'\n> & {\n name: string\n version: string\n children: Map<string, SafeNode | Link>\n edgesIn: Set<SafeEdge>\n edgesOut: Map<string, SafeEdge>\n from: SafeNode | null\n hasShrinkwrap: boolean\n inShrinkwrap: boolean | undefined\n integrity?: string | null\n isTop: boolean | undefined\n meta: BaseNode['meta'] & {\n addEdge(edge: SafeEdge): void\n }\n overrides: SafeOverrideSet | undefined\n versions: string[]\n get inDepBundle(): boolean\n get packageName(): string | null\n get parent(): SafeNode | null\n set parent(value: SafeNode | null)\n get resolveParent(): SafeNode | null\n get root(): SafeNode | null\n set root(value: SafeNode | null)\n new (...args: any): NodeClass\n addEdgeIn(edge: SafeEdge): void\n addEdgeOut(edge: SafeEdge): void\n canDedupe(preferDedupe?: boolean): boolean\n canReplace(node: SafeNode, ignorePeers?: string[]): boolean\n canReplaceWith(node: SafeNode, ignorePeers?: string[]): boolean\n deleteEdgeIn(edge: SafeEdge): void\n matches(node: SafeNode): boolean\n recalculateOutEdgesOverrides(): void\n resolve(name: string): SafeNode\n updateOverridesEdgeInAdded(\n otherOverrideSet: SafeOverrideSet | undefined\n ): boolean\n updateOverridesEdgeInRemoved(otherOverrideSet: SafeOverrideSet): boolean\n}\n\nconst Node: NodeClass = require(getArboristNodeClassPath())\n\n// Implementation code not related to patch https://github.com/npm/cli/pull/8089\n// is based on https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/node.js:\nexport class SafeNode extends Node {\n // Return true if it's safe to remove this node, because anything that is\n // depending on it would be fine with the thing that they would resolve to if\n // it was removed, or nothing is depending on it in the first place.\n override canDedupe(preferDedupe = false) {\n // Not allowed to mess with shrinkwraps or bundles.\n if (this.inDepBundle || this.inShrinkwrap) {\n return false\n }\n // It's a top level pkg, or a dep of one.\n if (!this.resolveParent?.resolveParent) {\n return false\n }\n // No one wants it, remove it.\n if (this.edgesIn.size === 0) {\n return true\n }\n const other = this.resolveParent.resolveParent.resolve(this.name)\n // Nothing else, need this one.\n if (!other) {\n return false\n }\n // If it's the same thing, then always fine to remove.\n if (other.matches(this)) {\n return true\n }\n // If the other thing can't replace this, then skip it.\n if (!other.canReplace(this)) {\n return false\n }\n // Patch replacing\n // if (preferDedupe || semver.gte(other.version, this.version)) {\n // return true\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // If we prefer dedupe, or if the version is equal, take the other.\n if (preferDedupe || semver.eq(other.version, this.version)) {\n return true\n }\n // If our current version isn't the result of an override, then prefer to\n // take the greater version.\n if (!this.overridden && semver.gt(other.version, this.version)) {\n return true\n }\n return false\n }\n\n // Is it safe to replace one node with another? check the edges to\n // make sure no one will get upset. Note that the node might end up\n // having its own unmet dependencies, if the new node has new deps.\n // Note that there are cases where Arborist will opt to insert a node\n // into the tree even though this function returns false! This is\n // necessary when a root dependency is added or updated, or when a\n // root dependency brings peer deps along with it. In that case, we\n // will go ahead and create the invalid state, and then try to resolve\n // it with more tree construction, because it's a user request.\n override canReplaceWith(node: SafeNode, ignorePeers?: string[]): boolean {\n if (this.name !== node.name || this.packageName !== node.packageName) {\n return false\n }\n // Patch replacing\n // if (node.overrides !== this.overrides) {\n // return false\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // If this node has no dependencies, then it's irrelevant to check the\n // override rules of the replacement node.\n if (this.edgesOut.size) {\n // XXX need to check for two root nodes?\n if (node.overrides) {\n if (!node.overrides.isEqual(this.overrides)) {\n return false\n }\n } else {\n if (this.overrides) {\n return false\n }\n }\n }\n // To satisfy the patch we ensure `node.overrides === this.overrides`\n // so that the condition we want to replace,\n // if (this.overrides !== node.overrides) {\n // , is not hit.`\n const oldOverrideSet = this.overrides\n let result = true\n if (oldOverrideSet !== node.overrides) {\n this.overrides = node.overrides\n }\n try {\n result = super.canReplaceWith(node, ignorePeers)\n this.overrides = oldOverrideSet\n } catch (e) {\n this.overrides = oldOverrideSet\n throw e\n }\n return result\n }\n\n // Patch adding deleteEdgeIn is based on https://github.com/npm/cli/pull/8089.\n override deleteEdgeIn(edge: SafeEdge) {\n this.edgesIn.delete(edge)\n const { overrides } = edge\n if (overrides) {\n this.updateOverridesEdgeInRemoved(overrides)\n }\n }\n\n override addEdgeIn(edge: SafeEdge): void {\n // Patch replacing\n // if (edge.overrides) {\n // this.overrides = edge.overrides\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // We need to handle the case where the new edge in has an overrides field\n // which is different from the current value.\n if (!this.overrides || !this.overrides.isEqual(edge.overrides)) {\n this.updateOverridesEdgeInAdded(edge.overrides)\n }\n this.edgesIn.add(edge)\n // Try to get metadata from the yarn.lock file.\n this.root.meta?.addEdge(edge)\n }\n\n // @ts-ignore: Incorrectly typed as a property instead of an accessor.\n override get overridden() {\n // Patch replacing\n // return !!(this.overrides && this.overrides.value && this.overrides.name === this.name)\n // is based on https://github.com/npm/cli/pull/8089.\n if (\n !this.overrides ||\n !this.overrides.value ||\n this.overrides.name !== this.name\n ) {\n return false\n }\n // The overrides rule is for a package with this name, but some override\n // rules only apply to specific versions. To make sure this package was\n // actually overridden, we check whether any edge going in had the rule\n // applied to it, in which case its overrides set is different than its\n // source node.\n for (const edge of this.edgesIn) {\n if (\n edge.overrides &&\n edge.overrides.name === this.name &&\n edge.overrides.value === this.version\n ) {\n if (!edge.overrides.isEqual(edge.from?.overrides)) {\n return true\n }\n }\n }\n return false\n }\n\n override set parent(newParent: SafeNode) {\n // Patch removing\n // if (parent.overrides) {\n // this.overrides = parent.overrides.getNodeRule(this)\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // The \"parent\" setter is a really large and complex function. To satisfy\n // the patch we hold on to the old overrides value and set `this.overrides`\n // to `undefined` so that the condition we want to remove is not hit.\n const { overrides } = this\n if (overrides) {\n this.overrides = undefined\n }\n try {\n super.parent = newParent\n this.overrides = overrides\n } catch (e) {\n this.overrides = overrides\n throw e\n }\n }\n\n // Patch adding recalculateOutEdgesOverrides is based on\n // https://github.com/npm/cli/pull/8089.\n override recalculateOutEdgesOverrides() {\n // For each edge out propagate the new overrides through.\n for (const edge of this.edgesOut.values()) {\n edge.reload(true)\n if (edge.to) {\n edge.to.updateOverridesEdgeInAdded(edge.overrides)\n }\n }\n }\n\n // @ts-ignore: Incorrectly typed to accept null.\n override set root(newRoot: SafeNode) {\n // Patch removing\n // if (!this.overrides && this.parent && this.parent.overrides) {\n // this.overrides = this.parent.overrides.getNodeRule(this)\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // The \"root\" setter is a really large and complex function. To satisfy the\n // patch we add a dummy value to `this.overrides` so that the condition we\n // want to remove is not hit.\n if (!this.overrides) {\n this.overrides = new SafeOverrideSet({ overrides: '' })\n }\n try {\n super.root = newRoot\n this.overrides = undefined\n } catch (e) {\n this.overrides = undefined\n throw e\n }\n }\n\n // Patch adding updateOverridesEdgeInAdded is based on\n // https://github.com/npm/cli/pull/7025.\n //\n // This logic isn't perfect either. When we have two edges in that have\n // different override sets, then we have to decide which set is correct. This\n // function assumes the more specific override set is applicable, so if we have\n // dependencies A->B->C and A->C and an override set that specifies what happens\n // for C under A->B, this will work even if the new A->C edge comes along and\n // tries to change the override set. The strictly correct logic is not to allow\n // two edges with different overrides to point to the same node, because even\n // if this node can satisfy both, one of its dependencies might need to be\n // different depending on the edge leading to it. However, this might cause a\n // lot of duplication, because the conflict in the dependencies might never\n // actually happen.\n override updateOverridesEdgeInAdded(\n otherOverrideSet: SafeOverrideSet | undefined\n ) {\n if (!otherOverrideSet) {\n // Assuming there are any overrides at all, the overrides field is never\n // undefined for any node at the end state of the tree. So if the new edge's\n // overrides is undefined it will be updated later. So we can wait with\n // updating the node's overrides field.\n return false\n }\n if (!this.overrides) {\n this.overrides = otherOverrideSet\n this.recalculateOutEdgesOverrides()\n return true\n }\n if (this.overrides.isEqual(otherOverrideSet)) {\n return false\n }\n const newOverrideSet = SafeOverrideSet.findSpecificOverrideSet(\n this.overrides,\n otherOverrideSet\n )\n if (newOverrideSet) {\n if (this.overrides.isEqual(newOverrideSet)) {\n return false\n }\n this.overrides = newOverrideSet\n this.recalculateOutEdgesOverrides()\n return true\n }\n // This is an error condition. We can only get here if the new override set\n // is in conflict with the existing.\n const log = getLogger()\n log?.silly('Conflicting override sets', this.name)\n return false\n }\n\n // Patch adding updateOverridesEdgeInRemoved is based on\n // https://github.com/npm/cli/pull/7025.\n override updateOverridesEdgeInRemoved(otherOverrideSet: SafeOverrideSet) {\n // If this edge's overrides isn't equal to this node's overrides,\n // then removing it won't change newOverrideSet later.\n if (!this.overrides || !this.overrides.isEqual(otherOverrideSet)) {\n return false\n }\n let newOverrideSet\n for (const edge of this.edgesIn) {\n const { overrides: edgeOverrides } = edge\n if (newOverrideSet && edgeOverrides) {\n newOverrideSet = SafeOverrideSet.findSpecificOverrideSet(\n edgeOverrides,\n newOverrideSet\n )\n } else {\n newOverrideSet = edgeOverrides\n }\n }\n if (this.overrides.isEqual(newOverrideSet)) {\n return false\n }\n this.overrides = newOverrideSet\n if (newOverrideSet) {\n // Optimization: If there's any override set at all, then no non-extraneous\n // node has an empty override set. So if we temporarily have no override set\n // (for example, we removed all the edges in), there's no use updating all\n // the edges out right now. Let's just wait until we have an actual override\n // set later.\n this.recalculateOutEdgesOverrides()\n }\n return true\n }\n}\n","import { depValid } from './dep-valid'\nimport { SafeNode } from './node'\nimport { SafeOverrideSet } from './override-set'\nimport { getArboristEdgeClassPath } from '../../paths'\n\nimport type { Edge as BaseEdge, DependencyProblem } from '@npmcli/arborist'\n\ntype EdgeClass = Omit<\n BaseEdge,\n | 'accept'\n | 'detach'\n | 'optional'\n | 'overrides'\n | 'peer'\n | 'peerConflicted'\n | 'rawSpec'\n | 'reload'\n | 'satisfiedBy'\n | 'spec'\n | 'to'\n> & {\n optional: boolean\n overrides: SafeOverrideSet | undefined\n peer: boolean\n peerConflicted: boolean\n rawSpec: string\n get accept(): string | undefined\n get spec(): string\n get to(): SafeNode | null\n new (...args: any): EdgeClass\n detach(): void\n reload(hard?: boolean): void\n satisfiedBy(node: SafeNode): boolean\n}\n\nexport type EdgeOptions = {\n type: string\n name: string\n spec: string\n from: SafeNode\n accept?: string | undefined\n overrides?: SafeOverrideSet | undefined\n to?: SafeNode | undefined\n}\n\nexport type ErrorStatus = DependencyProblem | 'OK'\n\nexport type Explanation = {\n type: string\n name: string\n spec: string\n bundled: boolean\n overridden: boolean\n error: ErrorStatus | undefined\n rawSpec: string | undefined\n from: object | undefined\n} | null\n\nexport const Edge: EdgeClass = require(getArboristEdgeClassPath())\n\n// The Edge class makes heavy use of private properties which subclasses do NOT\n// have access to. So we have to recreate any functionality that relies on those\n// private properties and use our own \"safe\" prefixed non-conflicting private\n// properties. Implementation code not related to patch https://github.com/npm/cli/pull/8089\n// is based on https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/edge.js.\n//\n// The npm application\n// Copyright (c) npm, Inc. and Contributors\n// Licensed on the terms of The Artistic License 2.0\n//\n// An edge in the dependency graph.\n// Represents a dependency relationship of some kind.\nexport class SafeEdge extends Edge {\n #safeError: ErrorStatus | null\n #safeExplanation: Explanation | undefined\n #safeFrom: SafeNode | null\n #safeTo: SafeNode | null\n\n constructor(options: EdgeOptions) {\n const { from } = options\n // Defer to supper to validate options and assign non-private values.\n super(options)\n if (from.constructor !== SafeNode) {\n Reflect.setPrototypeOf(from, SafeNode.prototype)\n }\n this.#safeError = null\n this.#safeExplanation = null\n this.#safeFrom = from\n this.#safeTo = null\n this.reload(true)\n }\n\n override get bundled() {\n return !!this.#safeFrom?.package?.bundleDependencies?.includes(this.name)\n }\n\n override get error() {\n if (!this.#safeError) {\n if (!this.#safeTo) {\n if (this.optional) {\n this.#safeError = null\n } else {\n this.#safeError = 'MISSING'\n }\n } else if (\n this.peer &&\n this.#safeFrom === this.#safeTo.parent &&\n // Patch adding \"?.\" use based on\n // https://github.com/npm/cli/pull/8089.\n !this.#safeFrom?.isTop\n ) {\n this.#safeError = 'PEER LOCAL'\n } else if (!this.satisfiedBy(this.#safeTo)) {\n this.#safeError = 'INVALID'\n }\n // Patch adding \"else if\" condition is based on\n // https://github.com/npm/cli/pull/8089.\n else if (\n this.overrides &&\n this.#safeTo.edgesOut.size &&\n SafeOverrideSet.doOverrideSetsConflict(\n this.overrides,\n this.#safeTo.overrides\n )\n ) {\n // Any inconsistency between the edge's override set and the target's\n // override set is potentially problematic. But we only say the edge is\n // in error if the override sets are plainly conflicting. Note that if\n // the target doesn't have any dependencies of their own, then this\n // inconsistency is irrelevant.\n this.#safeError = 'INVALID'\n } else {\n this.#safeError = 'OK'\n }\n }\n if (this.#safeError === 'OK') {\n return null\n }\n return this.#safeError\n }\n\n // @ts-ignore: Incorrectly typed as a property instead of an accessor.\n override get from() {\n return this.#safeFrom\n }\n\n // @ts-ignore: Incorrectly typed as a property instead of an accessor.\n override get spec(): string {\n if (\n this.overrides?.value &&\n this.overrides.value !== '*' &&\n this.overrides.name === this.name\n ) {\n if (this.overrides.value.startsWith('$')) {\n const ref = this.overrides.value.slice(1)\n // We may be a virtual root, if we are we want to resolve reference\n // overrides from the real root, not the virtual one.\n //\n // Patch adding \"?.\" use based on\n // https://github.com/npm/cli/pull/8089.\n const pkg = this.#safeFrom?.sourceReference\n ? this.#safeFrom?.sourceReference.root.package\n : this.#safeFrom?.root?.package\n if (pkg?.devDependencies?.[ref]) {\n return pkg.devDependencies[ref] as string\n }\n if (pkg?.optionalDependencies?.[ref]) {\n return pkg.optionalDependencies[ref] as string\n }\n if (pkg?.dependencies?.[ref]) {\n return pkg.dependencies[ref] as string\n }\n if (pkg?.peerDependencies?.[ref]) {\n return pkg.peerDependencies[ref] as string\n }\n throw new Error(`Unable to resolve reference ${this.overrides.value}`)\n }\n return this.overrides.value\n }\n return this.rawSpec\n }\n\n // @ts-ignore: Incorrectly typed as a property instead of an accessor.\n override get to() {\n return this.#safeTo\n }\n\n override detach() {\n this.#safeExplanation = null\n // Patch replacing\n // if (this.#to) {\n // this.#to.edgesIn.delete(this)\n // }\n // this.#from.edgesOut.delete(this.#name)\n // is based on https://github.com/npm/cli/pull/8089.\n this.#safeTo?.deleteEdgeIn(this)\n this.#safeFrom?.edgesOut.delete(this.name)\n this.#safeTo = null\n this.#safeError = 'DETACHED'\n this.#safeFrom = null\n }\n\n // Return the edge data, and an explanation of how that edge came to be here.\n // @ts-ignore: Edge#explain is defined with an unused `seen = []` param.\n override explain() {\n if (!this.#safeExplanation) {\n const explanation: Explanation = {\n type: this.type,\n name: this.name,\n spec: this.spec,\n bundled: false,\n overridden: false,\n error: undefined,\n from: undefined,\n rawSpec: undefined\n }\n if (this.rawSpec !== this.spec) {\n explanation.rawSpec = this.rawSpec\n explanation.overridden = true\n }\n if (this.bundled) {\n explanation.bundled = this.bundled\n }\n if (this.error) {\n explanation.error = this.error\n }\n if (this.#safeFrom) {\n explanation.from = this.#safeFrom.explain()\n }\n this.#safeExplanation = explanation\n }\n return this.#safeExplanation\n }\n\n override reload(hard = false) {\n this.#safeExplanation = null\n // Patch replacing\n // if (this.#from.overrides) {\n // is based on https://github.com/npm/cli/pull/8089.\n let needToUpdateOverrideSet = false\n let newOverrideSet\n let oldOverrideSet\n if (this.#safeFrom?.overrides) {\n newOverrideSet = this.#safeFrom.overrides.getEdgeRule(this)\n if (newOverrideSet && !newOverrideSet.isEqual(this.overrides)) {\n // If there's a new different override set we need to propagate it to\n // the nodes. If we're deleting the override set then there's no point\n // propagating it right now since it will be filled with another value\n // later.\n needToUpdateOverrideSet = true\n oldOverrideSet = this.overrides\n this.overrides = newOverrideSet\n }\n } else {\n this.overrides = undefined\n }\n // Patch adding \"?.\" use based on\n // https://github.com/npm/cli/pull/8089.\n const newTo = this.#safeFrom?.resolve(this.name)\n if (newTo !== this.#safeTo) {\n // Patch replacing\n // this.#to.edgesIn.delete(this)\n // is based on https://github.com/npm/cli/pull/8089.\n this.#safeTo?.deleteEdgeIn(this)\n this.#safeTo = (newTo as SafeNode) ?? null\n this.#safeError = null\n this.#safeTo?.addEdgeIn(this)\n } else if (hard) {\n this.#safeError = null\n }\n // Patch adding \"else if\" condition based on\n // https://github.com/npm/cli/pull/8089.\n else if (needToUpdateOverrideSet && this.#safeTo) {\n // Propagate the new override set to the target node.\n this.#safeTo.updateOverridesEdgeInRemoved(oldOverrideSet!)\n this.#safeTo.updateOverridesEdgeInAdded(newOverrideSet)\n }\n }\n\n override satisfiedBy(node: SafeNode) {\n // Patch replacing\n // if (node.name !== this.#name) {\n // return false\n // }\n // is based on https://github.com/npm/cli/pull/8089.\n if (node.name !== this.name || !this.#safeFrom) {\n return false\n }\n // NOTE: this condition means we explicitly do not support overriding\n // bundled or shrinkwrapped dependencies\n if (node.hasShrinkwrap || node.inShrinkwrap || node.inBundle) {\n return depValid(node, this.rawSpec, this.accept, this.#safeFrom)\n }\n // Patch replacing\n // return depValid(node, this.spec, this.#accept, this.#from)\n // is based on https://github.com/npm/cli/pull/8089.\n //\n // If there's no override we just use the spec.\n if (!this.overrides?.keySpec) {\n return depValid(node, this.spec, this.accept, this.#safeFrom)\n }\n // There's some override. If the target node satisfies the overriding spec\n // then it's okay.\n if (depValid(node, this.spec, this.accept, this.#safeFrom)) {\n return true\n }\n // If it doesn't, then it should at least satisfy the original spec.\n if (!depValid(node, this.rawSpec, this.accept, this.#safeFrom)) {\n return false\n }\n // It satisfies the original spec, not the overriding spec. We need to make\n // sure it doesn't use the overridden spec.\n // For example:\n // we might have an ^8.0.0 rawSpec, and an override that makes\n // keySpec=8.23.0 and the override value spec=9.0.0.\n // If the node is 9.0.0, then it's okay because it's consistent with spec.\n // If the node is 8.24.0, then it's okay because it's consistent with the rawSpec.\n // If the node is 8.23.0, then it's not okay because even though it's consistent\n // with the rawSpec, it's also consistent with the keySpec.\n // So we're looking for ^8.0.0 or 9.0.0 and not 8.23.0.\n return !depValid(node, this.overrides.keySpec, this.accept, this.#safeFrom)\n }\n}\n","import constants from '../../constants'\n\nimport type { Remap } from '@socketsecurity/registry/lib/objects'\nimport type { components } from '@socketsecurity/sdk/types/api'\n\nexport type ArtifactAlertCve = Remap<\n Omit<CompactSocketArtifactAlert, 'type'> & {\n type: CveAlertType\n }\n>\n\nexport type ArtifactAlertCveFixable = Remap<\n Omit<CompactSocketArtifactAlert, 'props' | 'type'> & {\n type: CveAlertType\n props: {\n firstPatchedVersionIdentifier: string\n vulnerableVersionRange: string\n [key: string]: any\n }\n }\n>\n\nexport type ArtifactAlertUpgrade = Remap<\n Omit<CompactSocketArtifactAlert, 'type'> & {\n type: 'socketUpgradeAvailable'\n }\n>\n\nexport type CveAlertType = 'cve' | 'mediumCVE' | 'mildCVE' | 'criticalCVE'\n\nexport type CompactSocketArtifactAlert = Remap<\n Omit<\n SocketArtifactAlert,\n 'action' | 'actionPolicyIndex' | 'category' | 'end' | 'file' | 'start'\n >\n>\n\nexport type CompactSocketArtifact = Remap<\n Omit<SocketArtifact, 'alerts' | 'batchIndex' | 'size'> & {\n alerts: CompactSocketArtifactAlert[]\n }\n>\n\nexport type SocketArtifact = components['schemas']['SocketArtifact']\n\nexport type SocketArtifactAlert = Remap<\n Omit<components['schemas']['SocketAlert'], 'props'> & {\n props?: any | undefined\n }\n>\n\nconst {\n ALERT_TYPE_CRITICAL_CVE,\n ALERT_TYPE_CVE,\n ALERT_TYPE_MEDIUM_CVE,\n ALERT_TYPE_MILD_CVE\n} = constants\n\nexport function isArtifactAlertCve(\n alert: CompactSocketArtifactAlert\n): alert is ArtifactAlertCve {\n const { type } = alert\n return (\n type === ALERT_TYPE_CVE ||\n type === ALERT_TYPE_MEDIUM_CVE ||\n type === ALERT_TYPE_MILD_CVE ||\n type === ALERT_TYPE_CRITICAL_CVE\n )\n}\n","export enum ALERT_FIX_TYPE {\n cve = 'cve',\n upgrade = 'upgrade'\n}\n","import { isObject } from '@socketsecurity/registry/lib/objects'\n\nimport { isErrnoException } from '../errors'\nimport { getPublicToken, setupSdk } from '../sdk'\nimport { findSocketYmlSync, getSetting } from '../settings'\n\nimport type { SocketSdkResultType } from '@socketsecurity/sdk'\n\ntype AlertUxLookup = ReturnType<typeof createAlertUXLookup>\n\ntype AlertUxLookupSettings = Parameters<AlertUxLookup>[0]\n\ntype AlertUxLookupResult = ReturnType<AlertUxLookup>\n\ntype NonNormalizedRule =\n | NonNullable<\n NonNullable<\n NonNullable<\n (SocketSdkResultType<'postSettings'> & {\n success: true\n })['data']['entries'][number]['settings'][string]\n >['issueRules']\n >\n >[string]\n | boolean\n\ntype NonNormalizedResolvedRule =\n | (NonNullable<\n NonNullable<\n (SocketSdkResultType<'postSettings'> & {\n success: true\n })['data']['defaults']['issueRules']\n >[string]\n > & { action: string })\n | boolean\n\ntype RuleActionUX = { block: boolean; display: boolean }\n\nconst ERROR_UX: RuleActionUX = {\n block: true,\n display: true\n}\n\nconst IGNORE_UX: RuleActionUX = {\n block: false,\n display: false\n}\n\nconst WARN_UX: RuleActionUX = {\n block: false,\n display: true\n}\n\n// Iterates over all entries with ordered issue rule for deferral. Iterates over\n// all issue rules and finds the first defined value that does not defer otherwise\n// uses the defaultValue. Takes the value and converts into a UX workflow.\nfunction resolveAlertRuleUX(\n orderedRulesCollection: Iterable<Iterable<NonNormalizedRule>>,\n defaultValue: NonNormalizedResolvedRule\n): RuleActionUX {\n if (\n defaultValue === true ||\n defaultValue === null ||\n defaultValue === undefined\n ) {\n defaultValue = { action: 'error' }\n } else if (defaultValue === false) {\n defaultValue = { action: 'ignore' }\n }\n let block = false\n let display = false\n let needDefault = true\n iterate_entries: for (const rules of orderedRulesCollection) {\n for (const rule of rules) {\n if (ruleValueDoesNotDefer(rule)) {\n needDefault = false\n const narrowingFilter = uxForDefinedNonDeferValue(rule)\n block = block || narrowingFilter.block\n display = display || narrowingFilter.display\n continue iterate_entries\n }\n }\n const narrowingFilter = uxForDefinedNonDeferValue(defaultValue)\n block = block || narrowingFilter.block\n display = display || narrowingFilter.display\n }\n if (needDefault) {\n const narrowingFilter = uxForDefinedNonDeferValue(defaultValue)\n block = block || narrowingFilter.block\n display = display || narrowingFilter.display\n }\n return { block, display }\n}\n\n// Negative form because it is narrowing the type.\nfunction ruleValueDoesNotDefer(\n rule: NonNormalizedRule\n): rule is NonNormalizedResolvedRule {\n if (rule === undefined) {\n return false\n }\n if (isObject(rule)) {\n const { action } = rule\n if (action === undefined || action === 'defer') {\n return false\n }\n }\n return true\n}\n\n// Handles booleans for backwards compatibility.\nfunction uxForDefinedNonDeferValue(\n ruleValue: NonNormalizedResolvedRule\n): RuleActionUX {\n if (typeof ruleValue === 'boolean') {\n return ruleValue ? ERROR_UX : IGNORE_UX\n }\n const { action } = ruleValue\n if (action === 'warn') {\n return WARN_UX\n } else if (action === 'ignore') {\n return IGNORE_UX\n }\n return ERROR_UX\n}\n\ntype SettingsType = (SocketSdkResultType<'postSettings'> & {\n success: true\n})['data']\n\nexport function createAlertUXLookup(settings: SettingsType): (context: {\n package: { name: string; version: string }\n alert: { type: string }\n}) => RuleActionUX {\n const cachedUX: Map<keyof typeof settings.defaults.issueRules, RuleActionUX> =\n new Map()\n return context => {\n const { type } = context.alert\n let ux = cachedUX.get(type)\n if (ux) {\n return ux\n }\n const orderedRulesCollection: NonNormalizedRule[][] = []\n for (const settingsEntry of settings.entries) {\n const orderedRules: NonNormalizedRule[] = []\n let target = settingsEntry.start\n while (target !== null) {\n const resolvedTarget = settingsEntry.settings[target]\n if (!resolvedTarget) {\n break\n }\n const issueRuleValue = resolvedTarget.issueRules?.[type]\n if (typeof issueRuleValue !== 'undefined') {\n orderedRules.push(issueRuleValue)\n }\n target = resolvedTarget.deferTo ?? null\n }\n orderedRulesCollection.push(orderedRules)\n }\n const defaultValue = settings.defaults.issueRules[type] as\n | { action: 'error' | 'ignore' | 'warn' }\n | boolean\n | undefined\n let resolvedDefaultValue: NonNormalizedResolvedRule = {\n action: 'error'\n }\n if (defaultValue === false) {\n resolvedDefaultValue = { action: 'ignore' }\n } else if (defaultValue && defaultValue !== true) {\n resolvedDefaultValue = { action: defaultValue.action ?? 'error' }\n }\n ux = resolveAlertRuleUX(orderedRulesCollection, resolvedDefaultValue)\n cachedUX.set(type, ux)\n return ux\n }\n}\n\nlet _uxLookup: AlertUxLookup | undefined\nexport async function uxLookup(\n settings: AlertUxLookupSettings\n): Promise<AlertUxLookupResult> {\n if (_uxLookup === undefined) {\n const { orgs, settings } = await (async () => {\n try {\n const sockSdk = await setupSdk(getPublicToken())\n const orgResult = await sockSdk.getOrganizations()\n if (!orgResult.success) {\n if (orgResult.status === 429) {\n throw new Error(`API token quota exceeded: ${orgResult.error}`)\n }\n throw new Error(\n `Failed to fetch Socket organization info: ${orgResult.error}`\n )\n }\n const { organizations } = orgResult.data\n const orgs: Array<Exclude<(typeof organizations)[string], undefined>> =\n []\n for (const org of Object.values(organizations)) {\n if (org) {\n orgs.push(org)\n }\n }\n const settingsResult = await sockSdk.postSettings(\n orgs.map(org => ({ organization: org.id }))\n )\n if (!settingsResult.success) {\n throw new Error(\n `Failed to fetch API key settings: ${settingsResult.error}`\n )\n }\n return {\n orgs,\n settings: settingsResult.data\n }\n } catch (e) {\n const cause = isObject(e) && 'cause' in e ? e['cause'] : undefined\n if (\n isErrnoException(cause) &&\n (cause.code === 'ENOTFOUND' || cause.code === 'ECONNREFUSED')\n ) {\n throw new Error(\n 'Unable to connect to socket.dev, ensure internet connectivity before retrying',\n {\n cause: e\n }\n )\n }\n throw e\n }\n })()\n // Remove any organizations not being enforced.\n const enforcedOrgs = getSetting('enforcedOrgs') ?? []\n for (const { 0: i, 1: org } of orgs.entries()) {\n if (!enforcedOrgs.includes(org.id)) {\n settings.entries.splice(i, 1)\n }\n }\n const socketYml = findSocketYmlSync()\n if (socketYml) {\n settings.entries.push({\n start: socketYml.path,\n settings: {\n [socketYml.path]: {\n deferTo: null,\n // TODO: TypeScript complains about the type not matching. We should\n // figure out why are providing\n // issueRules: { [issueName: string]: boolean }\n // but expecting\n // issueRules: { [issueName: string]: { action: 'defer' | 'error' | 'ignore' | 'monitor' | 'warn' } }\n issueRules: socketYml.parsed.issueRules as unknown as {\n [key: string]: {\n action: 'defer' | 'error' | 'ignore' | 'monitor' | 'warn'\n }\n }\n }\n }\n })\n }\n _uxLookup = createAlertUXLookup(settings)\n }\n return _uxLookup(settings)\n}\n","export function pick<T extends Record<string, any>, K extends keyof T>(\n input: T,\n keys: K[] | readonly K[]\n): Pick<T, K> {\n const result: Partial<Pick<T, K>> = {}\n for (const key of keys) {\n result[key] = input[key]\n }\n return result as Pick<T, K>\n}\n","export function stringJoinWithSeparateFinalSeparator(\n list: string[],\n separator: string = ' and '\n): string {\n const values = list.filter(Boolean)\n const { length } = values\n if (!length) {\n return ''\n }\n if (length === 1) {\n return values[0]!\n }\n const finalValue = values.pop()\n return `${values.join(', ')}${separator}${finalValue}`\n}\n","import { pick } from '../objects'\nimport { stringJoinWithSeparateFinalSeparator } from '../strings'\n\nimport type { SocketSdkReturnType } from '@socketsecurity/sdk'\n\nexport enum ALERT_SEVERITY {\n critical = 'critical',\n high = 'high',\n middle = 'middle',\n low = 'low'\n}\n\nexport type SocketSdkAlertList =\n SocketSdkReturnType<'getIssuesByNPMPackage'>['data']\n\nexport type SocketSdkAlert = SocketSdkAlertList[number]['value'] extends\n | infer U\n | undefined\n ? U\n : never\n\n// Ordered from most severe to least.\nconst SEVERITIES_BY_ORDER: ReadonlyArray<SocketSdkAlert['severity']> =\n Object.freeze(['critical', 'high', 'middle', 'low'])\n\nfunction getDesiredSeverities(\n lowestToInclude: SocketSdkAlert['severity'] | undefined\n): Array<SocketSdkAlert['severity']> {\n const result: Array<SocketSdkAlert['severity']> = []\n for (const severity of SEVERITIES_BY_ORDER) {\n result.push(severity)\n if (severity === lowestToInclude) {\n break\n }\n }\n return result\n}\n\nexport function formatSeverityCount(\n severityCount: Record<SocketSdkAlert['severity'], number>\n): string {\n const summary: string[] = []\n for (const severity of SEVERITIES_BY_ORDER) {\n if (severityCount[severity]) {\n summary.push(`${severityCount[severity]} ${severity}`)\n }\n }\n return stringJoinWithSeparateFinalSeparator(summary)\n}\n\nexport function getSeverityCount(\n issues: SocketSdkAlertList,\n lowestToInclude: SocketSdkAlert['severity'] | undefined\n): Record<SocketSdkAlert['severity'], number> {\n const severityCount = pick(\n { low: 0, middle: 0, high: 0, critical: 0 },\n getDesiredSeverities(lowestToInclude)\n ) as Record<SocketSdkAlert['severity'], number>\n\n for (const issue of issues) {\n const { value } = issue\n if (!value) {\n continue\n }\n const { severity } = value\n if (severityCount[severity] !== undefined) {\n severityCount[severity] += 1\n }\n }\n return severityCount\n}\n","import terminalLink from 'terminal-link'\nimport colors from 'yoctocolors-cjs'\n\nimport indentString from '@socketregistry/indent-string/index.cjs'\n\nexport class ColorOrMarkdown {\n public useMarkdown: boolean\n\n constructor(useMarkdown: boolean) {\n this.useMarkdown = !!useMarkdown\n }\n\n bold(text: string): string {\n return this.useMarkdown ? `**${text}**` : colors.bold(`${text}`)\n }\n\n header(text: string, level = 1): string {\n return this.useMarkdown\n ? `\\n${''.padStart(level, '#')} ${text}\\n`\n : colors.underline(`\\n${level === 1 ? colors.bold(text) : text}\\n`)\n }\n\n hyperlink(\n text: string,\n url: string | undefined,\n {\n fallback = true,\n fallbackToUrl\n }: {\n fallback?: boolean | undefined\n fallbackToUrl?: boolean | undefined\n } = {}\n ) {\n if (url) {\n return this.useMarkdown\n ? `[${text}](${url})`\n : terminalLink(text, url, {\n fallback: fallbackToUrl ? (_text, url) => url : fallback\n })\n }\n return text\n }\n\n indent(\n ...args: Parameters<typeof indentString>\n ): ReturnType<typeof indentString> {\n return indentString(...args)\n }\n\n italic(text: string): string {\n return this.useMarkdown ? `_${text}_` : colors.italic(`${text}`)\n }\n\n json(value: any): string {\n return this.useMarkdown\n ? '```json\\n' + JSON.stringify(value) + '\\n```'\n : JSON.stringify(value)\n }\n\n list(items: string[]): string {\n const indentedContent = items.map(item => this.indent(item).trimStart())\n return this.useMarkdown\n ? `* ${indentedContent.join('\\n* ')}\\n`\n : `${indentedContent.join('\\n')}\\n`\n }\n}\n","export function getSocketDevAlertUrl(alertType: string): string {\n return `https://socket.dev/alerts/${alertType}`\n}\n\nexport function getSocketDevPackageOverviewUrl(\n eco: string,\n name: string,\n version?: string | undefined\n): string {\n return `https://socket.dev/${eco}/package/${name}${version ? `/overview/${version}` : ''}`\n}\n","import path from 'node:path'\n\nimport constants from '../constants'\n\nlet _translations: typeof import('../../translations.json') | undefined\n\nexport function getTranslations() {\n if (_translations === undefined) {\n _translations = require(\n // Lazily access constants.rootPath.\n path.join(constants.rootPath, 'translations.json')\n )\n }\n return _translations!\n}\n","import semver from 'semver'\n\nimport { PackageURL } from '@socketregistry/packageurl-js'\nimport { getManifestData } from '@socketsecurity/registry'\nimport { hasOwn } from '@socketsecurity/registry/lib/objects'\nimport { resolvePackageName } from '@socketsecurity/registry/lib/packages'\nimport { naturalCompare } from '@socketsecurity/registry/lib/sorts'\n\nimport { CompactSocketArtifact, isArtifactAlertCve } from './alert/artifact'\nimport { ALERT_FIX_TYPE } from './alert/fix'\nimport { uxLookup } from './alert/rules'\nimport { ALERT_SEVERITY } from './alert/severity'\nimport { ColorOrMarkdown } from './color-or-markdown'\nimport { getSocketDevPackageOverviewUrl } from './socket-url'\nimport { getTranslations } from './translations'\nimport constants from '../constants'\n\nimport type { Spinner } from '@socketsecurity/registry/lib/spinner'\n\nexport type SocketPackageAlert = {\n key: string\n type: string\n block: boolean\n critical: boolean\n display: boolean\n fixable: boolean\n raw: any\n upgrade: boolean\n}\n\nexport type AlertsByPkgId = Map<string, SocketPackageAlert[]>\n\nconst { CVE_ALERT_PROPS_FIRST_PATCHED_VERSION_IDENTIFIER, NPM } = constants\n\nconst format = new ColorOrMarkdown(false)\n\ntype AlertIncludeFilter = {\n critical?: boolean | undefined\n cve?: boolean | undefined\n existing?: boolean | undefined\n unfixable?: boolean | undefined\n upgrade?: boolean | undefined\n}\n\ntype AddSocketArtifactAlertToAlertsMapOptions = {\n consolidate?: boolean | undefined\n include?: AlertIncludeFilter | undefined\n overrides?: { [key: string]: string } | undefined\n spinner?: Spinner | undefined\n}\n\nexport async function addArtifactToAlertsMap<T extends AlertsByPkgId>(\n artifact: CompactSocketArtifact,\n alertsByPkgId: T,\n options?: AddSocketArtifactAlertToAlertsMapOptions | undefined\n): Promise<T> {\n // Make TypeScript happy.\n if (!artifact.name || !artifact.version || !artifact.alerts?.length) {\n return alertsByPkgId\n }\n const {\n consolidate = false,\n include: _include,\n overrides\n } = {\n __proto__: null,\n ...options\n } as AddSocketArtifactAlertToAlertsMapOptions\n\n const include = {\n __proto__: null,\n critical: true,\n cve: true,\n existing: false,\n unfixable: true,\n upgrade: false,\n ..._include\n } as AlertIncludeFilter\n\n const name = resolvePackageName(artifact)\n const { version } = artifact\n const pkgId = `${name}@${version}`\n const major = semver.major(version)\n let sockPkgAlerts = []\n for (const alert of artifact.alerts) {\n // eslint-disable-next-line no-await-in-loop\n const ux = await uxLookup({\n package: { name, version },\n alert: { type: alert.type }\n })\n const fixType = alert.fix?.type ?? ''\n const critical = alert.severity === ALERT_SEVERITY.critical\n const cve = isArtifactAlertCve(alert)\n const fixableCve = fixType === ALERT_FIX_TYPE.cve\n const fixableUpgrade = fixType === ALERT_FIX_TYPE.upgrade\n const fixable = fixableCve || fixableUpgrade\n const upgrade = fixableUpgrade && !hasOwn(overrides, name)\n if (\n (include.cve && cve) ||\n (include.unfixable && !fixable) ||\n (include.critical && critical) ||\n (include.upgrade && upgrade)\n ) {\n sockPkgAlerts.push({\n name,\n version,\n key: alert.key,\n type: alert.type,\n block: ux.block,\n critical,\n display: ux.display,\n fixable,\n raw: alert,\n upgrade\n })\n }\n }\n if (!sockPkgAlerts.length) {\n return alertsByPkgId\n }\n if (consolidate) {\n const highestForCve = new Map<\n number,\n { alert: SocketPackageAlert; version: string }\n >()\n const highestForUpgrade = new Map<\n number,\n { alert: SocketPackageAlert; version: string }\n >()\n const unfixableAlerts: SocketPackageAlert[] = []\n for (const sockPkgAlert of sockPkgAlerts) {\n const alert = sockPkgAlert.raw\n const fixType = alert.fix?.type ?? ''\n if (fixType === ALERT_FIX_TYPE.cve) {\n const patchedVersion =\n alert.props[CVE_ALERT_PROPS_FIRST_PATCHED_VERSION_IDENTIFIER]\n const patchedMajor = semver.major(patchedVersion)\n const oldHighest = highestForCve.get(patchedMajor)\n const highest = oldHighest?.version ?? '0.0.0'\n if (semver.gt(patchedVersion, highest)) {\n highestForCve.set(patchedMajor, {\n alert: sockPkgAlert,\n version: patchedVersion\n })\n }\n } else if (fixType === ALERT_FIX_TYPE.upgrade) {\n const oldHighest = highestForUpgrade.get(major)\n const highest = oldHighest?.version ?? '0.0.0'\n if (semver.gt(version, highest)) {\n highestForUpgrade.set(major, { alert: sockPkgAlert, version })\n }\n } else {\n unfixableAlerts.push(sockPkgAlert)\n }\n }\n sockPkgAlerts = [\n ...unfixableAlerts,\n ...[...highestForCve.values()].map(d => d.alert),\n ...[...highestForUpgrade.values()].map(d => d.alert)\n ]\n }\n if (sockPkgAlerts.length) {\n sockPkgAlerts.sort((a, b) => naturalCompare(a.type, b.type))\n alertsByPkgId.set(pkgId, sockPkgAlerts)\n }\n return alertsByPkgId\n}\n\ntype CveExcludeFilter = {\n upgrade?: boolean | undefined\n}\n\ntype CveInfoByPkgId = Map<\n string,\n Array<{\n firstPatchedVersionIdentifier: string\n vulnerableVersionRange: string\n }>\n>\n\ntype GetCveInfoByPackageOptions = {\n exclude?: CveExcludeFilter | undefined\n}\n\nexport function getCveInfoByAlertsMap(\n alertsMap: AlertsByPkgId,\n options?: GetCveInfoByPackageOptions | undefined\n): CveInfoByPkgId | null {\n const exclude = {\n upgrade: true,\n ...({ __proto__: null, ...options } as GetCveInfoByPackageOptions).exclude\n }\n let infoByPkg: CveInfoByPkgId | null = null\n for (const [pkgId, sockPkgAlerts] of alertsMap) {\n const purlObj = PackageURL.fromString(`pkg:npm/${pkgId}`)\n const name = resolvePackageName(purlObj)\n for (const sockPkgAlert of sockPkgAlerts) {\n const alert = sockPkgAlert.raw\n if (\n alert.fix?.type !== ALERT_FIX_TYPE.cve ||\n (exclude.upgrade && getManifestData(NPM, name))\n ) {\n continue\n }\n if (!infoByPkg) {\n infoByPkg = new Map()\n }\n let infos = infoByPkg.get(name)\n if (!infos) {\n infos = []\n infoByPkg.set(name, infos)\n }\n const { firstPatchedVersionIdentifier, vulnerableVersionRange } =\n alert.props\n infos.push({\n firstPatchedVersionIdentifier,\n vulnerableVersionRange: new semver.Range(\n vulnerableVersionRange\n ).format()\n })\n }\n }\n return infoByPkg\n}\n\ntype LogAlertsMapOptions = {\n output?: NodeJS.WriteStream | undefined\n}\n\nexport function logAlertsMap(\n alertsMap: AlertsByPkgId,\n options: LogAlertsMapOptions\n) {\n const { output = process.stderr } = {\n __proto__: null,\n ...options\n } as LogAlertsMapOptions\n const translations = getTranslations()\n for (const [pkgId, alerts] of alertsMap) {\n const purlObj = PackageURL.fromString(`pkg:npm/${pkgId}`)\n const lines = new Set()\n for (const alert of alerts) {\n const { type } = alert\n const attributes = [\n ...(alert.fixable ? ['fixable'] : []),\n ...(alert.block ? [] : ['non-blocking'])\n ]\n const maybeAttributes = attributes.length\n ? ` (${attributes.join('; ')})`\n : ''\n // Based data from { pageProps: { alertTypes } } of:\n // https://socket.dev/_next/data/94666139314b6437ee4491a0864e72b264547585/en-US.json\n const info = (translations.alerts as any)[type]\n const title = info?.title ?? type\n const maybeDesc = info?.description ? ` - ${info.description}` : ''\n // TODO: emoji seems to mis-align terminals sometimes\n lines.add(` ${title}${maybeAttributes}${maybeDesc}`)\n }\n output.write(\n `(socket) ${format.hyperlink(\n pkgId,\n getSocketDevPackageOverviewUrl(\n NPM,\n resolvePackageName(purlObj),\n purlObj.version\n )\n )} contains risks:\\n`\n )\n for (const line of lines) {\n output.write(`${line}\\n`)\n }\n }\n}\n","import semver from 'semver'\n\nimport { PackageURL } from '@socketregistry/packageurl-js'\nimport { getManifestData } from '@socketsecurity/registry'\nimport { arrayUnique } from '@socketsecurity/registry/lib/arrays'\nimport { debugLog } from '@socketsecurity/registry/lib/debug'\nimport { hasOwn } from '@socketsecurity/registry/lib/objects'\nimport { fetchPackagePackument } from '@socketsecurity/registry/lib/packages'\n\nimport constants from '../../constants'\nimport { SafeArborist } from '../../shadow/npm/arborist/lib/arborist'\nimport { DiffAction } from '../../shadow/npm/arborist/lib/arborist/types'\nimport { Edge } from '../../shadow/npm/arborist/lib/edge'\nimport { getPublicToken, setupSdk } from '../../utils/sdk'\nimport { CompactSocketArtifact } from '../alert/artifact'\nimport { addArtifactToAlertsMap } from '../socket-package-alert'\n\nimport type { Diff } from '../../shadow/npm/arborist/lib/arborist/types'\nimport type { SafeEdge } from '../../shadow/npm/arborist/lib/edge'\nimport type { SafeNode } from '../../shadow/npm/arborist/lib/node'\nimport type { AlertsByPkgId } from '../socket-package-alert'\nimport type { Spinner } from '@socketsecurity/registry/lib/spinner'\n\ntype Packument = Exclude<\n Awaited<ReturnType<typeof fetchPackagePackument>>,\n null\n>\n\nconst { LOOP_SENTINEL, NPM, NPM_REGISTRY_URL } = constants\n\ntype DiffQueryIncludeFilter = {\n unchanged?: boolean | undefined\n unknownOrigin?: boolean | undefined\n}\n\ntype DiffQueryOptions = {\n include?: DiffQueryIncludeFilter | undefined\n}\n\ntype PackageDetail = {\n node: SafeNode\n existing?: SafeNode | undefined\n}\n\nfunction getDetailsFromDiff(\n diff_: Diff | null,\n options?: DiffQueryOptions | undefined\n): PackageDetail[] {\n const details: PackageDetail[] = []\n // `diff_` is `null` when `npm install --package-lock-only` is passed.\n if (!diff_) {\n return details\n }\n\n const include = {\n __proto__: null,\n unchanged: false,\n unknownOrigin: false,\n ...({ __proto__: null, ...options } as DiffQueryOptions).include\n } as DiffQueryIncludeFilter\n\n const queue: Diff[] = [...diff_.children]\n let pos = 0\n let { length: queueLength } = queue\n while (pos < queueLength) {\n if (pos === LOOP_SENTINEL) {\n throw new Error('Detected infinite loop while walking Arborist diff')\n }\n const diff = queue[pos++]!\n const { action } = diff\n if (action) {\n // The `pkgNode`, i.e. the `ideal` node, will be `undefined` if the diff\n // action is 'REMOVE'\n // The `oldNode`, i.e. the `actual` node, will be `undefined` if the diff\n // action is 'ADD'.\n const { actual: oldNode, ideal: pkgNode } = diff\n let existing: SafeNode | undefined\n let keep = false\n if (action === DiffAction.change) {\n if (pkgNode?.package.version !== oldNode?.package.version) {\n keep = true\n if (\n oldNode?.package.name &&\n oldNode.package.name === pkgNode?.package.name\n ) {\n existing = oldNode\n }\n } else {\n debugLog('SKIPPING META CHANGE ON', diff)\n }\n } else {\n keep = action !== DiffAction.remove\n }\n if (keep && pkgNode?.resolved && (!oldNode || oldNode.resolved)) {\n if (\n include.unknownOrigin ||\n getUrlOrigin(pkgNode.resolved) === NPM_REGISTRY_URL\n ) {\n details.push({\n node: pkgNode,\n existing\n })\n }\n }\n }\n for (const child of diff.children) {\n queue[queueLength++] = child\n }\n }\n if (include.unchanged) {\n const { unchanged } = diff_!\n for (let i = 0, { length } = unchanged; i < length; i += 1) {\n const pkgNode = unchanged[i]!\n if (\n include.unknownOrigin ||\n getUrlOrigin(pkgNode.resolved!) === NPM_REGISTRY_URL\n ) {\n details.push({\n node: pkgNode,\n existing: pkgNode\n })\n }\n }\n }\n return details\n}\n\nfunction getUrlOrigin(input: string): string {\n try {\n return URL.parse(input)?.origin ?? ''\n } catch {}\n return ''\n}\n\nexport function findBestPatchVersion(\n node: SafeNode,\n availableVersions: string[],\n vulnerableVersionRange?: string,\n _firstPatchedVersionIdentifier?: string | undefined\n): string | null {\n const manifestData = getManifestData(NPM, node.name)\n let eligibleVersions\n if (manifestData && manifestData.name === manifestData.package) {\n const major = semver.major(manifestData.version)\n eligibleVersions = availableVersions.filter(v => semver.major(v) === major)\n } else {\n const major = semver.major(node.version)\n eligibleVersions = availableVersions.filter(\n v =>\n // Filter for versions that are within the current major version and\n // are NOT in the vulnerable range.\n semver.major(v) === major &&\n (!vulnerableVersionRange ||\n !semver.satisfies(v, vulnerableVersionRange))\n )\n }\n return semver.maxSatisfying(eligibleVersions, '*')\n}\n\nexport function findPackageNodes(\n tree: SafeNode,\n packageName: string\n): SafeNode[] {\n const queue: Array<{ node: typeof tree }> = [{ node: tree }]\n const matches: SafeNode[] = []\n let sentinel = 0\n while (queue.length) {\n if (sentinel++ === LOOP_SENTINEL) {\n throw new Error('Detected infinite loop in findPackageNodes')\n }\n const { node: currentNode } = queue.pop()!\n const node = currentNode.children.get(packageName)\n if (node) {\n matches.push(node as unknown as SafeNode)\n }\n const children = [...currentNode.children.values()]\n for (let i = children.length - 1; i >= 0; i -= 1) {\n queue.push({ node: children[i] as unknown as SafeNode })\n }\n }\n return matches\n}\n\ntype AlertIncludeFilter = {\n critical?: boolean | undefined\n cve?: boolean | undefined\n existing?: boolean | undefined\n unfixable?: boolean | undefined\n upgrade?: boolean | undefined\n}\n\ntype GetAlertsMapFromArboristOptions = {\n consolidate?: boolean | undefined\n include?: AlertIncludeFilter | undefined\n spinner?: Spinner | undefined\n}\n\nexport async function getAlertsMapFromArborist(\n arb: SafeArborist,\n options?: GetAlertsMapFromArboristOptions | undefined\n): Promise<AlertsByPkgId> {\n const { include: _include, spinner } = {\n __proto__: null,\n consolidate: false,\n ...options\n } as GetAlertsMapFromArboristOptions\n\n const include = {\n __proto__: null,\n critical: true,\n cve: true,\n existing: false,\n unfixable: true,\n upgrade: false,\n ..._include\n } as AlertIncludeFilter\n\n const needInfoOn = getDetailsFromDiff(arb.diff, {\n include: {\n unchanged: include.existing\n }\n })\n const pkgIds = arrayUnique(needInfoOn.map(d => d.node.pkgid))\n let { length: remaining } = pkgIds\n const alertsByPkgId: AlertsByPkgId = new Map()\n if (!remaining) {\n return alertsByPkgId\n }\n\n const getText = () => `Looking up data for ${remaining} packages`\n\n spinner?.start(getText())\n\n let overrides: { [key: string]: string } | undefined\n const overridesMap = (\n arb.actualTree ??\n arb.idealTree ??\n (await arb.loadActual())\n )?.overrides?.children\n if (overridesMap) {\n overrides = Object.fromEntries(\n [...overridesMap.entries()].map(([key, overrideSet]) => {\n return [key, overrideSet.value!]\n })\n )\n }\n\n const socketSdk = await setupSdk(getPublicToken())\n\n const toAlertsMapOptions = {\n overrides,\n ...options\n }\n\n for await (const batchPackageFetchResult of socketSdk.batchPackageStream(\n {\n alerts: 'true',\n compact: 'true',\n fixable: include.unfixable ? 'false' : 'true'\n },\n {\n components: pkgIds.map(id => ({ purl: `pkg:npm/${id}` }))\n }\n )) {\n if (batchPackageFetchResult.success) {\n await addArtifactToAlertsMap(\n batchPackageFetchResult.data as CompactSocketArtifact,\n alertsByPkgId,\n toAlertsMapOptions\n )\n }\n remaining -= 1\n if (spinner && remaining > 0) {\n spinner.start()\n spinner.setText(getText())\n }\n }\n\n spinner?.stop()\n\n return alertsByPkgId\n}\n\nexport function updateNode(\n node: SafeNode,\n packument: Packument,\n vulnerableVersionRange?: string,\n firstPatchedVersionIdentifier?: string | undefined\n): boolean {\n const availableVersions = Object.keys(packument.versions)\n // Find the highest non-vulnerable version within the same major range\n const targetVersion = findBestPatchVersion(\n node,\n availableVersions,\n vulnerableVersionRange,\n firstPatchedVersionIdentifier\n )\n const targetPackument = targetVersion\n ? packument.versions[targetVersion]\n : undefined\n // Check !targetVersion to make TypeScript happy.\n if (!targetVersion || !targetPackument) {\n // No suitable patch version found.\n return false\n }\n // Use Object.defineProperty to override the version.\n Object.defineProperty(node, 'version', {\n configurable: true,\n enumerable: true,\n get: () => targetVersion\n })\n node.package.version = targetVersion\n // Update resolved and clear integrity for the new version.\n const purlObj = PackageURL.fromString(`pkg:npm/${node.name}`)\n node.resolved = `${NPM_REGISTRY_URL}/${node.name}/-/${purlObj.name}-${targetVersion}.tgz`\n const { integrity } = targetPackument.dist\n if (integrity) {\n node.integrity = integrity\n } else {\n delete node.integrity\n }\n if ('deprecated' in targetPackument) {\n node.package['deprecated'] = targetPackument.deprecated as string\n } else {\n delete node.package['deprecated']\n }\n const newDeps = { ...targetPackument.dependencies }\n const { dependencies: oldDeps } = node.package\n node.package.dependencies = newDeps\n if (oldDeps) {\n for (const oldDepName of Object.keys(oldDeps)) {\n if (!hasOwn(newDeps, oldDepName)) {\n node.edgesOut.get(oldDepName)?.detach()\n }\n }\n }\n for (const newDepName of Object.keys(newDeps)) {\n if (!hasOwn(oldDeps, newDepName)) {\n node.addEdgeOut(\n new Edge({\n from: node,\n name: newDepName,\n spec: newDeps[newDepName],\n type: 'prod'\n }) as unknown as SafeEdge\n )\n }\n }\n return true\n}\n","import process from 'node:process'\n\nimport { logger } from '@socketsecurity/registry/lib/logger'\nimport { confirm } from '@socketsecurity/registry/lib/prompts'\n\nimport constants from '../../../../../constants'\nimport { getAlertsMapFromArborist } from '../../../../../utils/lockfile/package-lock-json'\nimport { logAlertsMap } from '../../../../../utils/socket-package-alert'\nimport { getArboristClassPath } from '../../../paths'\n\nimport type { ArboristClass, ArboristReifyOptions } from './types'\nimport type { SafeNode } from '../node'\n\nconst {\n NPM,\n NPX,\n SOCKET_CLI_SAFE_WRAPPER,\n kInternalsSymbol,\n [kInternalsSymbol as unknown as 'Symbol(kInternalsSymbol)']: { getIpc }\n} = constants\n\nexport const SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES = {\n __proto__: null,\n audit: false,\n dryRun: true,\n fund: false,\n ignoreScripts: true,\n progress: false,\n save: false,\n saveBundle: false,\n silent: true\n}\n\nexport const kCtorArgs = Symbol('ctorArgs')\n\nexport const kRiskyReify = Symbol('riskyReify')\n\nexport const Arborist: ArboristClass = require(getArboristClassPath())\n\n// Implementation code not related to our custom behavior is based on\n// https://github.com/npm/cli/blob/v11.0.0/workspaces/arborist/lib/arborist/index.js:\nexport class SafeArborist extends Arborist {\n constructor(...ctorArgs: ConstructorParameters<ArboristClass>) {\n super(\n {\n path:\n (ctorArgs.length ? ctorArgs[0]?.path : undefined) ?? process.cwd(),\n ...(ctorArgs.length ? ctorArgs[0] : undefined),\n ...SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES\n },\n ...ctorArgs.slice(1)\n )\n ;(this as any)[kCtorArgs] = ctorArgs\n }\n\n async [kRiskyReify](\n ...args: Parameters<InstanceType<ArboristClass>['reify']>\n ): Promise<SafeNode> {\n const ctorArgs = (this as any)[kCtorArgs]\n const arb = new Arborist(\n {\n ...(ctorArgs.length ? ctorArgs[0] : undefined),\n progress: false\n },\n ...ctorArgs.slice(1)\n )\n const ret = await (arb.reify as (...args: any[]) => Promise<SafeNode>)(\n {\n ...(args.length ? args[0] : undefined),\n progress: false\n },\n ...args.slice(1)\n )\n Object.assign(this, arb)\n return ret\n }\n\n // @ts-ignore Incorrectly typed.\n override async reify(\n this: SafeArborist,\n ...args: Parameters<InstanceType<ArboristClass>['reify']>\n ): Promise<SafeNode> {\n const options = {\n __proto__: null,\n ...(args.length ? args[0] : undefined)\n } as ArboristReifyOptions\n const safeWrapperName = options.dryRun\n ? undefined\n : await getIpc(SOCKET_CLI_SAFE_WRAPPER)\n const isSafeNpm = safeWrapperName === NPM\n const isSafeNpx = safeWrapperName === NPX\n if (!safeWrapperName || (isSafeNpx && options['yes'])) {\n return await this[kRiskyReify](...args)\n }\n\n // Lazily access constants.spinner.\n const { spinner } = constants\n await super.reify(\n {\n ...options,\n ...SAFE_ARBORIST_REIFY_OPTIONS_OVERRIDES,\n progress: false\n },\n // @ts-ignore: TS gets grumpy about rest parameters.\n ...args.slice(1)\n )\n const alertsMap = await getAlertsMapFromArborist(this, {\n spinner,\n include: {\n existing: isSafeNpx,\n unfixable: isSafeNpm\n }\n })\n if (alertsMap.size) {\n logAlertsMap(alertsMap, { output: process.stderr })\n if (\n !(await confirm({\n message: 'Accept risks of installing these packages?',\n default: false\n }))\n ) {\n throw new Error('Socket npm exiting due to risks')\n }\n } else {\n logger.success('Socket npm found no risks!')\n }\n return await this[kRiskyReify](...args)\n }\n}\n","import {\n getArboristClassPath,\n getArboristEdgeClassPath,\n getArboristNodeClassPath,\n getArboristOverrideSetClassPath\n} from '../paths'\nimport { SafeArborist } from './lib/arborist'\nimport { SafeEdge } from './lib/edge'\nimport { SafeNode } from './lib/node'\nimport { SafeOverrideSet } from './lib/override-set'\n\nexport function installSafeArborist() {\n // Override '@npmcli/arborist' module exports with patched variants based on\n // https://github.com/npm/cli/pull/8089.\n const cache: { [key: string]: any } = require.cache\n cache[getArboristClassPath()] = { exports: SafeArborist }\n cache[getArboristEdgeClassPath()] = { exports: SafeEdge }\n cache[getArboristNodeClassPath()] = { exports: SafeNode }\n cache[getArboristOverrideSetClassPath()] = { exports: SafeOverrideSet }\n}\n","import { installSafeArborist } from './arborist'\n\ninstallSafeArborist()\n"],"names":["getSentry","constructor","abortSignal","cwd","signal","root","dir","encoding","logger","recursive","WIN32","warnedSettingPathWin32Missing","dataHome","settingsPath","yml","path","parsed","prevDir","settings","pendingSave","SOCKET_CLI_NO_API_TOKEN","_defaultToken","message","agent","proxy","baseUrl","name","version","homepage","DiffAction","UNDEFINED_TOKEN","id","transformer","mod","canDedupe","canReplaceWith","overrides","recalculateOutEdgesOverrides","edge","newOverrideSet","from","detach","explain","bundled","overridden","error","rawSpec","explanation","reload","needToUpdateOverrideSet","ALERT_TYPE_MILD_CVE","type","ALERT_FIX_TYPE","block","display","defaultValue","action","iterate_entries","needDefault","orderedRules","target","orderedRulesCollection","resolvedDefaultValue","ux","cachedUX","organizations","orgs","cause","deferTo","issueRules","_uxLookup","result","length","ALERT_SEVERITY","low","middle","high","critical","value","severity","severityCount","header","hyperlink","fallback","fallbackToUrl","_translations","NPM","consolidate","include","__proto__","cve","existing","upgrade","package","alert","raw","highestForCve","highestForUpgrade","unfixableAlerts","sockPkgAlerts","alertsByPkgId","infoByPkg","infos","vulnerableVersionRange","output","NPM_REGISTRY_URL","unchanged","unknownOrigin","actual","ideal","keep","debugLog","node","queue","eligibleVersions","matches","spinner","unfixable","alerts","compact","fixable","components","remaining","Object","configurable","enumerable","integrity","dependencies","spec","getIpc","audit","dryRun","fund","ignoreScripts","progress","save","saveBundle","silent","default","cache","exports","installSafeArborist"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA;;AAEE;AAA+DA;AAAU;AAC3E;AAIO;AAEA;AAGLC;;;AAGA;AACF;AAEO;AAIL;AACA;;AAEA;AACF;AAEO;AAIL;;AAEE;AACF;;AAEA;AACF;AAEO;AAGL;AACE;AACF;AACA;AACF;;ACrCA;AAAQC;AAAY;AAMb;AAEHC;AAAqBC;AAAoC;AAE3D;;AACQC;AAAK;;AAEb;AACE;;AAEI;AACF;;;AAGE;;AAEA;AACE;AACF;;AAEJ;AACAC;AACF;AACA;AACF;AASO;AAIL;AACEF;AACA;AACAG;AACF;AACF;AAEO;AAIL;AACEH;AACA;AACAG;AACF;AACF;AAMO;;AAKH;AACEA;AACAH;AACA;AAAoCG;AAAkB;AACxD;;AAEF;AACF;AAMO;;;AAYDA;AACA;AAAoCA;AAAkB;AACxD;;AAEF;AACF;;ACzGA;AACA;AACA;AACA;AACA;AAEA;AAiBA;AACA;AACA;AACA;AAEA;;;AAGI;AACA;AACE;AACA;;;AAME;AACEC;AACF;AACF;;AAC6CC;AAAgB;AAC7D;AACF;AACF;AACA;AACF;AAEA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGE;;AACQC;AAAM;AACd;;AAIE;;AAEIC;AACAH;AACF;AACF;AACEI;AAMF;AACF;AACAC;AACF;AACA;AACF;AAEA;;AAEE;AACE;AACF;AACA;AACF;AAEO;;AAEL;;;AAGE;;;AAGEC;AACF;AACA;;;AAGMC;AACAC;;AAEJ;AACE;AACF;AACF;AACAC;;AAEF;AACA;AACF;AAEO;;AAIP;AAEO;AAIL;AACAC;;AAEEC;;AAEEA;AACA;AACA;;AAKA;AACF;AACF;AACF;;AClJA;AAAQC;AAAwB;;AAEhC;AACA;AACE;AAEA;AACF;;AAEA;AACA;AACE;AAEA;AACF;;AAEA;AACA;AACO;AACL;AACA;AACEC;AACF;AACE;AAEE;AACA;;;AAKJ;AACA;AACF;AAEO;AACL;AAIF;AAEO;;;AAODC;AAEF;AACAD;AACF;;AAEE;AACF;AACA;AACEE;AAAqCC;;AACrCC;;AAEE;AACAC;AACA;AACAC;AACA;AACAC;;AAEJ;AACF;;AC/BYC;;;;AAAU;AAAA;;AChDf;;ACDP;AAAQC;AAAgB;AAaxB;AAIE;AACE;AACA;AACA;AACEC;AACAC;AACF;AACED;;AAEF;;AAEE;AACA;;;AAGE;AACF;;AAEJ;AACA;AACF;AAOA;AACO;;;AAMC;AACA;AACAE;AAIN;AACA;AACF;;AChCA;;AAEA;AACA;AACO;AACL;AACA;AACA;AAIE;AACA;AACA;;AAEF;;AAEA;AACA;AACA;AAIE;AAKE;AACE;AACF;AACF;AACA;AAKE;AACE;AACF;AACF;AACA;AACA;;AAEA;AACF;;AAEA;AACA;;;AAGI;AACF;AACA;AAAa;AAAQ;AAAoB;;;AAGrC;AACF;AACA;AACE;AACF;AACA;AACE;AACF;AACF;AACA;AACF;;;AAII;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACE;AACE;AACF;AACA;AACF;;AAEE;AAGE;AACF;AACA;AACF;AACA;AACA;AACA;AACA;AACF;AACA;AACF;;AAEA;AACA;;;AAGI;AACF;;AAEE;AACF;AACA;AAIE;AACF;AACA;AACE;AACF;AACA;;AAEA;;AAEF;AACF;;ACpFA;;AAEA;AACA;AACO;AACL;AACA;AACA;AACSC;AACP;AACA;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;;AAEE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACE;AACF;AACA;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACSC;AACP;AACE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;;;AAGI;AACF;AACF;;AAEI;AACF;AACF;AACF;AACA;AACA;AACA;AACA;AACA;;AAEA;AACE;AACF;;;;;;AAME;AACF;AACA;AACF;;AAEA;;AAEE;;AACQC;AAAU;AAClB;AACE;AACF;AACF;;AAGE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AACF;AACA;AACA;;AAEF;;AAEA;;AAEE;AACA;AACA;;AAME;AACF;AACA;AACA;AACA;AACA;AACA;AACA;;AAMI;AACE;AACF;AACF;AACF;AACA;AACF;;AAGE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACQA;AAAU;AAClB;;AAEA;;;;;;AAME;AACF;AACF;;AAEA;AACA;AACSC;AACP;;AAEEC;;;AAGA;AACF;AACF;;AAEA;;AAEE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AAAuCF;AAAc;AACvD;;;;;;AAME;AACF;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAKI;AACA;AACA;AACA;AACA;AACF;AACA;;;AAGE;AACF;;AAEE;AACF;;AAKA;;AAEI;AACF;;;AAGA;AACF;AACA;AACA;AACA;;AAEA;AACF;;AAEA;AACA;;AAEE;AACA;AACA;AACE;AACF;AACA;AACA;;AACUA;AAAyB;;;AAMjC;AACEG;AACF;AACF;;AAEE;AACF;;AAEA;AACE;AACA;AACA;AACA;AACA;;AAEF;AACA;AACF;AACF;;ACrUO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACL;AACA;AACA;AACA;;;AAGUC;AAAK;AACb;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACF;;AAGE;AACF;;AAGE;AACE;;AAEI;AACF;AACE;AACF;AACF;AAGE;AACA;AACA;AAEA;AACF;AACE;AACF;AACA;AACA;AAAA;AASE;AACA;AACA;AACA;AACA;AACA;AACF;AACE;AACF;AACF;AACA;AACE;AACF;;AAEF;;AAEA;;;AAGA;;AAEA;;;;;AASM;AACA;AACA;AACA;AACA;;AAIA;AACE;AACF;AACA;AACE;AACF;AACA;AACE;AACF;AACA;AACE;AACF;;AAEF;AACA;AACF;;AAEF;;AAEA;;;AAGA;AAESC;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACF;;AAEA;AACA;AACSC;AACP;AACE;;;;AAIEC;AACAC;AACAC;AACAL;AACAM;;AAEF;AACEC;;AAEF;;AAEEA;AACF;;AAEEA;AACF;AACA;;AAEA;AACA;AACF;;AAEF;AAESC;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA;;;AAGI;AACA;AACA;AACA;AACAC;;;AAGF;AACF;;AAEA;AACA;AACA;AACA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACF;AACA;AACA;AAAA;AAEE;AACA;AACA;AACF;AACF;;AAGE;AACA;AACA;AACA;AACA;AACA;AACE;AACF;AACA;AACA;;AAEE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACE;AACF;AACA;AACA;AACE;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF;AACF;;AC/QA;;;;AAIEC;AACF;AAEO;;AAGGC;AAAK;AACb;AAMF;;ACpEYC;;;AAAc;AAAA;;ACsC1B;AACEC;AACAC;AACF;AAEA;AACED;AACAC;AACF;AAEA;AACED;AACAC;AACF;;AAEA;AACA;AACA;AACA;;AASIC;AAAiBC;;AACnB;AACED;AAAiBC;;AACnB;;;;AAIAC;AACE;AACE;AACEC;AACA;AACAL;AACAC;AACA;AACF;AACF;AACA;AACAD;AACAC;AACF;AACA;AACE;AACAD;AACAC;AACF;;;AACgBA;;AAClB;;AAEA;AACA;;AAII;AACF;AACA;;AACUE;AAAO;AACf;AACE;AACF;AACF;AACA;AACF;;AAEA;AACA;AAGE;AACE;AACF;;AACQA;AAAO;;AAEb;AACF;AACE;AACF;AACA;AACF;AAMO;AAIL;AAEA;;AACUL;;AACR;AACA;AACE;AACF;;AAEA;;AAEE;;AAEE;;AAEE;AACF;AACA;AACA;AACEQ;AACF;AACAC;AACF;AACAC;AACF;;AAKA;AACEL;;;AAGAM;AAAyBN;;AAC3B;AACEM;AAAyBN;;AAC3B;AACAO;AACAC;AACA;;AAEJ;AAEA;AACO;;;;AAIW9C;;;;AAGV;AACA;AACE;;AAEA;;AAIF;;AACQ+C;;;;AAIN;AACEC;AACF;AACF;AACA;;;AAGA;;AAIA;;;;;;AAMA;AACA;AAIE;AAGIC;AACF;AAEJ;AACA;AACF;AACF;AACA;AACA;AACA;AAAa;AAAM;AAAO;;;AAGxB;AACF;AACA;AACA;AACEjD;;AAEEA;;AAEIkD;AACA;AACA;AACA;AACA;AACA;AACAC;AAKF;AACF;AACF;AACF;AACAC;AACF;;AAEF;;ACrQO;;AAKL;AACEC;AACF;AACA;AACF;;ACTO;AAIL;;AACQC;AAAO;;AAEb;AACF;;;AAGA;AACA;;AAEF;;ACTYC;;;;;AAAc;AAAA;AAgB1B;AACA;AAGA;;AAIE;AACEF;;AAEE;AACF;AACF;AACA;AACF;AAEO;;AAIL;AACE;;AAEA;AACF;;AAEF;AAEO;;AAKDG;AAAQC;AAAWC;AAASC;AAAY;AAI5C;;AACUC;AAAM;;AAEZ;AACF;;AACQC;AAAS;AACjB;AACEC;AACF;AACF;AACA;AACF;;ACjEO;;AAIH;AACF;;AAGE;AACF;AAEAC;AACE;AAGF;AAEAC;AAIIC;AACAC;;AAMF;AACE;;AAII;AACN;AACA;AACF;;AAKE;AACF;;AAGE;AACF;;;AAMA;;AAGE;;AAIF;AACF;;ACjEO;;AAEP;AAEO;AAKL;AACF;;ACNA;AAEO;;AAEHC;AACE;;AAGJ;AACA;AACF;;ACkBA;;AAA0DC;AAAI;AAE9D;AAiBO;AAKL;AACA;AACE;AACF;;AAEEC;AACAC;AACApD;AACF;AACEqD;;;AAIF;AACEA;AACAZ;AACAa;AACAC;AAEAC;;;AAIF;;AACQjE;AAAQ;AAChB;AACA;;AAEA;AACE;AACA;AACEkE;;AAAiBlE;;AACjBmE;;AAA0B;AAC5B;;;AAGA;AACA;AACA;AACA;;;;;;;;;;;;AAiBIC;AACAH;AACF;AACF;AACF;AACA;AACE;AACF;AACA;AACE;AAIA;;AAKA;AACE;;AAEA;AACE;AAEA;AACA;AACA;;AAEEI;AACEF;AACAnE;AACF;AACF;AACF;AACE;AACA;;AAEEsE;AAA+BH;AAAqBnE;AAAQ;AAC9D;AACF;AACEuE;AACF;AACF;AACAC;AAKF;;AAEEA;AACAC;AACF;AACA;AACF;AAkBO;AAIL;AACER;;AACMH;;AAA4B;;;;;AAKlC;AACA;AACE;;AAKE;AACF;;AAEEY;AACF;AACA;;AAEEC;AACAD;AACF;;;AACuCE;;;;;AAOvC;AACF;AACF;AACA;AACF;AAMO;;;AAI2B;AAC9Bd;;;AAGF;;;AAGE;AACA;;AACUtC;AAAK;;AAKb;AAGA;AACA;AACA;AACA;AACA;AACA;;AAEF;;AAWA;AACEqD;AACF;AACF;AACF;;ACpPA;;;AAA4BC;AAAiB;AAgB7C;;AAKE;;AAEE;AACF;AAEA;AACEhB;AACAiB;AACAC;;AACMlB;;AAA4B;;AAGpC;;;AAEMjB;AAAoB;;;AAGtB;AACF;AACA;;AACQhB;AAAO;AACf;AACE;AACA;AACA;AACA;;AACQoD;AAAiBC;AAAe;AACxC;;AAEA;;AAEIC;AACA;AAIEnB;AACF;AACF;AACEoB;AACF;AACF;AACED;AACF;AACA;AACE;;AAKIE;AACArB;AACF;AACF;AACF;AACF;AACA;AACEsB;AACF;AACF;;;AAEUP;AAAU;AAClB;AAAkBlC;;AAChB;AACA;;AAKIwC;AACArB;AACF;AACF;AACF;AACF;AACA;AACF;AAEA;;;;AAIE;AACF;AAEO;;AAOL;;;AAGEuB;AACF;;AAEEA;AAEI;AACA;;AAKN;AACA;AACF;AAEO;;AAI0CF;AAAW;;;;AAIxD;AACE;AACF;;AACQA;AAAkB;;AAE1B;AACEG;AACF;;AAEA;;;AACwD;AACxD;AACF;AACA;AACF;AAgBO;;AAIG3B;AAAmB4B;AAAQ;AACjC3B;AACAF;;AAIF;AACEE;AACAZ;AAGAwC;AACAzB;;AAIF;AACEJ;;AAEA;AACF;AACA;;AACMhB;AAAkB;AACxB;;AAEE;AACF;AAEA;AAEA4C;AAEA;;AAMA;;AAGM;AACF;AAEJ;;AAIA;;;;AAKA;AAEIE;AACAC;AACAC;AACF;AAEEC;;AAAsD;AACxD;;;AAQA;AACAC;AACA;;AAEEN;AACF;AACF;;AAIA;AACF;AAEO;;AAOL;;;AAUA;AACA;AACE;AACA;AACF;AACA;AACAO;AACEC;AACAC;;AAEF;AACAb;AACA;;AAEAA;;AACQc;;AACR;;AAEA;;AAEA;;;AAGA;AACE;AACF;AACA;AAAkB;;;AACVC;;AACRf;AACA;;AAEI;;AAEA;AACF;AACF;;AAEE;AACEA;AAEIxE;AACAd;AACAsG;AACA7E;AACF;AAEJ;AACF;AACA;AACF;;AChVA;;;;;AAKE;AAA+D8E;AAAO;AACxE;AAEO;AACLxC;AACAyC;AACAC;AACAC;AACAC;AACAC;AACAC;AACAC;AACAC;AACF;AAEO;AAEA;AAEA;;AAEP;AACA;AACO;;AAEH;AAEI1H;;;;AAOF;AACJ;AAEA;AAGE;AACA;;AAGIuH;;AAIJ;;AAGIA;;AAIJX;AACA;AACF;;AAEA;AACA;AAIE;AACElC;;;AAGF;AAGA;AACA;;;AAGA;;AAEA;;AACQ2B;AAAQ;;AAGZ;AACA;AACAkB;;AAEF;AACA;AAEF;;AAEE9C;AACEG;AACA0B;AACF;AACF;;;;AAEmD;;AAG7C/F;AACAoH;;AAGF;AACF;AACF;AACElI;AACF;;AAEF;AACF;;ACrHO;AACL;AACA;AACA;AACAmI;AAAkCC;;AAClCD;AAAsCC;;AACtCD;AAAsCC;;AACtCD;AAA6CC;;AAC/C;;ACjBAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;","debugId":"86178861-a8cc-486b-ac92-f49e627e80af"}
@@ -27,7 +27,7 @@ type AddSocketArtifactAlertToAlertsMapOptions = {
27
27
  } | undefined;
28
28
  spinner?: Spinner | undefined;
29
29
  };
30
- declare function addArtifactToAlertsMap(artifact: CompactSocketArtifact, alertsByPkgId: AlertsByPkgId, options?: AddSocketArtifactAlertToAlertsMapOptions | undefined): Promise<void>;
30
+ declare function addArtifactToAlertsMap<T extends AlertsByPkgId>(artifact: CompactSocketArtifact, alertsByPkgId: T, options?: AddSocketArtifactAlertToAlertsMapOptions | undefined): Promise<T>;
31
31
  type CveExcludeFilter = {
32
32
  upgrade?: boolean | undefined;
33
33
  };