diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 715ef3e..5580751 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -20,6 +20,8 @@ jobs: - run: npm run lint + - run: npm run typecheck + unit: runs-on: ${{ matrix.os }} timeout-minutes: 15 diff --git a/README.md b/README.md index 0219d0a..dc18776 100644 --- a/README.md +++ b/README.md @@ -36,13 +36,19 @@ Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.ht ```js -const spawn = require('cross-spawn'); +import { spawn, spawnSync } from 'cross-spawn'; // Spawn NPM asynchronously const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); // Spawn NPM synchronously -const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); +const result = spawnSync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); +``` + +`cross-spawn` is an ES module, which CommonJS code can load with `require()` too: + +```js +const { spawn, spawnSync } = require('cross-spawn'); ``` @@ -100,8 +106,11 @@ Remember to always test your code on Windows! ```sh npm test +# TypeScript types +npm run typecheck + # During development, in watch mode -node --test --watch "test/*.test.js" "lib/**/*.test.js" +node --test --watch "test/*.test.js" "src/**/*.test.js" ``` diff --git a/eslint.config.js b/eslint.config.js index 2f4d9d3..2398ca7 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,7 +1,5 @@ -'use strict'; - -const js = require('@eslint/js'); -const globals = require('globals'); +import js from '@eslint/js'; +import globals from 'globals'; const styleRules = { strict: ['error', 'global'], @@ -23,22 +21,23 @@ const styleRules = { 'no-unused-vars': ['error', { args: 'after-used', caughtErrors: 'none' }], }; -// Unit tests live next to the code they test, e.g. `lib/util/escape.test.js`, while `test/` keeps the end-to-end tests -const testFiles = ['test/**/*.js', 'lib/**/*.test.js']; +// Unit tests live next to the code they test, e.g. `src/util/escape.test.js`, while `test/` keeps the end-to-end tests +const testFiles = ['test/**/*.js', 'src/**/*.test.js']; -module.exports = [ +// ESLint requires the config to be the default export +export default [ { ignores: ['coverage/', 'test/tmp/', 'test/fixtures/(*'], }, js.configs.recommended, { // Runtime code must keep working on the Node versions declared in `engines` - files: ['index.js', 'lib/**/*.js'], - ignores: ['lib/**/*.test.js'], + files: ['src/**/*.js'], + ignores: ['src/**/*.test.js'], languageOptions: { ecmaVersion: 2024, - sourceType: 'commonjs', - globals: globals.node, + sourceType: 'module', + globals: globals.nodeBuiltin, }, rules: styleRules, }, @@ -46,8 +45,8 @@ module.exports = [ files: ['eslint.config.js', ...testFiles], languageOptions: { ecmaVersion: 'latest', - sourceType: 'commonjs', - globals: globals.node, + sourceType: 'module', + globals: globals.nodeBuiltin, }, rules: styleRules, }, diff --git a/package-lock.json b/package-lock.json index 4bcaf2f..deb724b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,11 +16,13 @@ "@commitlint/cli": "^21.3.0", "@commitlint/config-conventional": "^21.3.0", "@eslint/js": "^10.0.1", + "@types/node": "^22.20.7", "commit-and-tag-version": "^13.5.0", "eslint": "^10.16.0", "globals": "^17.14.0", "husky": "^9.1.7", - "lint-staged": "^17.6.3" + "lint-staged": "^17.6.3", + "typescript": "^7.0.2" }, "engines": { "node": ">=22.13.0" @@ -721,6 +723,356 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/node": { + "version": "22.20.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.7.tgz", + "integrity": "sha512-F/Mcc4pD3YwXQCG50hb8BjB5RmrOere6hge7n2XHf0V8tpkZOVEjwYv9Ql7n0MpMn8Bv7+q12P9w6UHsBm0Sfw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, "node_modules/acorn": { "version": "8.19.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", @@ -2549,6 +2901,48 @@ "node": ">= 0.8.0" } }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, "node_modules/unicorn-magic": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.3.0.tgz", diff --git a/package.json b/package.json index 4c6eb24..8823be6 100644 --- a/package.json +++ b/package.json @@ -19,15 +19,25 @@ "url": "git@github.com:moxystudio/node-cross-spawn.git" }, "license": "MIT", - "main": "index.js", + "type": "module", + "main": "./src/index.js", + "types": "./src/index.d.ts", + "exports": { + ".": { + "types": "./src/index.d.ts", + "default": "./src/index.js" + }, + "./package.json": "./package.json" + }, "files": [ - "lib", - "!lib/**/*.test.js" + "src", + "!src/**/*.test.js" ], "scripts": { "lint": "eslint .", - "test": "node --test --experimental-test-coverage --test-coverage-include=index.js --test-coverage-include=\"lib/**/*.js\" --test-coverage-exclude=\"lib/**/*.test.js\" \"test/*.test.js\" \"lib/**/*.test.js\"", - "prerelease": "npm t && npm run lint", + "test": "node --test --experimental-test-coverage --test-coverage-include=\"src/**/*.js\" --test-coverage-exclude=\"src/**/*.test.js\" \"test/*.test.js\" \"src/**/*.test.js\"", + "typecheck": "tsc -p test/types", + "prerelease": "npm t && npm run typecheck && npm run lint", "release": "commit-and-tag-version", "postrelease": "npm stage publish", "prepare": "husky" @@ -48,11 +58,13 @@ "@commitlint/cli": "^21.3.0", "@commitlint/config-conventional": "^21.3.0", "@eslint/js": "^10.0.1", + "@types/node": "^22.20.7", "commit-and-tag-version": "^13.5.0", "eslint": "^10.16.0", "globals": "^17.14.0", "husky": "^9.1.7", - "lint-staged": "^17.6.3" + "lint-staged": "^17.6.3", + "typescript": "^7.0.2" }, "engines": { "node": ">=22.13.0" diff --git a/src/index.d.ts b/src/index.d.ts new file mode 100644 index 0000000..b1c3c82 --- /dev/null +++ b/src/index.d.ts @@ -0,0 +1,13 @@ +import type * as childProcess from 'node:child_process'; + +/** + * Cross platform `child_process.spawn()`, with the same arguments and return value. + */ +export declare const spawn: typeof childProcess.spawn; + +/** + * Cross platform `child_process.spawnSync()`, with the same arguments and return value. + */ +export declare const spawnSync: typeof childProcess.spawnSync; + +export type { SpawnOptions, SpawnSyncOptions } from 'node:child_process'; diff --git a/index.js b/src/index.js similarity index 71% rename from index.js rename to src/index.js index 5c9a9bd..98ff032 100644 --- a/index.js +++ b/src/index.js @@ -1,7 +1,5 @@ -'use strict'; - -const cp = require('child_process'); -const parse = require('./lib/parse'); +import cp from 'child_process'; +import { parse } from './parse.js'; function spawn(command, args, options) { // Parse the arguments @@ -19,6 +17,4 @@ function spawnSync(command, args, options) { return cp.spawnSync(parsed.command, parsed.args, parsed.options); } -module.exports = spawn; -module.exports.spawn = spawn; -module.exports.sync = spawnSync; +export { spawn, spawnSync }; diff --git a/lib/parse.js b/src/parse.js similarity index 93% rename from lib/parse.js rename to src/parse.js index d8d576e..1c6b892 100644 --- a/lib/parse.js +++ b/src/parse.js @@ -1,10 +1,8 @@ -'use strict'; - -const path = require('path'); -const resolveCommand = require('./util/resolveCommand'); -const escape = require('./util/escape'); -const validate = require('./util/validate'); -const readShebang = require('./util/readShebang'); +import path from 'path'; +import { resolveCommand } from './util/command.js'; +import * as escape from './util/escape.js'; +import * as validate from './util/validate.js'; +import { readShebang } from './util/shebang.js'; const isWin = process.platform === 'win32'; const isExecutableRegExp = /\.(?:com|exe)$/i; @@ -70,7 +68,7 @@ function parseNonShell(parsed) { parsed.args.forEach((arg) => validate.assertValidArgument(arg)); // Escape command & arguments - // Batch files need a different escaping strategy, see `lib/util/escape.js` for more information + // Batch files need a different escaping strategy, see `src/util/escape.js` for more information if (isBatchFile(parsed.executableFile)) { // Run the batch file by its resolved path, so that cmd.exe runs exactly the file that was detected parsed.command = escape.command(parsed.executableFile); @@ -120,4 +118,4 @@ function parse(command, args, options) { return options.shell ? parsed : parseNonShell(parsed); } -module.exports = parse; +export { parse }; diff --git a/lib/util/resolveCommand.js b/src/util/command.js similarity index 93% rename from lib/util/resolveCommand.js rename to src/util/command.js index 2b8e9f0..acbc48a 100644 --- a/lib/util/resolveCommand.js +++ b/src/util/command.js @@ -1,10 +1,7 @@ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const url = require('url'); -// path-key is an ES module, which require() returns as a namespace object -const getPathKey = require('path-key').default; +import fs from 'fs'; +import path from 'path'; +import url from 'url'; +import getPathKey from 'path-key'; const isWin = process.platform === 'win32'; // A command with a path separator is a path, instead of a name to search for in PATH @@ -111,4 +108,4 @@ function resolveCommand(parsed) { return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); } -module.exports = resolveCommand; +export { resolveCommand }; diff --git a/lib/util/resolveCommand.test.js b/src/util/command.test.js similarity index 93% rename from lib/util/resolveCommand.test.js rename to src/util/command.test.js index 1a3f243..b6aa170 100644 --- a/lib/util/resolveCommand.test.js +++ b/src/util/command.test.js @@ -1,16 +1,14 @@ -'use strict'; - -const { describe, it, before, after, beforeEach, afterEach, mock } = require('node:test'); -const assert = require('node:assert/strict'); -const fs = require('fs'); -const os = require('os'); -const path = require('path'); -const { pathToFileURL } = require('url'); -const { Worker } = require('worker_threads'); -const resolveCommand = require('./resolveCommand'); +import { describe, it, before, after, beforeEach, afterEach, mock } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { pathToFileURL } from 'url'; +import { Worker } from 'worker_threads'; +import { resolveCommand } from './command.js'; const isWin = process.platform === 'win32'; -const testDir = path.resolve(__dirname, '../../test'); +const testDir = path.resolve(import.meta.dirname, '../../test'); const fixturesDir = path.join(testDir, 'fixtures'); const shebangFile = path.join(fixturesDir, 'shebang'); @@ -18,7 +16,7 @@ const shebangFile = path.join(fixturesDir, 'shebang'); function resolveCommandFromWorker(command, { cwd, env }) { const workerCode = [ 'const { parentPort, workerData } = require("worker_threads");', - 'const resolveCommand = require(workerData.modulePath);', + 'const { resolveCommand } = require(workerData.modulePath);', 'const cwd = workerData.isUrl ? new URL(workerData.cwd) : workerData.cwd;', 'try {', ' const options = { cwd, env: workerData.env };', @@ -31,7 +29,7 @@ function resolveCommandFromWorker(command, { cwd, env }) { const worker = new Worker(workerCode, { eval: true, workerData: { - modulePath: require.resolve('./resolveCommand'), + modulePath: path.join(import.meta.dirname, 'command.js'), command, cwd: cwd instanceof URL ? cwd.href : cwd, isUrl: cwd instanceof URL, diff --git a/lib/util/escape.js b/src/util/escape.js similarity index 96% rename from lib/util/escape.js rename to src/util/escape.js index b71d62a..6a51421 100644 --- a/lib/util/escape.js +++ b/src/util/escape.js @@ -1,5 +1,3 @@ -'use strict'; - // See http://www.robvanderwoude.com/escapechars.php // Note that % is not included because escaping it with ^ doesn't prevent %VAR% expansion if // a variable named `VAR^` exists, see `escapePercent()` below @@ -89,6 +87,8 @@ function escapeBatchArgument(arg) { return arg; } -module.exports.command = escapeCommand; -module.exports.argument = escapeArgument; -module.exports.batchArgument = escapeBatchArgument; +export { + escapeCommand as command, + escapeArgument as argument, + escapeBatchArgument as batchArgument, +}; diff --git a/lib/util/escape.test.js b/src/util/escape.test.js similarity index 93% rename from lib/util/escape.test.js rename to src/util/escape.test.js index 9862872..6f8fc29 100644 --- a/lib/util/escape.test.js +++ b/src/util/escape.test.js @@ -1,8 +1,6 @@ -'use strict'; - -const { describe, it } = require('node:test'); -const assert = require('node:assert/strict'); -const escape = require('./escape'); +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import * as escape from './escape.js'; describe('escape', () => { it('should quote batch arguments, doubling quotes and neutralizing %', () => { diff --git a/lib/util/readShebang.js b/src/util/shebang.js similarity index 87% rename from lib/util/readShebang.js rename to src/util/shebang.js index 0b51c90..cab2c06 100644 --- a/lib/util/readShebang.js +++ b/src/util/shebang.js @@ -1,7 +1,5 @@ -'use strict'; - -const fs = require('fs'); -const shebangCommand = require('shebang-command'); +import fs from 'fs'; +import shebangCommand from 'shebang-command'; function readShebang(command) { // Read the first 150 bytes from the file @@ -29,4 +27,4 @@ function readShebang(command) { return shebangCommand(buffer.subarray(0, bytesRead).toString()); } -module.exports = readShebang; +export { readShebang }; diff --git a/lib/util/readShebang.test.js b/src/util/shebang.test.js similarity index 82% rename from lib/util/readShebang.test.js rename to src/util/shebang.test.js index fb1fa5c..cb89cb3 100644 --- a/lib/util/readShebang.test.js +++ b/src/util/shebang.test.js @@ -1,11 +1,9 @@ -'use strict'; - -const { describe, it, afterEach, mock } = require('node:test'); -const assert = require('node:assert/strict'); -const fs = require('fs'); -const os = require('os'); -const path = require('path'); -const readShebang = require('./readShebang'); +import { describe, it, afterEach, mock } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { readShebang } from './shebang.js'; describe('readShebang', () => { afterEach(() => mock.restoreAll()); @@ -13,7 +11,7 @@ describe('readShebang', () => { it('should read the shebang command', () => { const close = mock.method(fs, 'closeSync'); - assert.equal(readShebang(path.join(__dirname, '../../test/fixtures/shebang')), 'node'); + assert.equal(readShebang(path.join(import.meta.dirname, '../../test/fixtures/shebang')), 'node'); assert.equal(close.mock.callCount(), 1); }); @@ -31,7 +29,7 @@ describe('readShebang', () => { }); it('should return null if the file has no shebang', () => { - assert.equal(readShebang(path.join(__dirname, '../../test/fixtures/echo.js')), null); + assert.equal(readShebang(path.join(import.meta.dirname, '../../test/fixtures/echo.js')), null); }); it('should close the file descriptor when reading fails, including descriptor zero', () => { @@ -50,7 +48,7 @@ describe('readShebang', () => { const open = mock.method(fs, 'openSync'); const close = mock.method(fs, 'closeSync'); - assert.equal(readShebang(__dirname), null); + assert.equal(readShebang(import.meta.dirname), null); // Opening a directory fails on Windows, but succeeds on other platforms and then reading fails assert.equal(close.mock.callCount(), open.mock.calls.filter((call) => call.error === undefined).length); diff --git a/lib/util/validate.js b/src/util/validate.js similarity index 94% rename from lib/util/validate.js rename to src/util/validate.js index 10701ab..fd16492 100644 --- a/lib/util/validate.js +++ b/src/util/validate.js @@ -1,5 +1,3 @@ -'use strict'; - // cmd.exe treats CR and LF as command separators and there's no way to escape them // Allowing them would enable command injection, so we reject them instead const lineBreakRegExp = /[\r\n]/; @@ -51,5 +49,4 @@ function assertValidArgument(arg) { } } -module.exports.assertValidCommand = assertValidCommand; -module.exports.assertValidArgument = assertValidArgument; +export { assertValidCommand, assertValidArgument }; diff --git a/lib/util/validate.test.js b/src/util/validate.test.js similarity index 94% rename from lib/util/validate.test.js rename to src/util/validate.test.js index ec38cbb..5a9b3b3 100644 --- a/lib/util/validate.test.js +++ b/src/util/validate.test.js @@ -1,8 +1,6 @@ -'use strict'; - -const { describe, it } = require('node:test'); -const assert = require('node:assert/strict'); -const validate = require('./validate'); +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import * as validate from './validate.js'; const invalidValueError = { name: 'TypeError', code: 'ERR_INVALID_ARG_VALUE' }; diff --git a/test/fixtures/echo.js b/test/fixtures/echo.js index b14f68d..bd6a39f 100644 --- a/test/fixtures/echo.js +++ b/test/fixtures/echo.js @@ -1,5 +1,3 @@ -'use strict'; - const args = process.argv.slice(2); args.forEach((arg, index) => { diff --git a/test/fixtures/exit-25.js b/test/fixtures/exit-25.js index 9b1890e..ea1a66f 100644 --- a/test/fixtures/exit-25.js +++ b/test/fixtures/exit-25.js @@ -1,3 +1 @@ -'use strict'; - process.exit(25); diff --git a/test/fixtures/win-ppid.js b/test/fixtures/win-ppid.js index 156ccfc..e375680 100755 --- a/test/fixtures/win-ppid.js +++ b/test/fixtures/win-ppid.js @@ -1,5 +1,3 @@ #!/usr/bin/env node -'use strict'; - console.log(process.ppid); diff --git a/test/index.test.js b/test/index.test.js index f4d51cb..3452af7 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -1,17 +1,18 @@ -'use strict'; - -const { describe, it, before, after, afterEach, mock } = require('node:test'); -const assert = require('node:assert/strict'); -const path = require('path'); -const fs = require('fs'); -const childProcess = require('child_process'); -const util = require('util'); -const pathKey = require('path-key').default(); -const run = require('./util/run'); -const spawn = require('../index'); -const parse = require('../lib/parse'); +import { describe, it, before, after, afterEach, mock } from 'node:test'; +import assert from 'node:assert/strict'; +import path from 'path'; +import fs from 'fs'; +import childProcess from 'child_process'; +import util from 'util'; +import { pathToFileURL } from 'url'; +import { Worker } from 'worker_threads'; +import getPathKey from 'path-key'; +import { run, methods, isMethodSync, isForceShell } from './util/run.js'; +import { spawnSync } from '../src/index.js'; +import { parse } from '../src/parse.js'; const isWin = process.platform === 'win32'; +const pathKey = getPathKey(); // Collects the events of a child process until it closes, then waits a bit longer to catch late events function waitForClose(cp) { @@ -28,21 +29,51 @@ function waitForClose(cp) { }); } -it('should load without printing warnings', () => { - // Some dependencies are ES modules, and require() of an ES module prints an ExperimentalWarning on some Node.js versions - const { status, stderr } = childProcess.spawnSync(process.execPath, ['-e', `require(${JSON.stringify(path.resolve(__dirname, '..'))})`]); +describe('package', () => { + // Runs code that loads the package by its name, from its own directory + const runNode = (...args) => childProcess.spawnSync(process.execPath, args, { + cwd: path.resolve(import.meta.dirname, '..'), + encoding: 'utf8', + }); + + it('should be importable from ES modules', () => { + const code = 'import { spawn, spawnSync } from "cross-spawn"; console.log(typeof spawn, typeof spawnSync);'; + const { status, stdout, stderr } = runNode('--input-type=module', '-e', code); + + assert.equal(stderr, ''); + assert.equal(status, 0); + assert.equal(stdout.trim(), 'function function'); + }); + + it('should be requirable from CommonJS without printing warnings', () => { + // require() of an ES module prints an ExperimentalWarning on some Node.js versions + const code = 'const { spawn, spawnSync } = require("cross-spawn"); console.log(typeof spawn, typeof spawnSync);'; + const { status, stdout, stderr } = runNode('--input-type=commonjs', '-e', code); + + assert.equal(stderr, ''); + assert.equal(status, 0); + assert.equal(stdout.trim(), 'function function'); + }); + + it('should only export the entry point and package.json', () => { + const { status: status1 } = runNode('--input-type=commonjs', '-e', 'require("cross-spawn/package.json");'); + + assert.equal(status1, 0); - assert.equal(status, 0); - assert.equal(stderr.toString(), ''); + const { status: status2, stderr } = runNode('--input-type=commonjs', '-e', 'require("cross-spawn/src/parse.js");'); + + assert.notEqual(status2, 0); + assert.match(stderr, /ERR_PACKAGE_PATH_NOT_EXPORTED/); + }); }); -run.methods.forEach((method) => { +methods.forEach((method) => { describe(method, () => { const originalPathEnv = process.env[pathKey]; - before(() => fs.mkdirSync(`${__dirname}/tmp`, { recursive: true })); + before(() => fs.mkdirSync(`${import.meta.dirname}/tmp`, { recursive: true })); - after(() => fs.rmSync(`${__dirname}/tmp`, { recursive: true, force: true })); + after(() => fs.rmSync(`${import.meta.dirname}/tmp`, { recursive: true, force: true })); afterEach(() => { mock.restoreAll(); @@ -51,13 +82,13 @@ run.methods.forEach((method) => { }); it('should expand using PATHEXT properly', async () => { - const { stdout } = await run(method, `${__dirname}/fixtures/say-foo`); + const { stdout } = await run(method, `${import.meta.dirname}/fixtures/say-foo`); assert.equal(stdout.trim(), 'foo'); }); it('should support shebang in executables with `/usr/bin/env`', async () => { - const { stdout: stdout1 } = await run(method, `${__dirname}/fixtures/shebang`); + const { stdout: stdout1 } = await run(method, `${import.meta.dirname}/fixtures/shebang`); assert.equal(stdout1, 'shebang works!'); @@ -65,14 +96,14 @@ run.methods.forEach((method) => { const { stdout: stdout2 } = await run(method, 'shebang', { env: { ...process.env, - [pathKey]: path.normalize(`${__dirname}/fixtures`) + path.delimiter + process.env[pathKey], + [pathKey]: path.normalize(`${import.meta.dirname}/fixtures`) + path.delimiter + process.env[pathKey], }, }); assert.equal(stdout2, 'shebang works!'); // Test if the actual shebang file is resolved against the process.env.PATH - process.env[pathKey] = path.normalize(`${__dirname}/fixtures`) + path.delimiter + process.env[pathKey]; + process.env[pathKey] = path.normalize(`${import.meta.dirname}/fixtures`) + path.delimiter + process.env[pathKey]; const { stdout: stdout3 } = await run(method, 'shebang'); @@ -81,30 +112,30 @@ run.methods.forEach((method) => { it('should handle commands with special shell chars', async () => { fs.writeFileSync( - `${__dirname}/fixtures/()%!^&;, `, - fs.readFileSync(`${__dirname}/fixtures/pre_()%!^&;, .sh`), + `${import.meta.dirname}/fixtures/()%!^&;, `, + fs.readFileSync(`${import.meta.dirname}/fixtures/pre_()%!^&;, .sh`), { mode: 0o0777 } ); fs.writeFileSync( - `${__dirname}/fixtures/()%!^&;, .bat`, - fs.readFileSync(`${__dirname}/fixtures/pre_()%!^&;, .bat`) + `${import.meta.dirname}/fixtures/()%!^&;, .bat`, + fs.readFileSync(`${import.meta.dirname}/fixtures/pre_()%!^&;, .bat`) ); // On Windows, the command resolves to a batch file, whose path can't contain ^ or % if (isWin) { - assert.throws(() => run(method, `${__dirname}/fixtures/()%!^&;, `), TypeError); + assert.throws(() => run(method, `${import.meta.dirname}/fixtures/()%!^&;, `), TypeError); return; } - const { stdout } = await run(method, `${__dirname}/fixtures/()%!^&;, `); + const { stdout } = await run(method, `${import.meta.dirname}/fixtures/()%!^&;, `); assert.equal(stdout.trim(), 'special'); }); it('should handle empty arguments and arguments with spaces', async () => { const { stdout } = await run(method, 'node', [ - `${__dirname}/fixtures/echo`, + `${import.meta.dirname}/fixtures/echo`, 'foo', '', 'bar', @@ -116,7 +147,7 @@ run.methods.forEach((method) => { it('should handle non-string arguments', async () => { const { stdout } = await run(method, 'node', [ - `${__dirname}/fixtures/echo`, + `${import.meta.dirname}/fixtures/echo`, 1234, ]); @@ -159,7 +190,7 @@ run.methods.forEach((method) => { '"(foo|bar>baz|foz)"', ]; - const { stdout } = await run(method, 'node', [`${__dirname}/fixtures/echo`].concat(args)); + const { stdout } = await run(method, 'node', [`${import.meta.dirname}/fixtures/echo`].concat(args)); assert.equal(stdout, args.join('\n')); }); @@ -176,30 +207,30 @@ run.methods.forEach((method) => { '\\\\server\\share\\', ]; - const { stdout } = await run(method, 'node', [`${__dirname}/fixtures/echo`].concat(args)); + const { stdout } = await run(method, 'node', [`${import.meta.dirname}/fixtures/echo`].concat(args)); assert.equal(stdout, args.join('\n')); }); if (isWin) { it('should double escape when executing `node_modules/.bin/.cmd`', async () => { - fs.mkdirSync(`${__dirname}/fixtures/node_modules/.bin`, { recursive: true }); - fs.writeFileSync(`${__dirname}/fixtures/node_modules/.bin/echo-cmd-shim.cmd`, - fs.readFileSync(`${__dirname}/fixtures/echo-cmd-shim.cmd`)); + fs.mkdirSync(`${import.meta.dirname}/fixtures/node_modules/.bin`, { recursive: true }); + fs.writeFileSync(`${import.meta.dirname}/fixtures/node_modules/.bin/echo-cmd-shim.cmd`, + fs.readFileSync(`${import.meta.dirname}/fixtures/echo-cmd-shim.cmd`)); const arg = '"(foo|bar>baz|foz)"'; - const { stdout } = await run(method, `${__dirname}/fixtures/node_modules/.bin/echo-cmd-shim`, [arg]); + const { stdout } = await run(method, `${import.meta.dirname}/fixtures/node_modules/.bin/echo-cmd-shim`, [arg]); assert.equal(stdout, arg); }); it('should reject arguments with line breaks when executing `node_modules/.bin/.cmd`', () => { - fs.mkdirSync(`${__dirname}/fixtures/node_modules/.bin`, { recursive: true }); - fs.writeFileSync(`${__dirname}/fixtures/node_modules/.bin/echo-cmd-shim.cmd`, - fs.readFileSync(`${__dirname}/fixtures/echo-cmd-shim.cmd`)); + fs.mkdirSync(`${import.meta.dirname}/fixtures/node_modules/.bin`, { recursive: true }); + fs.writeFileSync(`${import.meta.dirname}/fixtures/node_modules/.bin/echo-cmd-shim.cmd`, + fs.readFileSync(`${import.meta.dirname}/fixtures/echo-cmd-shim.cmd`)); - const command = `${__dirname}/fixtures/node_modules/.bin/echo-cmd-shim`; + const command = `${import.meta.dirname}/fixtures/node_modules/.bin/echo-cmd-shim`; assert.throws(() => run(method, command, ['foo\necho injected']), TypeError); assert.throws(() => run(method, command, ['foo\recho injected']), TypeError); @@ -223,7 +254,7 @@ run.methods.forEach((method) => { '"(foo|bar>baz|foz)"', ]; - const { stdout } = await run(method, `${__dirname}/fixtures/echo-forward.bat`, args); + const { stdout } = await run(method, `${import.meta.dirname}/fixtures/echo-forward.bat`, args); assert.equal(stdout, args.join('\n')); }); @@ -243,7 +274,7 @@ run.methods.forEach((method) => { ]; for (const arg of args) { - const { stdout } = await run(method, `${__dirname}/fixtures/echo-first-quoted.bat`, [arg]); + const { stdout } = await run(method, `${import.meta.dirname}/fixtures/echo-first-quoted.bat`, [arg]); assert.equal(stdout, arg); } @@ -252,11 +283,11 @@ run.methods.forEach((method) => { it('should reject commands ending with a dot or whitespace', () => { // Windows strips trailing dots and spaces from file names, so cmd.exe would still run the batch file const commands = [ - `${__dirname}/fixtures/echo-forward.bat `, - `${__dirname}/fixtures/echo-forward.bat.`, - `${__dirname}/fixtures/echo-forward `, - `${__dirname}/fixtures/echo-forward. `, - `${__dirname}/fixtures/echo-forward.bat\t`, + `${import.meta.dirname}/fixtures/echo-forward.bat `, + `${import.meta.dirname}/fixtures/echo-forward.bat.`, + `${import.meta.dirname}/fixtures/echo-forward `, + `${import.meta.dirname}/fixtures/echo-forward. `, + `${import.meta.dirname}/fixtures/echo-forward.bat\t`, ]; for (const command of commands) { @@ -266,7 +297,7 @@ run.methods.forEach((method) => { it('should reject batch files whose resolved path contains ^ or %', async () => { // The batch file sees its resolved path, e.g. in `%~dp0`, even if the command is just a name - const dirs = ['a^b', '100%', 'safe'].map((name) => path.join(__dirname, 'tmp', name)); + const dirs = ['a^b', '100%', 'safe'].map((name) => path.join(import.meta.dirname, 'tmp', name)); for (const dir of dirs) { fs.mkdirSync(dir, { recursive: true }); @@ -288,10 +319,10 @@ run.methods.forEach((method) => { it('should let batch files found in PATH know their own directory', async () => { // cmd.exe sets %~dp0 to the current directory if a batch file is run with a quoted name found in PATH, // which breaks batch files that use it to find their own files, e.g. Gradle's, see #203 - const dir = path.join(__dirname, 'fixtures', 'own-dir'); + const dir = path.join(import.meta.dirname, 'fixtures', 'own-dir'); const env = { ...process.env, [pathKey]: `${dir}${path.delimiter}${process.env[pathKey]}` }; - const { stdout } = await run(method, 'print-own-dir', { cwd: path.join(__dirname, 'fixtures'), env }); + const { stdout } = await run(method, 'print-own-dir', { cwd: path.join(import.meta.dirname, 'fixtures'), env }); assert.equal(stdout.trim().toLowerCase(), `${dir}${path.sep}`.toLowerCase()); }); @@ -308,14 +339,14 @@ run.methods.forEach((method) => { ]; for (const command of commands) { - assert.throws(() => run(method, command, ['foo'], { cwd: `${__dirname}/fixtures` }), TypeError); + assert.throws(() => run(method, command, ['foo'], { cwd: `${import.meta.dirname}/fixtures` }), TypeError); } }); it('should escape arguments for batch files whose command isn\'t written as a plain name or path', async () => { // cmd.exe ends command names at the first space, tab, `,`, `;` or `=`, and finds them with the // child's PATHEXT, so it may run a batch file that isn't obvious from the command - const fixtures = `${__dirname}/fixtures`; + const fixtures = `${import.meta.dirname}/fixtures`; const pathExtWithBatch = { ...process.env, PATHEXT: '.COM;.EXE;.BAT;.CMD' }; const cases = [ // [command, options, whether the batch file must run] @@ -359,14 +390,14 @@ run.methods.forEach((method) => { }); it('should turn echo off, enable command extensions and disable delayed expansion in cmd.exe', () => { - const parsed = parse(`${__dirname}/fixtures/echo-forward.bat`, ['!PATH!']); + const parsed = parse(`${import.meta.dirname}/fixtures/echo-forward.bat`, ['!PATH!']); assert.deepEqual(parsed.args.slice(0, 6), ['/d', '/q', '/e:on', '/v:off', '/s', '/c']); }); it('should not print the commands of batch files without `@echo off`', async () => { // See https://github.com/moxystudio/node-cross-spawn/issues/135 - const { stdout } = await run(method, `${__dirname}/fixtures/say-hello-echo-on.bat`); + const { stdout } = await run(method, `${import.meta.dirname}/fixtures/say-hello-echo-on.bat`); assert.equal(stdout.trim(), 'hello'); }); @@ -378,43 +409,43 @@ run.methods.forEach((method) => { const env = { ...process.env, 'CROSS_SPAWN_TEST^': '"&echo injected', CROSS_SPAWN_TEST: 'expanded' }; const args = ['%CROSS_SPAWN_TEST%', '"%CROSS_SPAWN_TEST%"']; - const { stdout: stdout1 } = await run(method, 'node', [`${__dirname}/fixtures/echo`].concat(args), { env }); - const { stdout: stdout2 } = await run(method, `${__dirname}/fixtures/echo-forward.bat`, args, { env }); + const { stdout: stdout1 } = await run(method, 'node', [`${import.meta.dirname}/fixtures/echo`].concat(args), { env }); + const { stdout: stdout2 } = await run(method, `${import.meta.dirname}/fixtures/echo-forward.bat`, args, { env }); assert.equal(stdout1, args.join('\n')); assert.equal(stdout2, args.join('\n')); }); } - if (isWin && run.isForceShell(method)) { + if (isWin && isForceShell(method)) { it('should reject arguments with line breaks when a shell is needed', () => { - assert.throws(() => run(method, 'node', [`${__dirname}/fixtures/echo`, 'foo\nbar']), TypeError); + assert.throws(() => run(method, 'node', [`${import.meta.dirname}/fixtures/echo`, 'foo\nbar']), TypeError); }); } it('should handle commands with names of environment variables', async () => { // On Windows, the command resolves to a batch file, whose path can't contain % if (isWin) { - assert.throws(() => run(method, `${__dirname}/fixtures/%CD%`), TypeError); + assert.throws(() => run(method, `${import.meta.dirname}/fixtures/%CD%`), TypeError); return; } - const { stdout } = await run(method, `${__dirname}/fixtures/%CD%`); + const { stdout } = await run(method, `${import.meta.dirname}/fixtures/%CD%`); assert.equal(stdout.trim(), 'special'); }); it('should handle optional spawn optional arguments correctly', async () => { - const { stdout: stdout1 } = await run(method, `${__dirname}/fixtures/say-foo`); + const { stdout: stdout1 } = await run(method, `${import.meta.dirname}/fixtures/say-foo`); assert.equal(stdout1.trim(), 'foo'); - const { stdout: stdout2 } = await run(method, `${__dirname}/fixtures/say-foo`, { stdio: 'ignore' }); + const { stdout: stdout2 } = await run(method, `${import.meta.dirname}/fixtures/say-foo`, { stdio: 'ignore' }); assert.equal(stdout2, null); - const { stdout: stdout3 } = await run(method, `${__dirname}/fixtures/say-foo`, null, { stdio: 'ignore' }); + const { stdout: stdout3 } = await run(method, `${import.meta.dirname}/fixtures/say-foo`, null, { stdio: 'ignore' }); assert.equal(stdout3, null); }); @@ -423,16 +454,16 @@ run.methods.forEach((method) => { const args = []; const options = {}; - await run(method, `${__dirname}/fixtures/say-foo`, args, options); + await run(method, `${import.meta.dirname}/fixtures/say-foo`, args, options); assert.deepEqual(args, []); assert.deepEqual(options, {}); }); - if (run.isMethodSync(method)) { + if (isMethodSync(method)) { it('should not set `error` if there is no error', () => { // Like Node.js, see https://github.com/moxystudio/node-cross-spawn/issues/151 - const result = spawn.sync('node', ['-e', '0'], { forceShell: run.isForceShell(method) }); + const result = spawnSync('node', ['-e', '0'], { forceShell: isForceShell(method) }); assert.equal(result.status, 0); assert.ok(!('error' in result)); @@ -440,11 +471,11 @@ run.methods.forEach((method) => { } it('should give correct exit code', async () => { - await assert.rejects(async () => run(method, 'node', [`${__dirname}/fixtures/exit-25`]), { exitCode: 25 }); + await assert.rejects(async () => run(method, 'node', [`${import.meta.dirname}/fixtures/exit-25`]), { exitCode: 25 }); }); it('should work with a relative posix path to a command', async () => { - const relativeFixturesPath = path.relative(process.cwd(), `${__dirname}/fixtures`).replace(/\\/, '/'); + const relativeFixturesPath = path.relative(process.cwd(), `${import.meta.dirname}/fixtures`).replace(/\\/, '/'); const { stdout: stdout1 } = await run(method, `${relativeFixturesPath}/say-foo`); @@ -464,7 +495,7 @@ run.methods.forEach((method) => { }); it('should work with a relative posix path to a command with a custom `cwd`', async () => { - const relativeTestPath = path.relative(process.cwd(), __dirname).replace(/\\/, '/'); + const relativeTestPath = path.relative(process.cwd(), import.meta.dirname).replace(/\\/, '/'); const { stdout: stdout1 } = await run(method, 'fixtures/say-foo', { cwd: relativeTestPath }); @@ -485,7 +516,7 @@ run.methods.forEach((method) => { { const assertError = (err) => { - const syscall = run.isMethodSync(method) ? 'spawnSync' : 'spawn'; + const syscall = isMethodSync(method) ? 'spawnSync' : 'spawn'; assert.ok(err.message.includes(syscall)); assert.ok(err.message.includes('ENOENT')); @@ -501,7 +532,7 @@ run.methods.forEach((method) => { return true; }; - if (run.isMethodSync(method)) { + if (isMethodSync(method)) { it('should fail with ENOENT if the command does not exist', () => { assert.throws(() => run(method, 'somecommandthatwillneverexist', ['foo']), assertError); }); @@ -522,13 +553,13 @@ run.methods.forEach((method) => { } } - if (run.isMethodSync(method)) { + if (isMethodSync(method)) { it('should NOT fail with ENOENT if the command actual exists but exited with 1', () => { - assert.throws(() => run(method, `${__dirname}/fixtures/exit-1`), (err) => err.code !== 'ENOENT'); + assert.throws(() => run(method, `${import.meta.dirname}/fixtures/exit-1`), (err) => err.code !== 'ENOENT'); }); } else { it('should NOT emit `error` if the command actual exists but exited with 1', async () => { - const promise = run(method, `${__dirname}/fixtures/exit-1`); + const promise = run(method, `${import.meta.dirname}/fixtures/exit-1`); promise.catch(() => {}); @@ -541,13 +572,13 @@ run.methods.forEach((method) => { }); } - if (run.isMethodSync(method)) { + if (isMethodSync(method)) { it('should NOT fail with ENOENT if shebang command does not exist', () => { - assert.throws(() => run(method, `${__dirname}/fixtures/shebang-enoent`), (err) => err.code !== 'ENOENT'); + assert.throws(() => run(method, `${import.meta.dirname}/fixtures/shebang-enoent`), (err) => err.code !== 'ENOENT'); }); } else { it('should NOT emit `error` if shebang command does not exist', async () => { - const promise = run(method, `${__dirname}/fixtures/shebang-enoent`); + const promise = run(method, `${import.meta.dirname}/fixtures/shebang-enoent`); promise.catch(() => {}); @@ -561,7 +592,7 @@ run.methods.forEach((method) => { }); } - if (run.isMethodSync(method)) { + if (isMethodSync(method)) { it('should fail with ENOENT a non-existing `cwd` was specified', () => { assert.throws(() => run(method, 'fixtures/say-foo', { cwd: 'somedirthatwillneverexist' }), { code: 'ENOENT' }); }); @@ -609,9 +640,9 @@ run.methods.forEach((method) => { }); } - if (isWin && !run.isForceShell(method)) { + if (isWin && !isForceShell(method)) { it('should NOT spawn a shell for a .exe', async () => { - const { stdout } = await run(method, `${__dirname}/fixtures/win-ppid.js`); + const { stdout } = await run(method, `${import.meta.dirname}/fixtures/win-ppid.js`); assert.equal(Number(stdout.trim()), process.pid); }); @@ -623,7 +654,7 @@ run.methods.forEach((method) => { it('should work if the path key is different in options.env', async () => { const env = { ...process.env, - [differentPathKey]: `${__dirname}\\fixtures;${process.env[pathKey]}`, + [differentPathKey]: `${import.meta.dirname}\\fixtures;${process.env[pathKey]}`, }; delete env[pathKey]; @@ -640,7 +671,7 @@ if (isWin) { it('should rely on Node.js refusing to run batch files without a shell', () => { // Commands that don't resolve are passed to Node.js as is, so it must never run a batch file without cmd.exe, // as its arguments wouldn't be escaped for it. Node.js refuses since its fix for CVE-2024-27980 - const file = `${__dirname}/fixtures/echo-forward.bat`; + const file = `${import.meta.dirname}/fixtures/echo-forward.bat`; assert.throws(() => childProcess.spawn(file, ['foo']), { code: 'EINVAL' }); assert.equal(childProcess.spawnSync(file, ['foo']).error.code, 'EINVAL'); @@ -648,16 +679,13 @@ if (isWin) { } if (isWin) { - const { Worker } = require('worker_threads'); - const { pathToFileURL } = require('url'); - // Spawns the command from a worker thread, which can't change the process cwd const spawnFromWorker = (command, cwd) => { const workerCode = [ 'const { parentPort, workerData } = require("worker_threads");', - 'const spawn = require(workerData.modulePath);', + 'const { spawnSync } = require(workerData.modulePath);', 'const cwd = workerData.isUrl ? new URL(workerData.cwd) : workerData.cwd;', - 'const result = spawn.sync(workerData.command, [], { cwd });', + 'const result = spawnSync(workerData.command, [], { cwd });', 'parentPort.postMessage({', ' status: result.status,', ' error: result.error && result.error.code,', @@ -668,7 +696,7 @@ if (isWin) { const worker = new Worker(workerCode, { eval: true, workerData: { - modulePath: path.resolve(__dirname, '..'), + modulePath: path.resolve(import.meta.dirname, '..'), command, cwd: cwd instanceof URL ? cwd.href : cwd, isUrl: cwd instanceof URL, @@ -684,7 +712,7 @@ if (isWin) { describe('worker threads', () => { it('should resolve relative shebangs with a custom cwd', async () => { - const result = await spawnFromWorker('./fixtures/shebang', __dirname); + const result = await spawnFromWorker('./fixtures/shebang', import.meta.dirname); assert.equal(result.error, undefined); assert.equal(result.status, 0); @@ -692,7 +720,7 @@ if (isWin) { }); it('should resolve relative shebangs with a `file:` URL as custom cwd', async () => { - const result = await spawnFromWorker('./fixtures/shebang', pathToFileURL(`${__dirname}/`)); + const result = await spawnFromWorker('./fixtures/shebang', pathToFileURL(`${import.meta.dirname}/`)); assert.equal(result.error, undefined); assert.equal(result.status, 0); diff --git a/test/types/commonjs.cts b/test/types/commonjs.cts new file mode 100644 index 0000000..2f73889 --- /dev/null +++ b/test/types/commonjs.cts @@ -0,0 +1,12 @@ +// Type tests for CommonJS, checked with `npm run typecheck` +import type { ChildProcess, SpawnSyncReturns } from 'node:child_process'; +import { spawn, spawnSync } from 'cross-spawn'; +import crossSpawn = require('cross-spawn'); + +const child: ChildProcess = spawn('npm', ['install'], { stdio: 'inherit' }); +const result: SpawnSyncReturns = crossSpawn.spawnSync('npm', ['install']); + +// @ts-expect-error There's no default export, the module is required as a namespace +crossSpawn('npm'); + +export { child, result, spawnSync }; diff --git a/test/types/esm.mts b/test/types/esm.mts new file mode 100644 index 0000000..34bc15e --- /dev/null +++ b/test/types/esm.mts @@ -0,0 +1,39 @@ +// Type tests for ES modules, checked with `npm run typecheck` +import type * as childProcess from 'node:child_process'; +import type { ChildProcess, ChildProcessWithoutNullStreams, SpawnSyncReturns } from 'node:child_process'; +import { spawn, spawnSync, type SpawnOptions, type SpawnSyncOptions } from 'cross-spawn'; +// @ts-expect-error There's no default export +import crossSpawn from 'cross-spawn'; + +// Whether two types are exactly the same +type Equal = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false; + +// The functions have exactly the same types as Node's, as they're drop in replacements +const sameSpawn: Equal = true; +const sameSpawnSync: Equal = true; +const sameOptions: Equal = true; +const sameSyncOptions: Equal = true; + +const options: SpawnOptions = { cwd: '/', stdio: 'inherit' }; +const syncOptions: SpawnSyncOptions = { cwd: '/', encoding: 'utf8' }; + +// Same overloads as Node's spawn +const child1: ChildProcess = spawn('npm', ['install'], options); +const child2: ChildProcess = spawn('npm', options); +const child3: ChildProcessWithoutNullStreams = spawn('npm', ['install']); + +// Same overloads as Node's spawnSync +const result1: SpawnSyncReturns = spawnSync('npm', ['install']); +const result2: SpawnSyncReturns = spawnSync('npm', ['install'], { encoding: 'utf8' }); +const result3: SpawnSyncReturns = spawnSync('npm', syncOptions); + +// @ts-expect-error The command must be a string +spawn(1); + +// @ts-expect-error The arguments must be strings +spawnSync('npm', [1]); + +// @ts-expect-error `spawn.sync()` is now `spawnSync()` +spawn.sync('npm'); + +export { sameSpawn, sameSpawnSync, sameOptions, sameSyncOptions, crossSpawn, child1, child2, child3, result1, result2, result3 }; diff --git a/test/types/tsconfig.json b/test/types/tsconfig.json new file mode 100644 index 0000000..3faa474 --- /dev/null +++ b/test/types/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "strict": true, + "noEmit": true, + "module": "nodenext", + "moduleResolution": "nodenext", + "target": "es2022", + "types": ["node"] + }, + "include": ["*.mts", "*.cts"] +} diff --git a/test/util/run.js b/test/util/run.js index f8c50f1..54953e4 100644 --- a/test/util/run.js +++ b/test/util/run.js @@ -1,6 +1,4 @@ -'use strict'; - -const spawn = require('../../index'); +import { spawn, spawnSync } from '../../src/index.js'; function isForceShell(method) { return /-force-shell$/.test(method); @@ -29,7 +27,7 @@ function resolveRun(exitCode, stdout, stderr) { } function runSync(command, args, options) { - const { error, status, stdout, stderr } = spawn.sync(command, args, options); + const { error, status, stdout, stderr } = spawnSync(command, args, options); if (error) { throw error; @@ -111,7 +109,6 @@ function run(method, command, args, options) { runAsync(command, args, options); } -module.exports = run; -module.exports.methods = ['spawn-force-shell', 'spawn', 'sync-force-shell', 'sync']; -module.exports.isMethodSync = isMethodSync; -module.exports.isForceShell = isForceShell; +const methods = ['spawn-force-shell', 'spawn', 'sync-force-shell', 'sync']; + +export { run, methods, isMethodSync, isForceShell };