UNPKG

@cyclonedx/cyclonedx-npm

Version:

Create CycloneDX Software Bill of Materials (SBOM) from NPM projects.

77 lines (72 loc) 3.18 kB
"use strict"; /*! This file is part of CycloneDX generator for NPM projects. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache-2.0 Copyright (c) OWASP Foundation. All Rights Reserved. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.NpmRunner = void 0; const node_child_process_1 = require("node:child_process"); const node_fs_1 = require("node:fs"); const node_path_1 = require("node:path"); class NpmRunner { static #jsMatcher = /\.[cm]?js$/; static #npxMatcher = /(^|\\|\/)npx-cli\.js$/; constructor(process_, console_) { this.run = NpmRunner.#makeNpmRunner(process_, console_); } run; #version; getVersion(options = {}) { if (this.#version === undefined) { this.#version = this.run(['--version'], { ...options, stdio: ['ignore', 'pipe', 'ignore'], encoding: 'buffer', maxBuffer: Number.MAX_SAFE_INTEGER }).toString().trim(); } return this.#version; } static #getExecPath(process_, console_) { const execPath = process_.env.npm_execpath ?? ''; if (execPath === '') { return undefined; } if (NpmRunner.#npxMatcher.test(execPath)) { console_.debug('DEBUG | command: npx-cli.js usage detected, checking for npm-cli.js ...'); const npmPath = (0, node_path_1.resolve)(execPath.replace(NpmRunner.#npxMatcher, '$1npm-cli.js')); if ((0, node_fs_1.existsSync)(npmPath)) { return npmPath; } } else if ((0, node_fs_1.existsSync)(execPath)) { return execPath; } throw new Error(`unexpected NPM execPath: ${execPath}`); } static #makeNpmRunner(process_, console_) { const execPath = NpmRunner.#getExecPath(process_, console_); if (execPath === undefined) { console_.debug('DEBUG | makeNpmRunner caused execSync "npm"'); return (args, options) => (0, node_child_process_1.execSync)('npm ' + args.join(' '), options); } if (NpmRunner.#jsMatcher.test(execPath)) { const nodeExecPath = process_.execPath; console_.debug('DEBUG | makeNpmRunner caused execFileSync "%s" with "-- %s"', nodeExecPath, execPath); return (args, options) => (0, node_child_process_1.execFileSync)(nodeExecPath, ['--', execPath, ...args], options); } console_.debug('DEBUG | makeNpmRunner caused execFileSync "%s"', execPath); return (args, options) => (0, node_child_process_1.execFileSync)(execPath, args, options); } } exports.NpmRunner = NpmRunner;