Skip to content

Commit 3942417

Browse files
chore: replace import-local and cross-spawn with Node.js built-ins (#4889)
* chore: replace import-local and cross-spawn with Node.js built-ins The CLI used one function of each package, both are a few lines with node:module and node:child_process. Claude-Session: https://claude.ai/code/session_013FhutRFjuQemBzekJMYcqL * test: ignore engines of packages installed by Yarn in generator tests [email protected] depends on rechoir 1, which requires Node.js 22.15, and Yarn 1 fails the install on Node.js 20. Claude-Session: https://claude.ai/code/session_013FhutRFjuQemBzekJMYcqL * fix: find the command file on Windows like cross-spawn Run .exe and .com files without a shell and escape the arguments twice for the .cmd shims of packages, they pass them to another shell. Claude-Session: https://claude.ai/code/session_013FhutRFjuQemBzekJMYcqL * fix: detect missing package managers spawnSync returns a result instead of throwing, so the CLI always chose npm without a lock file, even when npm was missing. Check the error and the exit status, so yarn and pnpm are found too. Claude-Session: https://claude.ai/code/session_013FhutRFjuQemBzekJMYcqL * chore: add a changeset for the package manager detection fix Claude-Session: https://claude.ai/code/session_013FhutRFjuQemBzekJMYcqL * refactor: run package managers asynchronously getDefaultPackageManager and installPackage are async, so spawn the commands and look up their files on Windows without blocking. Claude-Session: https://claude.ai/code/session_013FhutRFjuQemBzekJMYcqL * fix: exit when a package fails to install The result of the package manager was ignored, so the CLI continued as if the package was installed. Claude-Session: https://claude.ai/code/session_013FhutRFjuQemBzekJMYcqL
1 parent 349b660 commit 3942417

11 files changed

Lines changed: 409 additions & 87 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack-cli": patch
3+
---
4+
5+
fix: detect missing package managers and failed installations, without a lock file the CLI chose npm even when it wasn't installed instead of yarn or pnpm, and it continued after a package failed to install
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack-cli": patch
3+
---
4+
5+
chore: replace the `import-local` and `cross-spawn` dependencies with Node.js built-ins

‎.cspell.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@
6464
"Nitin",
6565
"nwjs",
6666
"Oikawa",
67+
"PATHEXT",
6768
"pathinfo",
6869
"plopfile",
6970
"pnpm",

‎package-lock.json‎

Lines changed: 0 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/webpack-cli/bin/cli.js‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,56 @@ if (enableCompileCache) {
2525
}
2626
}
2727

28+
/**
29+
* Runs the local installation of `webpack-cli` resolved from the current directory, unless it is
30+
* this file, the same as `import-local` does.
31+
* @returns {boolean} whether the local installation was run
32+
*/
33+
const runLocalCLI = () => {
34+
const path = require("node:path");
35+
36+
let cwd;
37+
38+
try {
39+
cwd = require("node:fs").realpathSync(process.cwd());
40+
} catch (error) {
41+
if (error.code !== "ENOENT") {
42+
return false;
43+
}
44+
45+
cwd = path.resolve(process.cwd());
46+
}
47+
48+
let localFile;
49+
50+
try {
51+
localFile = require("node:module")
52+
.createRequire(path.join(cwd, "noop.js"))
53+
.resolve("webpack-cli/bin/cli.js");
54+
} catch {
55+
return false;
56+
}
57+
58+
const localNodeModules = path.join(process.cwd(), "node_modules");
59+
const isInLocalNodeModules =
60+
!path.relative(localNodeModules, __filename).startsWith("..") &&
61+
// On Windows, `path.relative()` returns the second path when the paths are on different drives
62+
path.parse(localNodeModules).root === path.parse(__filename).root;
63+
64+
// `path.relative()` because the case of `__filename` is inconsistent on Windows
65+
if (isInLocalNodeModules || path.relative(localFile, __filename) === "") {
66+
return false;
67+
}
68+
69+
require(localFile);
70+
71+
return true;
72+
};
73+
2874
// Prefer the local installation of `webpack-cli` when one exists. Run this
2975
// before requiring the (heavier) CLI implementation: a delegated run then never
30-
// loads it, and `WEBPACK_CLI_SKIP_IMPORT_LOCAL` skips loading `import-local` too.
31-
if (!process.env.WEBPACK_CLI_SKIP_IMPORT_LOCAL && require("import-local")(__filename)) {
76+
// loads it, and `WEBPACK_CLI_SKIP_IMPORT_LOCAL` skips the lookup too.
77+
if (!process.env.WEBPACK_CLI_SKIP_IMPORT_LOCAL && runLocalCLI()) {
3278
return;
3379
}
3480

‎packages/webpack-cli/package.json‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,7 @@
3333
"dependencies": {
3434
"@discoveryjs/json-ext": "^1.1.0",
3535
"commander": "^14.0.3",
36-
"cross-spawn": "^7.0.6",
3736
"envinfo": "^7.21.0",
38-
"import-local": "^3.2.0",
3937
"interpret": "^3.1.1",
4038
"rechoir": "^1.0.0",
4139
"webpack-merge": "^6.0.1"

‎packages/webpack-cli/src/webpack-cli.ts‎

Lines changed: 107 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { type SpawnOptions } from "node:child_process";
12
import fs from "node:fs";
23
import { createRequire } from "node:module";
34
import path from "node:path";
@@ -628,9 +629,93 @@ class WebpackCLI {
628629
};
629630
}
630631

631-
async getDefaultPackageManager(): Promise<PackageManager | undefined> {
632-
const { sync } = await import("cross-spawn");
632+
/**
633+
* Runs a command, the same as `cross-spawn` does.
634+
* @param {string} command command
635+
* @param {string[]} args arguments
636+
* @param {SpawnOptions} options options
637+
* @returns {Promise<{ status: number | null, error?: Error }>} exit status, or the error when the command fails to start
638+
*/
639+
async #spawn(
640+
command: string,
641+
args: string[],
642+
options: SpawnOptions = {},
643+
): Promise<{ status: number | null; error?: Error }> {
644+
const { spawn } = await import("node:child_process");
645+
const run = (command: string, args: string[], options: SpawnOptions) =>
646+
new Promise<{ status: number | null; error?: Error }>((resolve) => {
647+
spawn(command, args, options)
648+
.once("error", (error) => resolve({ status: null, error }))
649+
.once("close", (status) => resolve({ status }));
650+
});
651+
652+
if (process.platform !== "win32") {
653+
return run(command, args, options);
654+
}
655+
656+
// Find the file of the command like `which`, on Windows the current directory goes first
657+
const extensions = (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";");
658+
659+
if (command.includes(".") && extensions[0] !== "") {
660+
extensions.unshift("");
661+
}
662+
663+
const directories = /[/\\]/.test(command)
664+
? [""]
665+
: [process.cwd(), ...(process.env.PATH || "").split(";")];
666+
let file: string | undefined;
667+
668+
search: for (const directory of directories) {
669+
for (const extension of extensions) {
670+
const candidate = path.resolve(
671+
path.join(directory.replace(/^"(.*)"$/, "$1"), command) + extension,
672+
);
673+
674+
try {
675+
if (
676+
(await fs.promises.stat(candidate)).isFile() &&
677+
extensions.some(
678+
(extension) =>
679+
extension !== "" && candidate.toLowerCase().endsWith(extension.toLowerCase()),
680+
)
681+
) {
682+
file = candidate;
683+
684+
break search;
685+
}
686+
} catch {
687+
// Not found
688+
}
689+
}
690+
}
691+
692+
// Executables run directly
693+
if (file && /\.(?:com|exe)$/i.test(file)) {
694+
return run(command, args, options);
695+
}
696+
697+
// Other files, e.g. `npm.cmd`, only run in a shell, which doesn't escape arguments, and the
698+
// `.cmd` shims of packages pass them to another shell, so they are escaped twice
699+
const isShim = Boolean(file && /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i.test(file));
700+
const metaChars = /([()\][%!^"`<>&|;, *?])/g;
701+
const escapedArgs = args.map((arg) => {
702+
const quoted = `"${arg
703+
// Double the backslashes before a quote and escape the quote
704+
.replaceAll(/(?=(\\+?)?)\1"/g, '$1$1\\"')
705+
// Double the backslashes at the end, they precede the closing quote
706+
.replace(/(?=(\\+?)?)\1$/, "$1$1")}"`.replaceAll(metaChars, "^$1");
707+
708+
return isShim ? quoted.replaceAll(metaChars, "^$1") : quoted;
709+
});
633710

711+
return run(
712+
[path.normalize(command).replaceAll(metaChars, "^$1"), ...escapedArgs].join(" "),
713+
[],
714+
{ ...options, shell: true },
715+
);
716+
}
717+
718+
async getDefaultPackageManager(): Promise<PackageManager | undefined> {
634719
try {
635720
await fs.promises.access(path.resolve(process.cwd(), "package-lock.json"), fs.constants.F_OK);
636721
return "npm";
@@ -652,37 +737,20 @@ class WebpackCLI {
652737
// Nothing
653738
}
654739

655-
try {
656-
// the sync function below will fail if npm is not installed,
657-
// an error will be thrown
658-
if (sync("npm", ["--version"])) {
659-
return "npm";
660-
}
661-
} catch {
662-
// Nothing
663-
}
740+
// A missing package manager fails to start, or exits with an error in the shell on Windows
741+
for (const packageManager of ["npm", "yarn", "pnpm"] as const) {
742+
const { error, status } = await this.#spawn(packageManager, ["--version"], {
743+
stdio: "ignore",
744+
});
664745

665-
try {
666-
// the sync function below will fail if yarn is not installed,
667-
// an error will be thrown
668-
if (sync("yarn", ["--version"])) {
669-
return "yarn";
746+
if (!error && status === 0) {
747+
return packageManager;
670748
}
671-
} catch {
672-
// Nothing
673749
}
674750

675-
try {
676-
// the sync function below will fail if pnpm is not installed,
677-
// an error will be thrown
678-
if (sync("pnpm", ["--version"])) {
679-
return "pnpm";
680-
}
681-
} catch {
682-
this.logger.error("No package manager found.");
751+
this.logger.error("No package manager found.");
683752

684-
process.exit(2);
685-
}
753+
process.exit(2);
686754
}
687755

688756
async isPackageInstalled(packageName: string): Promise<boolean> {
@@ -812,10 +880,18 @@ class WebpackCLI {
812880
}
813881

814882
if (needInstall) {
815-
const { sync } = await import("cross-spawn");
816-
817883
try {
818-
sync(packageManager, commandArguments, { stdio: "inherit" });
884+
const { error, status } = await this.#spawn(packageManager, commandArguments, {
885+
stdio: "inherit",
886+
});
887+
888+
if (error) {
889+
throw error;
890+
}
891+
892+
if (status !== 0) {
893+
throw new Error(`'${commandToBeRun}' exited with code ${status}`);
894+
}
819895
} catch (error) {
820896
this.logger.error(error);
821897

0 commit comments

Comments
 (0)