|
| 1 | +import child_process from "child_process"; |
| 2 | +import { dirname, join } from "path"; |
| 3 | +import { promisify } from "util"; |
| 4 | +const execFileImpl = promisify(child_process.execFile); |
| 5 | + |
| 6 | +/** |
| 7 | + * @typedef {Object} ExecOptions |
| 8 | + * @property {string} [cwd] Current working directory. Default: process.cwd(). |
| 9 | + * @property {import('./logger.js').ILogger} [logger] |
| 10 | + * @property {boolean} [logOutput] Log captured stdout/stderr at info level. Default: false. |
| 11 | + * @property {number} [maxBuffer] Max bytes allowed on stdout or stderr. Default: 16 * 1024 * 1024. |
| 12 | + */ |
| 13 | + |
| 14 | +/** |
| 15 | + * @typedef {Object} NpmPrefixOptions |
| 16 | + * @property {string} [prefix] Prefix to pass to npm via "--prefix". |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @typedef {ExecOptions & NpmPrefixOptions} ExecNpmOptions |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @typedef {Object} ExecResult |
| 25 | + * @property {string} stdout |
| 26 | + * @property {string} stderr |
| 27 | + */ |
| 28 | + |
| 29 | +/** |
| 30 | + * @typedef {Error & { stdout?: string, stderr?: string, code?: number }} ExecError |
| 31 | + */ |
| 32 | + |
| 33 | +/** |
| 34 | + * Checks whether an unknown error object is an ExecError. |
| 35 | + * @param {unknown} error |
| 36 | + * @returns {error is ExecError} |
| 37 | + */ |
| 38 | +export function isExecError(error) { |
| 39 | + if (!(error instanceof Error)) return false; |
| 40 | + |
| 41 | + const e = /** @type {ExecError} */ (error); |
| 42 | + return typeof e.stdout === "string" || typeof e.stderr === "string"; |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Wraps `child_process.execFile()`, adding logging and a larger default maxBuffer. |
| 47 | + * |
| 48 | + * @param {string} file |
| 49 | + * @param {string[]} [args] |
| 50 | + * @param {ExecOptions} [options] |
| 51 | + * @returns {Promise<ExecResult>} |
| 52 | + * @throws {ExecError} |
| 53 | + */ |
| 54 | +export async function execFile(file, args, options = {}) { |
| 55 | + const { |
| 56 | + cwd, |
| 57 | + logger, |
| 58 | + logOutput = false, |
| 59 | + // Node default is 1024 * 1024, which is too small for some git commands returning many entities or large file content. |
| 60 | + // To support "git show", should be larger than the largest swagger file in the repo (2.5 MB as of 2/28/2025). |
| 61 | + maxBuffer = 16 * 1024 * 1024, |
| 62 | + } = options; |
| 63 | + |
| 64 | + logger?.info(`execFile("${file}", ${JSON.stringify(args)})`); |
| 65 | + |
| 66 | + try { |
| 67 | + // execFile(file, args) is more secure than exec(cmd), since the latter is vulnerable to shell injection |
| 68 | + const result = await execFileImpl(file, args, { |
| 69 | + cwd, |
| 70 | + maxBuffer, |
| 71 | + }); |
| 72 | + |
| 73 | + logger?.debug(`stdout: '${result.stdout}'`); |
| 74 | + logger?.debug(`stderr: '${result.stderr}'`); |
| 75 | + if (logOutput) { |
| 76 | + if (result.stdout) { |
| 77 | + logger?.info(result.stdout.trimEnd()); |
| 78 | + } |
| 79 | + if (result.stderr) { |
| 80 | + logger?.info(result.stderr.trimEnd()); |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + return result; |
| 85 | + } catch (error) { |
| 86 | + /* v8 ignore next */ |
| 87 | + logger?.debug(`error: '${JSON.stringify(error)}'`); |
| 88 | + if (logOutput && isExecError(error)) { |
| 89 | + if (error.stdout) { |
| 90 | + logger?.info(error.stdout.trimEnd()); |
| 91 | + } |
| 92 | + if (error.stderr) { |
| 93 | + logger?.info(error.stderr.trimEnd()); |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + throw error; |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +/** |
| 102 | + * Calls `execFile()` with appropriate arguments to run `npm` on all platforms |
| 103 | + * |
| 104 | + * @param {string[]} args |
| 105 | + * @param {ExecNpmOptions} [options] |
| 106 | + * @returns {Promise<ExecResult>} |
| 107 | + * @throws {ExecError} |
| 108 | + */ |
| 109 | +export async function execNpm(args, options = {}) { |
| 110 | + const { prefix } = options; |
| 111 | + |
| 112 | + // Exclude platform-specific code from coverage |
| 113 | + /* v8 ignore start */ |
| 114 | + const { file, defaultArgs } = |
| 115 | + process.platform === "win32" |
| 116 | + ? { |
| 117 | + // Only way I could find to run "npm" on Windows, without using the shell (e.g. "cmd /c npm ...") |
| 118 | + // |
| 119 | + // "node.exe", ["--", "npm-cli.js", ...args] |
| 120 | + // |
| 121 | + // The "--" MUST come BEFORE "npm-cli.js", to ensure args are sent to the script unchanged. |
| 122 | + // If the "--" comes after "npm-cli.js", the args sent to the script will be ["--", ...args], |
| 123 | + // which is NOT equivalent, and can break if args itself contains another "--". |
| 124 | + |
| 125 | + // example: "C:\Program Files\nodejs\node.exe" |
| 126 | + file: process.execPath, |
| 127 | + |
| 128 | + // example: "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" |
| 129 | + defaultArgs: [ |
| 130 | + "--", |
| 131 | + join(dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js"), |
| 132 | + ], |
| 133 | + } |
| 134 | + : { file: "npm", defaultArgs: [] }; |
| 135 | + /* v8 ignore stop */ |
| 136 | + |
| 137 | + const prefixArgs = prefix ? ["--prefix", prefix] : []; |
| 138 | + |
| 139 | + return await execFile(file, [...defaultArgs, ...prefixArgs, ...args], options); |
| 140 | +} |
| 141 | + |
| 142 | +/** |
| 143 | + * Calls `execNpm()` with arguments ["exec", "--no", "--"] prepended. |
| 144 | + * |
| 145 | + * @param {string[]} args |
| 146 | + * @param {ExecNpmOptions} [options] |
| 147 | + * @returns {Promise<ExecResult>} |
| 148 | + * @throws {ExecError} |
| 149 | + */ |
| 150 | +export async function execNpmExec(args, options = {}) { |
| 151 | + return await execNpm(["exec", "--no", "--", ...args], options); |
| 152 | +} |
0 commit comments