// @ts-check /** * @typedef {import("node:child_process").SpawnOptions} SpawnOptions */ import * as child_process from "node:child_process"; import * as os from "node:os"; import { URL, fileURLToPath } from "node:url"; /** * @param {string} command * @param {string[]} args * @returns {boolean} */ function isRunningNx(command, args) { return command.startsWith("yarn") && args[0] === "nx"; } export function workspaceRoot() { return fileURLToPath(new URL("../../", import.meta.url)); } /** * @param {string} command * @param {string[]} args * @param {SpawnOptions=} options * @returns {Promise} */ function spawn(command, args, options) { return new Promise((resolve) => { /** @type {SpawnOptions} */ const opts = { ...options, stdio: "inherit", }; // As of Node 20.12.2, it is no longer allowed to spawn a process with // `.bat` or `.cmd` without shell (see // https://nodejs.org/en/blog/release/v20.12.2). // Route through `cmd.exe /c` explicitly instead of using `shell: true` // to avoid DEP0190 warning about passing args with shell option. const proc = command.endsWith(".bat") || command.endsWith(".cmd") ? child_process.spawn("cmd.exe", ["/c", command, ...args], opts) : child_process.spawn(command, args, opts); proc.on("close", (code) => resolve(code ?? -1)); }); } /** * @param {string} command * @param {...string} args * @returns {Promise} */ export function execute(command, ...args) { return spawn(command, args, { // Nx is only installed at workspace root — adjust `cwd` accordingly. cwd: isRunningNx(command, args) ? workspaceRoot() : process.cwd(), }); } /** * @param {string} command * @param {...string} args * @returns {Promise} */ export function runScript(command, ...args) { const yarn = os.platform() === "win32" ? "yarn.cmd" : "yarn"; return execute(yarn, command, ...args); }