Require Node.js 12.20 and move to ESM (#478)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Minh Nguyen · committed by GitHub · parent 9216ec8 · Browse files · 62 files·+1016 added−1034 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
62 files+1016 added−1034 removed
- tests:+385 added−345 removed
- other:+631 added−689 removed
Provenance
- Commit
7707880- Tree
3625f07- Author
Minh Nguyen <2852660+NMinhNguyen@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
9216ec8
62 files changed+1016 added−1034 removed
modified:.github/workflows/main.yml-1 removed
11 unmodified lines12131415161617181911 unmodified lines11 unmodified lines node-version: - 16 - 14 - 12 - 10 os: - ubuntu-latest - macos-latest - windows-latest11 unmodified linesmodified:lib/command.js+4 added-15 removed
1123411 unmodified lines1617181921222320212526222723242531322627282930316 unmodified lines38394041474849505152'use strict';const normalizeArgs = (file, args = []) => { if (!Array.isArray(args)) { return [file]; }11 unmodified lines
return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`;};
const joinCommand = (file, args) => { return normalizeArgs(file, args).join(' ');};export const joinCommand = (file, args) => normalizeArgs(file, args).join(' ');
const getEscapedCommand = (file, args) => { return normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');export const getEscapedCommand = (file, args) => normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');};
const SPACES_REGEXP = / +/g;
// Handle `execa.command()`const parseCommand = command => {// Handle `execaCommand()`export const parseCommand = command => { const tokens = []; for (const token of command.trim().split(SPACES_REGEXP)) { // Allow spaces to be escaped by a backslash if not meant as a delimiter const previousToken = tokens[tokens.length - 1];6 unmodified lines }
return tokens;};
module.exports = { joinCommand, getEscapedCommand, parseCommand};modified:lib/error.js+3 added-6 removed
121234517 unmodified lines232425262827282930313 unmodified lines3536373840394041424338 unmodified lines828384858788'use strict';const {signalsByName} = require('human-signals');import {signalsByName} from 'human-signals';
const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { if (timedOut) { return `timed out after ${timeout} milliseconds`;17 unmodified lines
return 'failed';};
const makeError = ({export const makeError = ({ stdout, stderr, all, error,3 unmodified lines escapedCommand, timedOut, isCanceled, killed, parsed: {options: {timeout}} parsed: {options: {timeout}},}) => { // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. // We normalize them to `undefined` exitCode = exitCode === null ? undefined : exitCode;38 unmodified lines error.killed = killed && !timedOut;
return error;};
module.exports = makeError;modified:lib/kill.js+10 added-23 removed
1-'use strict';2-const os = require('os');3-const onExit = require('signal-exit');1+import os from 'node:os';2+import onExit from 'signal-exit';3 4 const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;5 6 // Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior8-const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {7+export const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {8 const killResult = kill(signal);9 setKillTimeout(kill, signal, options, killResult);10 return killResult;11 };16 unmodified lines28 t.unref();29 }30 };31 33-const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {34- return isSigterm(signal) && forceKillAfterTimeout !== false && killResult;35-};32+const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult;33 37-const isSigterm = signal => {38- return signal === os.constants.signals.SIGTERM ||39- (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');40-};34+const isSigterm = signal => signal === os.constants.signals.SIGTERM35+ || (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');36 37 const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {38 if (forceKillAfterTimeout === true) {39 return DEFAULT_FORCE_KILL_TIMEOUT;6 unmodified lines46 return forceKillAfterTimeout;47 };48 49 // `childProcess.cancel()`55-const spawnedCancel = (spawned, context) => {50+export const spawnedCancel = (spawned, context) => {51 const killResult = spawned.kill();52 53 if (killResult) {54 context.isCanceled = true;5 unmodified lines60 reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));61 };62 63 // `timeout` option handling69-const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {64+export const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {65 if (timeout === 0 || timeout === undefined) {66 return spawnedPromise;67 }68 10 unmodified lines79 80 return Promise.race([timeoutPromise, safeSpawnedPromise]);81 };82 88-const validateTimeout = ({timeout}) => {83+export const validateTimeout = ({timeout}) => {84 if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {85 throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);86 }87 };88 89 // `cleanup` option handling95-const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {90+export const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {91 if (!cleanup || detached) {92 return timedPromise;93 }94 4 unmodified lines99 return timedPromise.finally(() => {100 removeExitHandler();101 });102 };108-109-module.exports = {110- spawnedKill,111- spawnedCancel,112- setupTimeout,113- validateTimeout,114- setExitHandler115-};modified:lib/promise.js+17 added-27 removed
1-'use strict';2-1 const nativePromisePrototype = (async () => {})().constructor.prototype;2 const descriptors = ['then', 'catch', 'finally'].map(property => [3 property,6- Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property)4+ Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),5 ]);6 7 // The return value is a mixin of `childProcess` and `Promise`10-const mergePromise = (spawned, promise) => {8+export const mergePromise = (spawned, promise) => {9 for (const [property, descriptor] of descriptors) {10 // Starting the main `promise` is deferred to avoid consuming streams13- const value = typeof promise === 'function' ?14- (...args) => Reflect.apply(descriptor.value, promise(), args) :15- descriptor.value.bind(promise);11+ const value = typeof promise === 'function'12+ ? (...args) => Reflect.apply(descriptor.value, promise(), args)13+ : descriptor.value.bind(promise);14 15 Reflect.defineProperty(spawned, property, {...descriptor, value});16 }17 18 return spawned;19 };20 21 // Use promises instead of `child_process` events24-const getSpawnedPromise = spawned => {25- return new Promise((resolve, reject) => {26- spawned.on('exit', (exitCode, signal) => {27- resolve({exitCode, signal});28- });22+export const getSpawnedPromise = spawned => new Promise((resolve, reject) => {23+ spawned.on('exit', (exitCode, signal) => {24+ resolve({exitCode, signal});25+ });26 30- spawned.on('error', error => {31- reject(error);32- });33-34- if (spawned.stdin) {35- spawned.stdin.on('error', error => {36- reject(error);37- });38- }27+ spawned.on('error', error => {28+ reject(error);29 });40-};30 42-module.exports = {43- mergePromise,44- getSpawnedPromise45-};46-31+ if (spawned.stdin) {32+ spawned.stdin.on('error', error => {33+ reject(error);34+ });35+ }36+});modified:lib/stdio.js+2 added-5 removed
1-'use strict';1 const aliases = ['stdin', 'stdout', 'stderr'];2 3 const hasAlias = options => aliases.some(alias => options[alias] !== undefined);4 6-const normalizeStdio = options => {5+export const normalizeStdio = options => {6 if (!options) {7 return;8 }9 18 unmodified lines28 const length = Math.max(stdio.length, aliases.length);29 return Array.from({length}, (value, index) => stdio[index]);30 };31 33-module.exports = normalizeStdio;34-32 // `ipc` is pushed unless it is already present36-module.exports.node = options => {33+export const normalizeStdioNode = options => {34 const stdio = normalizeStdio(options);35 36 if (stdio === 'ipc') {37 return 'ipc';12 unmodified linesmodified:lib/stream.js+8 added-17 removed
1-'use strict';2-const isStream = require('is-stream');3-const getStream = require('get-stream');4-const mergeStream = require('merge-stream');1+import {isStream} from 'is-stream';2+import getStream from 'get-stream';3+import mergeStream from 'merge-stream';4 5 // `input` option7-const handleInput = (spawned, input) => {6+export const handleInput = (spawned, input) => {7 // Checking for stdin is workaround for https://github.com/nodejs/node/issues/268528 // @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.09 if (input === undefined || spawned.stdin === undefined) {10 return;6 unmodified lines17 }18 };19 20 // `all` interleaves `stdout` and `stderr`22-const makeAllStream = (spawned, {all}) => {21+export const makeAllStream = (spawned, {all}) => {22 if (!all || (!spawned.stdout && !spawned.stderr)) {23 return;24 }25 37 unmodified lines63 return getStream.buffer(stream, {maxBuffer});64 };65 66 // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)68-const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {67+export const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {68 const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});69 const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});70 const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});71 3 unmodified lines75 return Promise.all([76 {error, signal: error.signal, timedOut: error.timedOut},77 getBufferedData(stdout, stdoutPromise),78 getBufferedData(stderr, stderrPromise),80- getBufferedData(all, allPromise)79+ getBufferedData(all, allPromise),80 ]);81 }82 };83 85-const validateInputSync = ({input}) => {84+export const validateInputSync = ({input}) => {85 if (isStream(input)) {86 throw new TypeError('The `input` option cannot be a stream in sync mode');87 }88 };90-91-module.exports = {92- handleInput,93- makeAllStream,94- getSpawnedResult,95- validateInputSync96-};97-deleted:test/fixtures/command with space-3 removed
1-#!/usr/bin/env node2-'use strict';3-console.log(process.argv.slice(2).join('\n'));added:test/fixtures/command with space.js+4 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+console.log(process.argv.slice(2).join('\n'));deleted:test/fixtures/delay-4 removed
1-#!/usr/bin/env node2-'use strict';3-4-setTimeout(() => {}, Number(process.argv[2]));added:test/fixtures/delay.js+4 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+setTimeout(() => {}, Number(process.argv[2]));deleted:test/fixtures/detach-8 removed
1-#!/usr/bin/env node2-'use strict';3-4-const execa = require('../..');5-6-const subprocess = execa('node', ['./test/fixtures/forever'], {detached: true});7-console.log(subprocess.pid);8-process.exit();added:test/fixtures/detach.js+7 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {execa} from '../../index.js';4+5+const subprocess = execa('node', ['./test/fixtures/forever.js'], {detached: true});6+console.log(subprocess.pid);7+process.exit(0);deleted:test/fixtures/echo-3 removed
1-#!/usr/bin/env node2-'use strict';3-console.log(process.argv.slice(2).join('\n'));deleted:test/fixtures/echo-fail-5 removed
1-#!/usr/bin/env node2-'use strict';3-console.log('stdout');4-console.error('stderr');5-process.exit(1);added:test/fixtures/echo-fail.js+6 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+console.log('stdout');5+console.error('stderr');6+process.exit(1);added:test/fixtures/echo.js+4 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+console.log(process.argv.slice(2).join('\n'));deleted:test/fixtures/environment-4 removed
1-#!/usr/bin/env node2-'use strict';3-console.log(process.env.FOO);4-console.log(process.env.BAR);added:test/fixtures/environment.js+5 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+console.log(process.env.FOO);5+console.log(process.env.BAR);deleted:test/fixtures/exit-3 removed
1-#!/usr/bin/env node2-'use strict';3-process.exit(Number(process.argv[2]));added:test/fixtures/exit.js+4 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+process.exit(Number(process.argv[2]));deleted:test/fixtures/fail-4 removed
1-#!/usr/bin/env node2-'use strict';3-4-process.exit(2);added:test/fixtures/fail.js+4 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+process.exit(2);deleted:test/fixtures/forever-4 removed
1-#!/usr/bin/env node2-'use strict';3-4-setTimeout(() => {}, 1e8);added:test/fixtures/forever.js+2 added
1+#!/usr/bin/env node2+setTimeout(() => {}, 1e8);deleted:test/fixtures/max-buffer-6 removed
1-#!/usr/bin/env node2-'use strict';3-const output = process.argv[2] || 'stdout';4-const bytes = Number(process.argv[3] || 1e7);5-6-process[output].write('.'.repeat(bytes - 1) + '\n');added:test/fixtures/max-buffer.js+7 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+const output = process.argv[2] || 'stdout';5+const bytes = Number(process.argv[3] || 1e7);6+7+process[output].write('.'.repeat(bytes - 1) + '\n');deleted:test/fixtures/no-killable-12 removed
1-#!/usr/bin/env node2-'use strict';3-4-process.on('SIGTERM', () => {5- console.log('Received SIGTERM, but we ignore it');6-});7-8-process.send('');9-10-setInterval(() => {11- // Run forever12-}, 20000);added:test/fixtures/no-killable.js+12 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+process.on('SIGTERM', () => {5+ console.log('Received SIGTERM, but we ignore it');6+});7+8+process.send('');9+10+setInterval(() => {11+ // Run forever12+}, 20_000);deleted:test/fixtures/non-executable-2 removed
1-#!/usr/bin/env node2-'use strict';added:test/fixtures/non-executable.js+1 added
1+#!/usr/bin/env nodedeleted:test/fixtures/noop-3 removed
1-#!/usr/bin/env node2-'use strict';3-console.log(process.argv[2]);deleted:test/fixtures/noop-132-9 removed
1-#!/usr/bin/env node2-'use strict';3-4-process.stdout.write('1');5-process.stderr.write('3');6-7-setTimeout(() => {8- process.stdout.write('2');9-}, 1000);added:test/fixtures/noop-132.js+9 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+process.stdout.write('1');5+process.stderr.write('3');6+7+setTimeout(() => {8+ process.stdout.write('2');9+}, 1000);deleted:test/fixtures/noop-err-3 removed
1-#!/usr/bin/env node2-'use strict';3-console.error(process.argv[2]);added:test/fixtures/noop-err.js+4 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+console.error(process.argv[2]);deleted:test/fixtures/noop-throw-4 removed
1-#!/usr/bin/env node2-'use strict';3-console.error(process.argv[2]);4-process.exit(2);added:test/fixtures/noop-throw.js+5 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+console.error(process.argv[2]);5+process.exit(2);added:test/fixtures/noop.js+4 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+console.log(process.argv[2]);deleted:test/fixtures/send-9 removed
1-#!/usr/bin/env node2-'use strict';3-process.on('message', message => {4- if (message === 'ping') {5- process.send('pong');6- } else {7- throw new Error('Receive wrong message');8- }9-});added:test/fixtures/send.js+12 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+process.on('message', message => {5+ if (message === 'ping') {6+ process.send('pong');7+ } else {8+ throw new Error('Receive wrong message');9+ }10+});11+12+process.send('');deleted:test/fixtures/stdin-3 removed
1-#!/usr/bin/env node2-'use strict';3-process.stdin.pipe(process.stdout);added:test/fixtures/stdin.js+4 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+process.stdin.pipe(process.stdout);deleted:test/fixtures/sub-process-8 removed
1-#!/usr/bin/env node2-'use strict';3-const execa = require('../..');4-5-const cleanup = process.argv[2] === 'true';6-const detached = process.argv[3] === 'true';7-const subprocess = execa('node', ['./test/fixtures/forever'], {cleanup, detached});8-process.send(subprocess.pid);deleted:test/fixtures/sub-process-exit-17 removed
1-#!/usr/bin/env node2-'use strict';3-const execa = require('../..');4-5-const cleanup = process.argv[2] === 'true';6-const detached = process.argv[3] === 'true';7-8-const runChild = async () => {9- try {10- await execa('node', ['./test/fixtures/noop'], {cleanup, detached});11- } catch (error) {12- console.error(error);13- process.exit(1);14- }15-};16-17-runChild();added:test/fixtures/sub-process-exit.js+17 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {execa} from '../../index.js';4+5+const cleanup = process.argv[2] === 'true';6+const detached = process.argv[3] === 'true';7+8+const runChild = async () => {9+ try {10+ await execa('node', ['./test/fixtures/noop.js'], {cleanup, detached});11+ } catch (error) {12+ console.error(error);13+ process.exit(1);14+ }15+};16+17+runChild();added:test/fixtures/sub-process.js+8 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {execa} from '../../index.js';4+5+const cleanup = process.argv[2] === 'true';6+const detached = process.argv[3] === 'true';7+const subprocess = execa('node', ['./test/fixtures/forever.js'], {cleanup, detached});8+process.send(subprocess.pid);added:test/helpers/override-promise.js+11 added
1+// Can't use `test.before`, because `ava` needs `Promise`.2+const nativePromise = Promise;3+global.Promise = class BrokenPromise {4+ then() {5+ throw new Error('error');6+ }7+};8+9+export function restorePromise() {10+ global.Promise = nativePromise;11+}modified:test/command.js+33 added-31 removed
1-import path from 'path';1+import path from 'node:path';2+import process from 'node:process';3+import {fileURLToPath} from 'node:url';4 import test from 'ava';3-import execa from '..';5+import {execa, execaSync, execaCommand, execaCommandSync} from '../index.js';6 5-process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;7+process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;8 9 const command = async (t, expected, ...args) => {8- const {command: failCommand} = await t.throwsAsync(execa('fail', args));9- t.is(failCommand, `fail${expected}`);10+ const {command: failCommand} = await t.throwsAsync(execa('fail.js', args));11+ t.is(failCommand, `fail.js${expected}`);12 11- const {command} = await execa('noop', args);12- t.is(command, `noop${expected}`);13+ const {command} = await execa('noop.js', args);14+ t.is(command, `noop.js${expected}`);15 };16 17 command.title = (message, expected) => `command is: ${JSON.stringify(expected)}`;18 1 unmodified line20 test(command, ' baz quz', 'baz', 'quz');21 test(command, '');22 23 const testEscapedCommand = async (t, expected, args) => {22- const {escapedCommand: failEscapedCommand} = await t.throwsAsync(execa('fail', args));23- t.is(failEscapedCommand, `fail ${expected}`);24+ const {escapedCommand: failEscapedCommand} = await t.throwsAsync(execa('fail.js', args));25+ t.is(failEscapedCommand, `fail.js ${expected}`);26 27 const {escapedCommand: failEscapedCommandSync} = t.throws(() => {26- execa.sync('fail', args);28+ execaSync('fail.js', args);29 });28- t.is(failEscapedCommandSync, `fail ${expected}`);30+ t.is(failEscapedCommandSync, `fail.js ${expected}`);31 30- const {escapedCommand} = await execa('noop', args);31- t.is(escapedCommand, `noop ${expected}`);32+ const {escapedCommand} = await execa('noop.js', args);33+ t.is(escapedCommand, `noop.js ${expected}`);34 33- const {escapedCommand: escapedCommandSync} = execa.sync('noop', args);34- t.is(escapedCommandSync, `noop ${expected}`);35+ const {escapedCommand: escapedCommandSync} = execaSync('noop.js', args);36+ t.is(escapedCommandSync, `noop.js ${expected}`);37 };38 39 testEscapedCommand.title = (message, expected) => `escapedCommand is: ${JSON.stringify(expected)}`;40 2 unmodified lines43 test(testEscapedCommand, '"\\"foo\\""', ['"foo"']);44 test(testEscapedCommand, '"*"', ['*']);45 46 test('allow commands with spaces and no array arguments', async t => {45- const {stdout} = await execa('command with space');47+ const {stdout} = await execa('command with space.js');48 t.is(stdout, '');49 });50 51 test('allow commands with spaces and array arguments', async t => {50- const {stdout} = await execa('command with space', ['foo', 'bar']);52+ const {stdout} = await execa('command with space.js', ['foo', 'bar']);53 t.is(stdout, 'foo\nbar');54 });55 54-test('execa.command()', async t => {55- const {stdout} = await execa.command('node test/fixtures/echo foo bar');56+test('execaCommand()', async t => {57+ const {stdout} = await execaCommand('node test/fixtures/echo.js foo bar');58 t.is(stdout, 'foo\nbar');59 });60 59-test('execa.command() ignores consecutive spaces', async t => {60- const {stdout} = await execa.command('node test/fixtures/echo foo bar');61+test('execaCommand() ignores consecutive spaces', async t => {62+ const {stdout} = await execaCommand('node test/fixtures/echo.js foo bar');63 t.is(stdout, 'foo\nbar');64 });65 64-test('execa.command() allows escaping spaces in commands', async t => {65- const {stdout} = await execa.command('command\\ with\\ space foo bar');66+test('execaCommand() allows escaping spaces in commands', async t => {67+ const {stdout} = await execaCommand('command\\ with\\ space.js foo bar');68 t.is(stdout, 'foo\nbar');69 });70 69-test('execa.command() allows escaping spaces in arguments', async t => {70- const {stdout} = await execa.command('node test/fixtures/echo foo\\ bar');71+test('execaCommand() allows escaping spaces in arguments', async t => {72+ const {stdout} = await execaCommand('node test/fixtures/echo.js foo\\ bar');73 t.is(stdout, 'foo bar');74 });75 74-test('execa.command() escapes other whitespaces', async t => {75- const {stdout} = await execa.command('node test/fixtures/echo foo\tbar');76+test('execaCommand() escapes other whitespaces', async t => {77+ const {stdout} = await execaCommand('node test/fixtures/echo.js foo\tbar');78 t.is(stdout, 'foo\tbar');79 });80 79-test('execa.command() trims', async t => {80- const {stdout} = await execa.command(' node test/fixtures/echo foo bar ');81+test('execaCommand() trims', async t => {82+ const {stdout} = await execaCommand(' node test/fixtures/echo.js foo bar ');83 t.is(stdout, 'foo\nbar');84 });85 84-test('execa.command.sync()', t => {85- const {stdout} = execa.commandSync('node test/fixtures/echo foo bar');86+test('execaCommandSync()', t => {87+ const {stdout} = execaCommandSync('node test/fixtures/echo.js foo bar');88 t.is(stdout, 'foo\nbar');89 });modified:test/error.js+49 added-41 removed
1-import path from 'path';2-import childProcess from 'child_process';1+import path from 'node:path';2+import process from 'node:process';3+import childProcess from 'node:child_process';4+import {fileURLToPath} from 'node:url';5+import {promisify} from 'node:util';6 import test from 'ava';4-import execa from '..';7+import {execa, execaSync} from '../index.js';8 6-process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;9+const pExec = promisify(childProcess.exec);10 11+process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;12+13 const TIMEOUT_REGEXP = /timed out after/;14 15 const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);16 17 test('stdout/stderr/all available on errors', async t => {13- const {stdout, stderr, all} = await t.throwsAsync(execa('exit', ['2'], {all: true}), {message: getExitRegExp('2')});18+ const {stdout, stderr, all} = await t.throwsAsync(execa('exit.js', ['2'], {all: true}), {message: getExitRegExp('2')});19 t.is(typeof stdout, 'string');20 t.is(typeof stderr, 'string');21 t.is(typeof all, 'string');22 });23 19-const WRONG_COMMAND = process.platform === 'win32' ?20- '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.' :21- '';24+const WRONG_COMMAND = process.platform === 'win32'25+ ? '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.'26+ : '';27 28 test('stdout/stderr/all on process errors', async t => {29 const {stdout, stderr, all} = await t.throwsAsync(execa('wrong command', {all: true}));30 t.is(stdout, '');2 unmodified lines33 });34 35 test('stdout/stderr/all on process errors, in sync mode', t => {36 const {stdout, stderr, all} = t.throws(() => {32- execa.sync('wrong command');37+ execaSync('wrong command');38 });39 t.is(stdout, '');40 t.is(stderr, WRONG_COMMAND);41 t.is(all, undefined);42 });43 44 test('exitCode is 0 on success', async t => {40- const {exitCode} = await execa('noop', ['foo']);45+ const {exitCode} = await execa('noop.js', ['foo']);46 t.is(exitCode, 0);47 });48 49 const testExitCode = async (t, number) => {45- const {exitCode} = await t.throwsAsync(execa('exit', [`${number}`]), {message: getExitRegExp(number)});50+ const {exitCode} = await t.throwsAsync(execa('exit.js', [`${number}`]), {message: getExitRegExp(number)});51 t.is(exitCode, number);52 };53 54 test('exitCode is 2', testExitCode, 2);55 test('exitCode is 3', testExitCode, 3);56 test('exitCode is 4', testExitCode, 4);57 58 test('error.message contains the command', async t => {54- await t.throwsAsync(execa('exit', ['2', 'foo', 'bar']), {message: /exit 2 foo bar/});59+ await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});60 });61 62 test('error.message contains stdout/stderr if available', async t => {58- const {message} = await t.throwsAsync(execa('echo-fail'));63+ const {message} = await t.throwsAsync(execa('echo-fail.js'));64 t.true(message.includes('stderr'));65 t.true(message.includes('stdout'));66 });67 68 test('error.message does not contain stdout/stderr if not available', async t => {64- const {message} = await t.throwsAsync(execa('echo-fail', {stdio: 'ignore'}));69+ const {message} = await t.throwsAsync(execa('echo-fail.js', {stdio: 'ignore'}));70 t.false(message.includes('stderr'));71 t.false(message.includes('stdout'));72 });73 74 test('error.shortMessage does not contain stdout/stderr', async t => {70- const {shortMessage} = await t.throwsAsync(execa('echo-fail'));75+ const {shortMessage} = await t.throwsAsync(execa('echo-fail.js'));76 t.false(shortMessage.includes('stderr'));77 t.false(shortMessage.includes('stdout'));78 });79 80 test('Original error.message is kept', async t => {76- const {originalMessage} = await t.throwsAsync(execa('noop', {cwd: 1}));77- t.true(originalMessage.startsWith('The "options.cwd" property must be of type string. Received type number'));81+ const {originalMessage} = await t.throwsAsync(execa('noop.js', {cwd: 1}));82+ // On Node >=14.18.0, the error message is83+ // `The "options.cwd" property must be of type string or an instance of Buffer or URL. Received type number (1)`84+ t.true(originalMessage.startsWith('The "options.cwd" property must be of type string'));85+ t.true(originalMessage.includes('. Received type number'));86 });87 88 test('failed is false on success', async t => {81- const {failed} = await execa('noop', ['foo']);89+ const {failed} = await execa('noop.js', ['foo']);90 t.false(failed);91 });92 93 test('failed is true on failure', async t => {86- const {failed} = await t.throwsAsync(execa('exit', ['2']));94+ const {failed} = await t.throwsAsync(execa('exit.js', ['2']));95 t.true(failed);96 });97 98 test('error.killed is true if process was killed directly', async t => {91- const subprocess = execa('noop');99+ const subprocess = execa('noop.js');100 101 subprocess.kill();102 103 const {killed} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});104 t.true(killed);105 });106 107 test('error.killed is false if process was killed indirectly', async t => {100- const subprocess = execa('noop');108+ const subprocess = execa('noop.js');109 110 process.kill(subprocess.pid, 'SIGINT');111 112 // `process.kill()` is emulated by Node.js on Windows2 unmodified lines115 t.false(killed);116 });117 118 test('result.killed is false if not killed', async t => {111- const {killed} = await execa('noop');119+ const {killed} = await execa('noop.js');120 t.false(killed);121 });122 123 test('result.killed is false if not killed, in sync mode', t => {116- const {killed} = execa.sync('noop');124+ const {killed} = execaSync('noop.js');125 t.false(killed);126 });127 128 test('result.killed is false on process error', async t => {2 unmodified lines131 });132 133 test('result.killed is false on process error, in sync mode', t => {134 const {killed} = t.throws(() => {127- execa.sync('wrong command');135+ execaSync('wrong command');136 });137 t.false(killed);138 });139 140 if (process.platform === 'darwin') {133- test.cb('sanity check: child_process.exec also has killed.false if killed indirectly', t => {134- const {pid} = childProcess.exec('noop', error => {135- t.truthy(error);136- t.false(error.killed);137- t.end();138- });141+ test('sanity check: child_process.exec also has killed.false if killed indirectly', async t => {142+ const promise = pExec('noop.js');143 140- process.kill(pid, 'SIGINT');144+ process.kill(promise.child.pid, 'SIGINT');145+146+ const error = await t.throwsAsync(promise);147+ t.truthy(error);148+ t.false(error.killed);149 });150 }151 152 if (process.platform !== 'win32') {153 test('error.signal is SIGINT', async t => {146- const subprocess = execa('noop');154+ const subprocess = execa('noop.js');155 156 process.kill(subprocess.pid, 'SIGINT');157 158 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});159 t.is(signal, 'SIGINT');160 });161 162 test('error.signalDescription is defined', async t => {155- const subprocess = execa('noop');163+ const subprocess = execa('noop.js');164 165 process.kill(subprocess.pid, 'SIGINT');166 167 const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});168 t.is(signalDescription, 'User interruption with CTRL-C');169 });170 171 test('error.signal is SIGTERM', async t => {164- const subprocess = execa('noop');172+ const subprocess = execa('noop.js');173 174 process.kill(subprocess.pid, 'SIGTERM');175 176 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});177 t.is(signal, 'SIGTERM');178 });179 180 test('custom error.signal', async t => {173- const {signal} = await t.throwsAsync(execa('noop', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));181+ const {signal} = await t.throwsAsync(execa('noop.js', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));182 t.is(signal, 'SIGHUP');183 });184 185 test('exitCode is undefined on signal termination', async t => {178- const subprocess = execa('noop');186+ const subprocess = execa('noop.js');187 188 process.kill(subprocess.pid);189 190 const {exitCode} = await t.throwsAsync(subprocess);1 unmodified line192 });193 }194 195 test('result.signal is undefined for successful execution', async t => {188- const {signal} = await execa('noop');196+ const {signal} = await execa('noop.js');197 t.is(signal, undefined);198 });199 200 test('result.signal is undefined if process failed, but was not killed', async t => {193- const {signal} = await t.throwsAsync(execa('exit', [2]), {message: getExitRegExp('2')});201+ const {signal} = await t.throwsAsync(execa('exit.js', [2]), {message: getExitRegExp('2')});202 t.is(signal, undefined);203 });204 205 test('result.signalDescription is undefined for successful execution', async t => {198- const {signalDescription} = await execa('noop');206+ const {signalDescription} = await execa('noop.js');207 t.is(signalDescription, undefined);208 });209 210 test('error.code is undefined on success', async t => {203- const {code} = await execa('noop');211+ const {code} = await execa('noop.js');212 t.is(code, undefined);213 });214 215 test('error.code is defined on failure if applicable', async t => {208- const {code} = await t.throwsAsync(execa('noop', {cwd: 1}));216+ const {code} = await t.throwsAsync(execa('noop.js', {cwd: 1}));217 t.is(code, 'ERR_INVALID_ARG_TYPE');218 });modified:test/kill.js+36 added-34 removed
1-import path from 'path';1+import path from 'node:path';2+import process from 'node:process';3+import {fileURLToPath} from 'node:url';4 import test from 'ava';5 import pEvent from 'p-event';6 import isRunning from 'is-running';5-import execa from '..';7+import {execa, execaSync} from '../index.js';8 7-process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;9+process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;10 11 const TIMEOUT_REGEXP = /timed out after/;12 13 test('kill("SIGKILL") should terminate cleanly', async t => {12- const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});14+ const subprocess = execa('node', ['./test/fixtures/no-killable.js'], {stdio: ['ipc']});15 await pEvent(subprocess, 'message');16 17 subprocess.kill('SIGKILL');18 4 unmodified lines23 // `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).24 // Therefore, this feature and those tests do not make sense on Windows.25 if (process.platform !== 'win32') {26 test('`forceKillAfterTimeout: false` should not kill after a timeout', async t => {25- const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});27+ const subprocess = execa('node', ['./test/fixtures/no-killable.js'], {stdio: ['ipc']});28 await pEvent(subprocess, 'message');29 30 subprocess.kill('SIGTERM', {forceKillAfterTimeout: false});31 1 unmodified line33 subprocess.kill('SIGKILL');34 });35 36 test('`forceKillAfterTimeout: number` should kill after a timeout', async t => {35- const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});37+ const subprocess = execa('node', ['./test/fixtures/no-killable.js'], {stdio: ['ipc']});38 await pEvent(subprocess, 'message');39 40 subprocess.kill('SIGTERM', {forceKillAfterTimeout: 50});41 1 unmodified line43 t.is(signal, 'SIGKILL');44 });45 46 test('`forceKillAfterTimeout: true` should kill after a timeout', async t => {45- const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});47+ const subprocess = execa('node', ['./test/fixtures/no-killable.js'], {stdio: ['ipc']});48 await pEvent(subprocess, 'message');49 50 subprocess.kill('SIGTERM', {forceKillAfterTimeout: true});51 1 unmodified line53 t.is(signal, 'SIGKILL');54 });55 56 test('kill() with no arguments should kill after a timeout', async t => {55- const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});57+ const subprocess = execa('node', ['./test/fixtures/no-killable.js'], {stdio: ['ipc']});58 await pEvent(subprocess, 'message');59 60 subprocess.kill();61 2 unmodified lines64 });65 66 test('`forceKillAfterTimeout` should not be NaN', t => {67 t.throws(() => {66- execa('noop').kill('SIGTERM', {forceKillAfterTimeout: Number.NaN});68+ execa('noop.js').kill('SIGTERM', {forceKillAfterTimeout: Number.NaN});69 }, {instanceOf: TypeError, message: /non-negative integer/});70 });71 72 test('`forceKillAfterTimeout` should not be negative', t => {73 t.throws(() => {72- execa('noop').kill('SIGTERM', {forceKillAfterTimeout: -1});74+ execa('noop.js').kill('SIGTERM', {forceKillAfterTimeout: -1});75 }, {instanceOf: TypeError, message: /non-negative integer/});76 });77 }78 79 test('execa() returns a promise with kill()', t => {78- const {kill} = execa('noop', ['foo']);80+ const {kill} = execa('noop.js', ['foo']);81 t.is(typeof kill, 'function');82 });83 84 test('timeout kills the process if it times out', async t => {83- const {killed, timedOut} = await t.throwsAsync(execa('noop', {timeout: 1}), TIMEOUT_REGEXP);85+ const {killed, timedOut} = await t.throwsAsync(execa('noop.js', {timeout: 1}), {message: TIMEOUT_REGEXP});86 t.false(killed);87 t.true(timedOut);88 });89 90 test('timeout kills the process if it times out, in sync mode', async t => {91 const {killed, timedOut} = await t.throws(() => {90- execa.sync('noop', {timeout: 1, message: TIMEOUT_REGEXP});92+ execaSync('noop.js', {timeout: 1, message: TIMEOUT_REGEXP});93 });94 t.false(killed);95 t.true(timedOut);96 });97 98 test('timeout does not kill the process if it does not time out', async t => {97- const {timedOut} = await execa('delay', ['500'], {timeout: 1e8});99+ const {timedOut} = await execa('delay.js', ['500'], {timeout: 1e8});100 t.false(timedOut);101 });102 103 const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;104 105 test('timeout must not be negative', async t => {106 await t.throws(() => {105- execa('noop', {timeout: -1});106- }, INVALID_TIMEOUT_REGEXP);107+ execa('noop.js', {timeout: -1});108+ }, {message: INVALID_TIMEOUT_REGEXP});109 });110 111 test('timeout must be an integer', async t => {112 await t.throws(() => {111- execa('noop', {timeout: false});112- }, INVALID_TIMEOUT_REGEXP);113+ execa('noop.js', {timeout: false});114+ }, {message: INVALID_TIMEOUT_REGEXP});115 });116 117 test('timedOut is false if timeout is undefined', async t => {116- const {timedOut} = await execa('noop');118+ const {timedOut} = await execa('noop.js');119 t.false(timedOut);120 });121 122 test('timedOut is false if timeout is 0', async t => {121- const {timedOut} = await execa('noop', {timeout: 0});123+ const {timedOut} = await execa('noop.js', {timeout: 0});124 t.false(timedOut);125 });126 127 test('timedOut is false if timeout is undefined and exit code is 0 in sync mode', t => {126- const {timedOut} = execa.sync('noop');128+ const {timedOut} = execaSync('noop.js');129 t.false(timedOut);130 });131 132 // When child process exits before parent process133 const spawnAndExit = async (t, cleanup, detached) => {132- await t.notThrowsAsync(execa('sub-process-exit', [cleanup, detached]));134+ await t.notThrowsAsync(execa('sub-process-exit.js', [cleanup, detached]));135 };136 137 test('spawnAndExit', spawnAndExit, false, false);138 test('spawnAndExit cleanup', spawnAndExit, true, false);1 unmodified line140 test('spawnAndExit cleanup detached', spawnAndExit, true, true);141 142 // When parent process exits before child process143 const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {142- const subprocess = execa('sub-process', [cleanup, detached], {stdio: ['ignore', 'ignore', 'ignore', 'ipc']});144+ const subprocess = execa('sub-process.js', [cleanup, detached], {stdio: ['ignore', 'ignore', 'ignore', 'ipc']});145 146 const pid = await pEvent(subprocess, 'message');147 t.true(Number.isInteger(pid));148 t.true(isRunning(pid));30 unmodified lines179 test('removes exit handler on exit', async t => {180 // @todo this relies on `signal-exit` internals181 const emitter = process.__signal_exit_emitter__;182 181- const subprocess = execa('noop');183+ const subprocess = execa('noop.js');184 const listener = emitter.listeners('exit').pop();185 186 await new Promise((resolve, reject) => {187 subprocess.on('error', reject);10 unmodified lines198 t.true(subprocess.killed);199 });200 201 test('result.isCanceled is false when spawned.cancel() isn\'t called (success)', async t => {200- const {isCanceled} = await execa('noop');202+ const {isCanceled} = await execa('noop.js');203 t.false(isCanceled);204 });205 206 test('result.isCanceled is false when spawned.cancel() isn\'t called (failure)', async t => {205- const {isCanceled} = await t.throwsAsync(execa('fail'));207+ const {isCanceled} = await t.throwsAsync(execa('fail.js'));208 t.false(isCanceled);209 });210 211 test('result.isCanceled is false when spawned.cancel() isn\'t called in sync mode (success)', t => {210- const {isCanceled} = execa.sync('noop');212+ const {isCanceled} = execaSync('noop.js');213 t.false(isCanceled);214 });215 216 test('result.isCanceled is false when spawned.cancel() isn\'t called in sync mode (failure)', t => {217 const {isCanceled} = t.throws(() => {216- execa.sync('fail');218+ execaSync('fail.js');219 });220 t.false(isCanceled);221 });222 223 test('calling cancel method throws an error with message "Command was canceled"', async t => {222- const subprocess = execa('noop');224+ const subprocess = execa('noop.js');225 subprocess.cancel();226 await t.throwsAsync(subprocess, {message: /Command was canceled/});227 });228 229 test('error.isCanceled is true when cancel method is used', async t => {228- const subprocess = execa('noop');230+ const subprocess = execa('noop.js');231 subprocess.cancel();232 const {isCanceled} = await t.throwsAsync(subprocess);233 t.true(isCanceled);234 });235 236 test('error.isCanceled is false when kill method is used', async t => {235- const subprocess = execa('noop');237+ const subprocess = execa('noop.js');238 subprocess.kill();239 const {isCanceled} = await t.throwsAsync(subprocess);240 t.false(isCanceled);241 });242 243 test('calling cancel method twice should show the same behaviour as calling it once', async t => {242- const subprocess = execa('noop');244+ const subprocess = execa('noop.js');245 subprocess.cancel();246 subprocess.cancel();247 const {isCanceled} = await t.throwsAsync(subprocess);248 t.true(isCanceled);249 t.true(subprocess.killed);250 });251 252 test('calling cancel method on a successfully completed process does not make result.isCanceled true', async t => {251- const subprocess = execa('noop');253+ const subprocess = execa('noop.js');254 const {isCanceled} = await subprocess;255 subprocess.cancel();256 t.false(isCanceled);257 });258 259 test('calling cancel method on a process which has been killed does not make error.isCanceled true', async t => {258- const subprocess = execa('noop');260+ const subprocess = execa('noop.js');261 subprocess.kill();262 const {isCanceled} = await t.throwsAsync(subprocess);263 t.false(isCanceled);264 });modified:test/node.js+24 added-20 removed
1-import path from 'path';1+import path from 'node:path';2+import process from 'node:process';3+import {fileURLToPath} from 'node:url';4 import test from 'ava';5 import pEvent from 'p-event';4-import execa from '..';6+import {execaNode} from '../index.js';7 6-process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;8+process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;9 10 async function inspectMacro(t, input) {11 const originalArgv = process.execArgv;12 process.execArgv = [input, '-e'];13 try {12- const subprocess = execa.node('console.log("foo")', {13- reject: false14+ const subprocess = execaNode('console.log("foo")', {15+ reject: false,16 });17 18 const {stdout, stderr} = await subprocess;19 4 unmodified lines24 }25 }26 27 test('node()', async t => {26- const {exitCode} = await execa.node('test/fixtures/noop');28+ const {exitCode} = await execaNode('test/fixtures/noop.js');29 t.is(exitCode, 0);30 });31 32 test('node pipe stdout', async t => {31- const {stdout} = await execa.node('test/fixtures/noop', ['foo'], {32- stdout: 'pipe'33+ const {stdout} = await execaNode('test/fixtures/noop.js', ['foo'], {34+ stdout: 'pipe',35 });36 37 t.is(stdout, 'foo');38 });39 40 test('node correctly use nodePath', async t => {39- const {stdout} = await execa.node(process.platform === 'win32' ? 'hello.cmd' : 'hello.sh', {41+ const {stdout} = await execaNode(process.platform === 'win32' ? 'hello.cmd' : 'hello.sh', {42 stdout: 'pipe',43 nodePath: process.platform === 'win32' ? 'cmd.exe' : 'bash',42- nodeOptions: process.platform === 'win32' ? ['/c'] : []44+ nodeOptions: process.platform === 'win32' ? ['/c'] : [],45 });46 47 t.is(stdout, 'Hello World');48 });49 50 test('node pass on nodeOptions', async t => {49- const {stdout} = await execa.node('console.log("foo")', {51+ const {stdout} = await execaNode('console.log("foo")', {52 stdout: 'pipe',51- nodeOptions: ['-e']53+ nodeOptions: ['-e'],54 });55 56 t.is(stdout, 'foo');57 });58 59 test.serial(60 'node removes --inspect from nodeOptions when defined by parent process',61 inspectMacro,60- '--inspect'62+ '--inspect',63 );64 65 test.serial(66 'node removes --inspect=9222 from nodeOptions when defined by parent process',67 inspectMacro,66- '--inspect=9222'68+ '--inspect=9222',69 );70 71 test.serial(72 'node removes --inspect-brk from nodeOptions when defined by parent process',73 inspectMacro,72- '--inspect-brk'74+ '--inspect-brk',75 );76 77 test.serial(78 'node removes --inspect-brk=9222 from nodeOptions when defined by parent process',79 inspectMacro,78- '--inspect-brk=9222'80+ '--inspect-brk=9222',81 );82 83 test.serial(84 'node should not remove --inspect when passed through nodeOptions',85 async t => {84- const {stdout, stderr} = await execa.node('console.log("foo")', {86+ const {stdout, stderr} = await execaNode('console.log("foo")', {87 reject: false,86- nodeOptions: ['--inspect', '-e']88+ nodeOptions: ['--inspect', '-e'],89 });90 91 t.is(stdout, 'foo');92 t.true(stderr.includes('Debugger listening'));91- }93+ },94 );95 96 test('node\'s forked script has a communication channel', async t => {95- const subprocess = execa.node('test/fixtures/send');97+ const subprocess = execaNode('test/fixtures/send.js');98+ await pEvent(subprocess, 'message');99+100 subprocess.send('ping');101 102 const message = await pEvent(subprocess, 'message');103 t.is(message, 'pong');1 unmodified linemodified:test/override-promise.js+11 added-13 removed
1-import path from 'path';1+import path from 'node:path';2+import process from 'node:process';3+import {fileURLToPath} from 'node:url';4 import test from 'ava';5+// The helper module overrides Promise on import so has to be imported before `execa`.6+// Can't use top-level await (TLA) + `import(…)` since Node.js 12 doesn't support TLA.7+import {restorePromise} from './helpers/override-promise.js';8+// eslint-disable-next-line import/order9+import {execa} from '../index.js';10 4-process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;11+restorePromise();12 6-// Can't use `test.before`, because `ava` needs `Promise`.7-// Can't use `import(…)` either, because `execa` is not an ES Module.8-const nativePromise = Promise;9-global.Promise = class BrokenPromise {10- then() {11- throw new Error('error');12- }13-};14-const execa = require('..');15-global.Promise = nativePromise;13+process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;14 15 test('should work with third-party Promise', async t => {18- const {stdout} = await execa('noop', ['foo']);16+ const {stdout} = await execa('noop.js', ['foo']);17 t.is(stdout, 'foo');18 });modified:test/promise.js+10 added-9 removed
1-import path from 'path';1+import path from 'node:path';2+import process from 'node:process';3+import {fileURLToPath} from 'node:url';4 import test from 'ava';3-import execa from '..';5+import {execa} from '../index.js';6 5-process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;7+process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;8 9 test('promise methods are not enumerable', t => {8- const descriptors = Object.getOwnPropertyDescriptors(execa('noop'));9- // eslint-disable-next-line promise/prefer-await-to-then10+ const descriptors = Object.getOwnPropertyDescriptors(execa('noop.js'));11 t.false(descriptors.then.enumerable);12 t.false(descriptors.catch.enumerable);13 t.false(descriptors.finally.enumerable);14 });15 16 test('finally function is executed on success', async t => {17 let isCalled = false;17- const {stdout} = await execa('noop', ['foo']).finally(() => {18+ const {stdout} = await execa('noop.js', ['foo']).finally(() => {19 isCalled = true;20 });21 t.is(isCalled, true);22 t.is(stdout, 'foo');23 });24 25 test('finally function is executed on failure', async t => {26 let isError = false;26- const {stdout, stderr} = await t.throwsAsync(execa('exit', ['2']).finally(() => {27+ const {stdout, stderr} = await t.throwsAsync(execa('exit.js', ['2']).finally(() => {28 isError = true;29 }));30 t.is(isError, true);31 t.is(typeof stdout, 'string');32 t.is(typeof stderr, 'string');33 });34 35 test('throw in finally function bubbles up on success', async t => {35- const {message} = await t.throwsAsync(execa('noop', ['foo']).finally(() => {36+ const {message} = await t.throwsAsync(execa('noop.js', ['foo']).finally(() => {37 throw new Error('called');38 }));39 t.is(message, 'called');40 });41 42 test('throw in finally bubbles up on error', async t => {42- const {message} = await t.throwsAsync(execa('exit', ['2']).finally(() => {43+ const {message} = await t.throwsAsync(execa('exit.js', ['2']).finally(() => {44 throw new Error('called');45 }));46 t.is(message, 'called');47 });modified:test/stdio.js+5 added-5 removed
1-import {inspect} from 'util';1+import {inspect} from 'node:util';2 import test from 'ava';3-import normalizeStdio from '../lib/stdio';3+import {normalizeStdio, normalizeStdioNode} from '../lib/stdio.js';4 5 const macro = (t, input, expected, func) => {6 if (expected instanceof Error) {7 t.throws(() => {8 normalizeStdio(input);9- }, expected.message);9+ }, {message: expected.message});10 return;11 }12 13 t.deepEqual(func(input), expected);32 unmodified lines46 test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));47 test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));48 test(stdioMacro, {stdin: 0, stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));49 50-const forkMacro = (...args) => macro(...args, normalizeStdio.node);51-forkMacro.title = macroTitle('execa.fork()');50+const forkMacro = (...args) => macro(...args, normalizeStdioNode);51+forkMacro.title = macroTitle('execaNode()');52 53 test(forkMacro, undefined, [undefined, undefined, undefined, 'ipc']);54 test(forkMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore', 'ipc']);55 test(forkMacro, {stdio: 'ipc'}, 'ipc');11 unmodified linesmodified:test/stream.js+43 added-40 removed
1-import path from 'path';2-import fs from 'fs';3-import Stream from 'stream';1+import {Buffer} from 'node:buffer';2+import path from 'node:path';3+import process from 'node:process';4+import fs from 'node:fs';5+import {fileURLToPath} from 'node:url';6+import Stream from 'node:stream';7 import test from 'ava';8 import getStream from 'get-stream';9 import tempfile from 'tempfile';7-import execa from '..';10+import {execa, execaSync} from '../index.js';11 9-process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;12+process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;13 14 test('buffer', async t => {12- const {stdout} = await execa('noop', ['foo'], {encoding: null});15+ const {stdout} = await execa('noop.js', ['foo'], {encoding: null});16 t.true(Buffer.isBuffer(stdout));17 t.is(stdout.toString(), 'foo');18 });19 20 test('pass `stdout` to a file descriptor', async t => {21 const file = tempfile('.txt');19- await execa('test/fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});22+ await execa('test/fixtures/noop.js', ['foo bar'], {stdout: fs.openSync(file, 'w')});23 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');24 });25 26 test('pass `stderr` to a file descriptor', async t => {27 const file = tempfile('.txt');25- await execa('test/fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});28+ await execa('test/fixtures/noop-err.js', ['foo bar'], {stderr: fs.openSync(file, 'w')});29 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');30 });31 32 test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {30- const {all} = await execa('noop-132', {all: true});33+ const {all} = await execa('noop-132.js', {all: true});34 t.is(all, '132');35 });36 37 test('result.all is undefined unless opts.all is true', async t => {35- const {all} = await execa('noop');38+ const {all} = await execa('noop.js');39 t.is(all, undefined);40 });41 42 test('stdout/stderr/all are undefined if ignored', async t => {40- const {stdout, stderr, all} = await execa('noop', {stdio: 'ignore', all: true});43+ const {stdout, stderr, all} = await execa('noop.js', {stdio: 'ignore', all: true});44 t.is(stdout, undefined);45 t.is(stderr, undefined);46 t.is(all, undefined);47 });48 49 test('stdout/stderr/all are undefined if ignored in sync mode', t => {47- const {stdout, stderr, all} = execa.sync('noop', {stdio: 'ignore', all: true});50+ const {stdout, stderr, all} = execaSync('noop.js', {stdio: 'ignore', all: true});51 t.is(stdout, undefined);52 t.is(stderr, undefined);53 t.is(all, undefined);54 });55 56 test('input option can be a String', async t => {54- const {stdout} = await execa('stdin', {input: 'foobar'});57+ const {stdout} = await execa('stdin.js', {input: 'foobar'});58 t.is(stdout, 'foobar');59 });60 61 test('input option can be a Buffer', async t => {59- const {stdout} = await execa('stdin', {input: 'testing12'});62+ const {stdout} = await execa('stdin.js', {input: 'testing12'});63 t.is(stdout, 'testing12');64 });65 66 test('input can be a Stream', async t => {67 const stream = new Stream.PassThrough();68 stream.write('howdy');69 stream.end();67- const {stdout} = await execa('stdin', {input: stream});70+ const {stdout} = await execa('stdin.js', {input: stream});71 t.is(stdout, 'howdy');72 });73 74 test('you can write to child.stdin', async t => {72- const subprocess = execa('stdin');75+ const subprocess = execa('stdin.js');76 subprocess.stdin.end('unicorns');77 t.is((await subprocess).stdout, 'unicorns');78 });79 80 test('input option can be a String - sync', t => {78- const {stdout} = execa.sync('stdin', {input: 'foobar'});81+ const {stdout} = execaSync('stdin.js', {input: 'foobar'});82 t.is(stdout, 'foobar');83 });84 85 test('input option can be a Buffer - sync', t => {83- const {stdout} = execa.sync('stdin', {input: Buffer.from('testing12', 'utf8')});86+ const {stdout} = execaSync('stdin.js', {input: Buffer.from('testing12', 'utf8')});87 t.is(stdout, 'testing12');88 });89 90 test('opts.stdout:ignore - stdout will not collect data', async t => {88- const {stdout} = await execa('stdin', {91+ const {stdout} = await execa('stdin.js', {92 input: 'hello',90- stdio: [undefined, 'ignore', undefined]93+ stdio: [undefined, 'ignore', undefined],94 });95 t.is(stdout, undefined);96 });97 98 test('helpful error trying to provide an input stream in sync mode', t => {99 t.throws(100 () => {98- execa.sync('stdin', {input: new Stream.PassThrough()});101+ execaSync('stdin.js', {input: new Stream.PassThrough()});102 },100- /The `input` option cannot be a stream in sync mode/103+ {message: /The `input` option cannot be a stream in sync mode/},104 );105 });106 107 test('maxBuffer affects stdout', async t => {105- await t.notThrowsAsync(execa('max-buffer', ['stdout', '10'], {maxBuffer: 10}));106- const {stdout, all} = await t.throwsAsync(execa('max-buffer', ['stdout', '11'], {maxBuffer: 10, all: true}), /max-buffer stdout/);108+ await t.notThrowsAsync(execa('max-buffer.js', ['stdout', '10'], {maxBuffer: 10}));109+ const {stdout, all} = await t.throwsAsync(execa('max-buffer.js', ['stdout', '11'], {maxBuffer: 10, all: true}), {message: /max-buffer.js stdout/});110 t.is(stdout, '.'.repeat(10));111 t.is(all, '.'.repeat(10));112 });113 114 test('maxBuffer affects stderr', async t => {112- await t.notThrowsAsync(execa('max-buffer', ['stderr', '10'], {maxBuffer: 10}));113- const {stderr, all} = await t.throwsAsync(execa('max-buffer', ['stderr', '11'], {maxBuffer: 10, all: true}), /max-buffer stderr/);115+ await t.notThrowsAsync(execa('max-buffer.js', ['stderr', '10'], {maxBuffer: 10}));116+ const {stderr, all} = await t.throwsAsync(execa('max-buffer.js', ['stderr', '11'], {maxBuffer: 10, all: true}), {message: /max-buffer.js stderr/});117 t.is(stderr, '.'.repeat(10));118 t.is(all, '.'.repeat(10));119 });120 121 test('do not buffer stdout when `buffer` set to `false`', async t => {119- const promise = execa('max-buffer', ['stdout', '10'], {buffer: false});122+ const promise = execa('max-buffer.js', ['stdout', '10'], {buffer: false});123 const [result, stdout] = await Promise.all([124 promise,122- getStream(promise.stdout)125+ getStream(promise.stdout),126 ]);127 128 t.is(result.stdout, undefined);129 t.is(stdout, '.........\n');130 });131 132 test('do not buffer stderr when `buffer` set to `false`', async t => {130- const promise = execa('max-buffer', ['stderr', '10'], {buffer: false});133+ const promise = execa('max-buffer.js', ['stderr', '10'], {buffer: false});134 const [result, stderr] = await Promise.all([135 promise,133- getStream(promise.stderr)136+ getStream(promise.stderr),137 ]);138 139 t.is(result.stderr, undefined);140 t.is(stderr, '.........\n');141 });142 143 test('do not buffer when streaming', async t => {141- const {stdout} = execa('max-buffer', ['stdout', '21'], {maxBuffer: 10});144+ const {stdout} = execa('max-buffer.js', ['stdout', '21'], {maxBuffer: 10});145 const result = await getStream(stdout);146 t.is(result, '....................\n');147 });148 149 test('buffer: false > promise resolves', async t => {147- await t.notThrowsAsync(execa('noop', {buffer: false}));150+ await t.notThrowsAsync(execa('noop.js', {buffer: false}));151 });152 153 test('buffer: false > promise resolves when output is big but is not pipable', async t => {151- await t.notThrowsAsync(execa('max-buffer', {buffer: false, stdout: 'ignore'}));154+ await t.notThrowsAsync(execa('max-buffer.js', {buffer: false, stdout: 'ignore'}));155 });156 157 test('buffer: false > promise resolves when output is big and is read', async t => {155- const subprocess = execa('max-buffer', {buffer: false});158+ const subprocess = execa('max-buffer.js', {buffer: false});159 subprocess.stdout.resume();160 subprocess.stderr.resume();161 await t.notThrowsAsync(subprocess);162 });163 164 test('buffer: false > promise resolves when output is big and "all" is used and is read', async t => {162- const subprocess = execa('max-buffer', {buffer: false, all: true});165+ const subprocess = execa('max-buffer.js', {buffer: false, all: true});166 subprocess.all.resume();167 await t.notThrowsAsync(subprocess);168 });169 170 test('buffer: false > promise rejects when process returns non-zero', async t => {168- const subprocess = execa('fail', {buffer: false});171+ const subprocess = execa('fail.js', {buffer: false});172 const {exitCode} = await t.throwsAsync(subprocess);173 t.is(exitCode, 2);174 });175 176 test('can use all: true with stdout: ignore', async t => {174- await t.notThrowsAsync(execa('max-buffer', {buffer: false, stdout: 'ignore', all: true}));177+ await t.notThrowsAsync(execa('max-buffer.js', {buffer: false, stdout: 'ignore', all: true}));178 });179 180 test('can use all: true with stderr: ignore', async t => {178- await t.notThrowsAsync(execa('max-buffer', ['stderr'], {buffer: false, stderr: 'ignore', all: true}));181+ await t.notThrowsAsync(execa('max-buffer.js', ['stderr'], {buffer: false, stderr: 'ignore', all: true}));182 });183 184 const BUFFER_TIMEOUT = 1e3;185 186 // On Unix (not Windows), a process won't exit if stdout has not been read.187 if (process.platform !== 'win32') {188 test.serial('buffer: false > promise does not resolve when output is big and is not read', async t => {186- const {timedOut} = await t.throwsAsync(execa('max-buffer', {buffer: false, timeout: BUFFER_TIMEOUT}));189+ const {timedOut} = await t.throwsAsync(execa('max-buffer.js', {buffer: false, timeout: BUFFER_TIMEOUT}));190 t.true(timedOut);191 });192 193 test.serial('buffer: false > promise does not resolve when output is big and "all" is used but not read', async t => {191- const subprocess = execa('max-buffer', {buffer: false, all: true, timeout: BUFFER_TIMEOUT});194+ const subprocess = execa('max-buffer.js', {buffer: false, all: true, timeout: BUFFER_TIMEOUT});195 subprocess.stdout.resume();196 subprocess.stderr.resume();197 const {timedOut} = await t.throwsAsync(subprocess);198 t.true(timedOut);2 unmodified linesmodified:test/test.js+40 added-38 removed
1-import path from 'path';1+import path from 'node:path';2+import process from 'node:process';3+import {fileURLToPath} from 'node:url';4 import test from 'ava';5 import isRunning from 'is-running';6 import getNode from 'get-node';5-import execa from '..';7+import {execa, execaSync} from '../index.js';8 7-process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;9+process.env.PATH = fileURLToPath(new URL('./fixtures', import.meta.url)) + path.delimiter + process.env.PATH;10 process.env.FOO = 'foo';11 12 const ENOENT_REGEXP = process.platform === 'win32' ? /failed with exit code 1/ : /spawn.* ENOENT/;13 14 test('execa()', async t => {13- const {stdout} = await execa('noop', ['foo']);15+ const {stdout} = await execa('noop.js', ['foo']);16 t.is(stdout, 'foo');17 });18 19 if (process.platform === 'win32') {7 unmodified lines27 t.is(stdout, 'Hello World');28 });29 }30 29-test('execa.sync()', t => {30- const {stdout} = execa.sync('noop', ['foo']);31+test('execaSync()', t => {32+ const {stdout} = execaSync('noop.js', ['foo']);33 t.is(stdout, 'foo');34 });35 34-test('execa.sync() throws error if written to stderr', t => {36+test('execaSync() throws error if written to stderr', t => {37 t.throws(() => {36- execa.sync('foo');37- }, ENOENT_REGEXP);38+ execaSync('foo');39+ }, {message: ENOENT_REGEXP});40 });41 42 test('skip throwing when using reject option', async t => {41- const {exitCode} = await execa('fail', {reject: false});43+ const {exitCode} = await execa('fail.js', {reject: false});44 t.is(exitCode, 2);45 });46 47 test('skip throwing when using reject option in sync mode', t => {46- const {exitCode} = execa.sync('fail', {reject: false});48+ const {exitCode} = execaSync('fail.js', {reject: false});49 t.is(exitCode, 2);50 });51 52 test('stripFinalNewline: true', async t => {51- const {stdout} = await execa('noop', ['foo']);53+ const {stdout} = await execa('noop.js', ['foo']);54 t.is(stdout, 'foo');55 });56 57 test('stripFinalNewline: false', async t => {56- const {stdout} = await execa('noop', ['foo'], {stripFinalNewline: false});58+ const {stdout} = await execa('noop.js', ['foo'], {stripFinalNewline: false});59 t.is(stdout, 'foo\n');60 });61 62 test('stripFinalNewline on failure', async t => {61- const {stderr} = await t.throwsAsync(execa('noop-throw', ['foo'], {stripFinalNewline: true}));63+ const {stderr} = await t.throwsAsync(execa('noop-throw.js', ['foo'], {stripFinalNewline: true}));64 t.is(stderr, 'foo');65 });66 67 test('stripFinalNewline in sync mode', t => {66- const {stdout} = execa.sync('noop', ['foo'], {stripFinalNewline: true});68+ const {stdout} = execaSync('noop.js', ['foo'], {stripFinalNewline: true});69 t.is(stdout, 'foo');70 });71 72 test('stripFinalNewline in sync mode on failure', t => {73 const {stderr} = t.throws(() => {72- execa.sync('noop-throw', ['foo'], {stripFinalNewline: true});74+ execaSync('noop-throw.js', ['foo'], {stripFinalNewline: true});75 });76 t.is(stderr, 'foo');77 });78 1 unmodified line80 await t.notThrowsAsync(execa('ava', ['--version'], {preferLocal: true, env: {Path: '', PATH: ''}}));81 });82 83 test('preferLocal: false', async t => {82- await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: {Path: '', PATH: ''}}), ENOENT_REGEXP);84+ await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: {Path: '', PATH: ''}}), {message: ENOENT_REGEXP});85 });86 87 test('preferLocal: undefined', async t => {86- await t.throwsAsync(execa('ava', ['--version'], {env: {Path: '', PATH: ''}}), ENOENT_REGEXP);88+ await t.throwsAsync(execa('ava', ['--version'], {env: {Path: '', PATH: ''}}), {message: ENOENT_REGEXP});89 });90 91 test('localDir option', async t => {92 const command = process.platform === 'win32' ? 'echo %PATH%' : 'echo $PATH';8 unmodified lines101 t.true(stdout.includes('6.0.0'));102 });103 104 test('stdin errors are handled', async t => {103- const subprocess = execa('noop');105+ const subprocess = execa('noop.js');106 subprocess.stdin.emit('error', new Error('test'));105- await t.throwsAsync(subprocess, /test/);107+ await t.throwsAsync(subprocess, {message: /test/});108 });109 110 test('child process errors are handled', async t => {109- const subprocess = execa('noop');111+ const subprocess = execa('noop.js');112 subprocess.emit('error', new Error('test'));111- await t.throwsAsync(subprocess, /test/);113+ await t.throwsAsync(subprocess, {message: /test/});114 });115 116 test('child process errors rejects promise right away', async t => {115- const subprocess = execa('noop');117+ const subprocess = execa('noop.js');118 subprocess.emit('error', new Error('test'));117- await t.throwsAsync(subprocess, /test/);119+ await t.throwsAsync(subprocess, {message: /test/});120 });121 122 test('execa() returns a promise with pid', t => {121- const {pid} = execa('noop', ['foo']);123+ const {pid} = execa('noop.js', ['foo']);124 t.is(typeof pid, 'number');125 });126 127 test('child_process.spawn() propagated errors have correct shape', t => {126- const subprocess = execa('noop', {uid: -1});128+ const subprocess = execa('noop.js', {uid: -1});129 t.notThrows(() => {130 subprocess.catch(() => {});131 subprocess.unref();132 subprocess.on('error', () => {});133 });134 });135 136 test('child_process.spawn() errors are propagated', async t => {135- const {failed} = await t.throwsAsync(execa('noop', {uid: -1}));137+ const {failed} = await t.throwsAsync(execa('noop.js', {uid: -1}));138 t.true(failed);139 });140 141 test('child_process.spawnSync() errors are propagated with a correct shape', t => {142 const {failed} = t.throws(() => {141- execa.sync('noop', {timeout: -1});143+ execaSync('noop.js', {timeout: -1});144 });145 t.true(failed);146 });147 148 test('do not try to consume streams twice', async t => {147- const subprocess = execa('noop', ['foo']);149+ const subprocess = execa('noop.js', ['foo']);150 t.is((await subprocess).stdout, 'foo');151 t.is((await subprocess).stdout, 'foo');152 });153 154 test('use relative path with \'..\' chars', async t => {153- const pathViaParentDir = path.join('..', path.basename(path.dirname(__dirname)), 'test', 'fixtures', 'noop');155+ const pathViaParentDir = path.join('..', path.basename(fileURLToPath(new URL('..', import.meta.url))), 'test', 'fixtures', 'noop.js');156 const {stdout} = await execa(pathViaParentDir, ['foo']);157 t.is(stdout, 'foo');158 });159 160 if (process.platform !== 'win32') {161 test('execa() rejects if running non-executable', async t => {160- const subprocess = execa('non-executable');162+ const subprocess = execa('non-executable.js');163 await t.throwsAsync(subprocess);164 });165 166 test('execa() rejects with correct error and doesn\'t throw if running non-executable with input', async t => {167 // On Node <12.6.0, `EACCESS` is emitted on `childProcess`.168 // On Node >=12.6.0, `EPIPE` is emitted on `childProcess.stdin`.167- await t.throwsAsync(execa('non-executable', {input: 'Hey!'}), /EACCES|EPIPE/);169+ await t.throwsAsync(execa('non-executable.js', {input: 'Hey!'}), {message: /EACCES|EPIPE/});170 });171 }172 173 if (process.platform !== 'win32') {9 unmodified lines183 });184 }185 186 test('use environment variables by default', async t => {185- const {stdout} = await execa('environment');187+ const {stdout} = await execa('environment.js');188 t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);189 });190 191 test('extend environment variables by default', async t => {190- const {stdout} = await execa('environment', [], {env: {BAR: 'bar'}});192+ const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar'}});193 t.deepEqual(stdout.split('\n'), ['foo', 'bar']);194 });195 196 test('do not extend environment with `extendEnv: false`', async t => {195- const {stdout} = await execa('environment', [], {env: {BAR: 'bar', PATH: process.env.PATH}, extendEnv: false});197+ const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', PATH: process.env.PATH}, extendEnv: false});198 t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);199 });200 201 test('can use `options.shell: true`', async t => {200- const {stdout} = await execa('node test/fixtures/noop foo', {shell: true});202+ const {stdout} = await execa('node test/fixtures/noop.js foo', {shell: true});203 t.is(stdout, 'foo');204 });205 206 test('can use `options.shell: string`', async t => {207 const shell = process.platform === 'win32' ? 'cmd.exe' : '/bin/bash';206- const {stdout} = await execa('node test/fixtures/noop foo', {shell});208+ const {stdout} = await execa('node test/fixtures/noop.js foo', {shell});209 t.is(stdout, 'foo');210 });211 212 test('use extend environment with `extendEnv: true` and `shell: true`', async t => {4 unmodified lines217 delete process.env.TEST;218 });219 220 test('detach child process', async t => {219- const {stdout} = await execa('detach');221+ const {stdout} = await execa('detach.js');222 const pid = Number(stdout);223 t.true(Number.isInteger(pid));224 t.true(isRunning(pid));225 2 unmodified linesmodified:index.d.ts+424 added-436 removed
1-/// <reference types="node"/>2-import {ChildProcess} from 'child_process';3-import {Stream, Readable as ReadableStream} from 'stream';1+import {Buffer} from 'node:buffer';2+import {ChildProcess} from 'node:child_process';3+import {Stream, Readable as ReadableStream} from 'node:stream';4 5-declare namespace execa {6- type StdioOption =7- | 'pipe'8- | 'ipc'9- | 'ignore'10- | 'inherit'11- | Stream12- | number13- | undefined;5+export type StdioOption =6+ | 'pipe'7+ | 'ipc'8+ | 'ignore'9+ | 'inherit'10+ | Stream11+ | number12+ | undefined;13 15- interface CommonOptions<EncodingType> {16- /**17- Kill the spawned process when the parent process exits unless either:18- - the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)19- - the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit14+export interface CommonOptions<EncodingType> {15+ /**16+ Kill the spawned process when the parent process exits unless either:17+ - the spawned process is [`detached`](https://nodejs.org/api/child_process.html#child_process_options_detached)18+ - the parent process is terminated abruptly, for example, with `SIGKILL` as opposed to `SIGTERM` or a normal exit19 21- @default true22- */23- readonly cleanup?: boolean;20+ @default true21+ */22+ readonly cleanup?: boolean;23 25- /**26- Prefer locally installed binaries when looking for a binary to execute.24+ /**25+ Prefer locally installed binaries when looking for a binary to execute.26 28- If you `$ npm install foo`, you can then `execa('foo')`.27+ If you `$ npm install foo`, you can then `execa('foo')`.28 30- @default false31- */32- readonly preferLocal?: boolean;29+ @default false30+ */31+ readonly preferLocal?: boolean;32 34- /**35- Preferred path to find locally installed binaries in (use with `preferLocal`).33+ /**34+ Preferred path to find locally installed binaries in (use with `preferLocal`).35 37- @default process.cwd()38- */39- readonly localDir?: string;36+ @default process.cwd()37+ */38+ readonly localDir?: string;39 41- /**42- Path to the Node.js executable to use in child processes.40+ /**41+ Path to the Node.js executable to use in child processes.42 44- This can be either an absolute path or a path relative to the `cwd` option.43+ This can be either an absolute path or a path relative to the `cwd` option.44 46- Requires `preferLocal` to be `true`.45+ Requires `preferLocal` to be `true`.46 48- For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process.47+ For example, this can be used together with [`get-node`](https://github.com/ehmicky/get-node) to run a specific Node.js version in a child process.48 50- @default process.execPath51- */52- readonly execPath?: string;49+ @default process.execPath50+ */51+ readonly execPath?: string;52 54- /**55- Buffer the output from the spawned process. When set to `false`, you must read the output of `stdout` and `stderr` (or `all` if the `all` option is `true`). Otherwise the returned promise will not be resolved/rejected.53+ /**54+ Buffer the output from the spawned process. When set to `false`, you must read the output of `stdout` and `stderr` (or `all` if the `all` option is `true`). Otherwise the returned promise will not be resolved/rejected.55 57- If the spawned process fails, `error.stdout`, `error.stderr`, and `error.all` will contain the buffered data.56+ If the spawned process fails, `error.stdout`, `error.stderr`, and `error.all` will contain the buffered data.57 59- @default true60- */61- readonly buffer?: boolean;58+ @default true59+ */60+ readonly buffer?: boolean;61 63- /**64- Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).62+ /**63+ Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).64 66- @default 'pipe'67- */68- readonly stdin?: StdioOption;65+ @default 'pipe'66+ */67+ readonly stdin?: StdioOption;68 70- /**71- Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).69+ /**70+ Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).71 73- @default 'pipe'74- */75- readonly stdout?: StdioOption;72+ @default 'pipe'73+ */74+ readonly stdout?: StdioOption;75 77- /**78- Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).76+ /**77+ Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).78 80- @default 'pipe'81- */82- readonly stderr?: StdioOption;79+ @default 'pipe'80+ */81+ readonly stderr?: StdioOption;82 84- /**85- Setting this to `false` resolves the promise with the error instead of rejecting it.83+ /**84+ Setting this to `false` resolves the promise with the error instead of rejecting it.85 87- @default true88- */89- readonly reject?: boolean;86+ @default true87+ */88+ readonly reject?: boolean;89 91- /**92- Add an `.all` property on the promise and the resolved value. The property contains the output of the process with `stdout` and `stderr` interleaved.90+ /**91+ Add an `.all` property on the promise and the resolved value. The property contains the output of the process with `stdout` and `stderr` interleaved.92 94- @default false95- */96- readonly all?: boolean;93+ @default false94+ */95+ readonly all?: boolean;96 98- /**99- Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.97+ /**98+ Strip the final [newline character](https://en.wikipedia.org/wiki/Newline) from the output.99 101- @default true102- */103- readonly stripFinalNewline?: boolean;100+ @default true101+ */102+ readonly stripFinalNewline?: boolean;103 105- /**106- Set to `false` if you don't want to extend the environment variables when providing the `env` property.104+ /**105+ Set to `false` if you don't want to extend the environment variables when providing the `env` property.106 108- @default true109- */110- readonly extendEnv?: boolean;107+ @default true108+ */109+ readonly extendEnv?: boolean;110 112- /**113- Current working directory of the child process.111+ /**112+ Current working directory of the child process.113 115- @default process.cwd()116- */117- readonly cwd?: string;114+ @default process.cwd()115+ */116+ readonly cwd?: string;117 119- /**120- Environment key-value pairs. Extends automatically from `process.env`. Set `extendEnv` to `false` if you don't want this.118+ /**119+ Environment key-value pairs. Extends automatically from `process.env`. Set `extendEnv` to `false` if you don't want this.120 122- @default process.env123- */124- readonly env?: NodeJS.ProcessEnv;121+ @default process.env122+ */123+ readonly env?: NodeJS.ProcessEnv;124 126- /**127- Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified.128- */129- readonly argv0?: string;125+ /**126+ Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified.127+ */128+ readonly argv0?: string;129 131- /**132- Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.130+ /**131+ Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_stdio) configuration.132 134- @default 'pipe'135- */136- readonly stdio?: 'pipe' | 'ignore' | 'inherit' | readonly StdioOption[];133+ @default 'pipe'134+ */135+ readonly stdio?: 'pipe' | 'ignore' | 'inherit' | readonly StdioOption[];136 138- /**139- Specify the kind of serialization used for sending messages between processes when using the `stdio: 'ipc'` option or `execa.node()`:140- - `json`: Uses `JSON.stringify()` and `JSON.parse()`.141- - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)137+ /**138+ Specify the kind of serialization used for sending messages between processes when using the `stdio: 'ipc'` option or `execaNode()`:139+ - `json`: Uses `JSON.stringify()` and `JSON.parse()`.140+ - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)141 143- Requires Node.js `13.2.0` or later.142+ Requires Node.js `13.2.0` or later.143 145- [More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)144+ [More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)145 147- @default 'json'148- */149- readonly serialization?: 'json' | 'advanced';146+ @default 'json'147+ */148+ readonly serialization?: 'json' | 'advanced';149 151- /**152- Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).150+ /**151+ Prepare child to run independently of its parent process. Specific behavior [depends on the platform](https://nodejs.org/api/child_process.html#child_process_options_detached).152 154- @default false155- */156- readonly detached?: boolean;153+ @default false154+ */155+ readonly detached?: boolean;156 158- /**159- Sets the user identity of the process.160- */161- readonly uid?: number;157+ /**158+ Sets the user identity of the process.159+ */160+ readonly uid?: number;161 163- /**164- Sets the group identity of the process.165- */166- readonly gid?: number;162+ /**163+ Sets the group identity of the process.164+ */165+ readonly gid?: number;166 168- /**169- If `true`, runs `command` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.167+ /**168+ If `true`, runs `command` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.169 171- We recommend against using this option since it is:172- - not cross-platform, encouraging shell-specific syntax.173- - slower, because of the additional shell interpretation.174- - unsafe, potentially allowing command injection.170+ We recommend against using this option since it is:171+ - not cross-platform, encouraging shell-specific syntax.172+ - slower, because of the additional shell interpretation.173+ - unsafe, potentially allowing command injection.174 176- @default false177- */178- readonly shell?: boolean | string;175+ @default false176+ */177+ readonly shell?: boolean | string;178 180- /**181- Specify the character encoding used to decode the `stdout` and `stderr` output. If set to `null`, then `stdout` and `stderr` will be a `Buffer` instead of a string.179+ /**180+ Specify the character encoding used to decode the `stdout` and `stderr` output. If set to `null`, then `stdout` and `stderr` will be a `Buffer` instead of a string.181 183- @default 'utf8'184- */185- readonly encoding?: EncodingType;182+ @default 'utf8'183+ */184+ readonly encoding?: EncodingType;185 187- /**188- If `timeout` is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than `timeout` milliseconds.186+ /**187+ If `timeout` is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than `timeout` milliseconds.188 190- @default 0191- */192- readonly timeout?: number;189+ @default 0190+ */191+ readonly timeout?: number;192 194- /**195- Largest amount of data in bytes allowed on `stdout` or `stderr`. Default: 100 MB.193+ /**194+ Largest amount of data in bytes allowed on `stdout` or `stderr`. Default: 100 MB.195 197- @default 100_000_000198- */199- readonly maxBuffer?: number;196+ @default 100_000_000197+ */198+ readonly maxBuffer?: number;199 201- /**202- Signal value to be used when the spawned process will be killed.200+ /**201+ Signal value to be used when the spawned process will be killed.202 204- @default 'SIGTERM'205- */206- readonly killSignal?: string | number;203+ @default 'SIGTERM'204+ */205+ readonly killSignal?: string | number;206 208- /**209- If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.207+ /**208+ If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.209 211- @default false212- */213- readonly windowsVerbatimArguments?: boolean;210+ @default false211+ */212+ readonly windowsVerbatimArguments?: boolean;213 215- /**216- On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows.214+ /**215+ On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows.216 218- @default true219- */220- readonly windowsHide?: boolean;221- }217+ @default true218+ */219+ readonly windowsHide?: boolean;220+}221 223- interface Options<EncodingType = string> extends CommonOptions<EncodingType> {224- /**225- Write some input to the `stdin` of your binary.226- */227- readonly input?: string | Buffer | ReadableStream;228- }222+export interface Options<EncodingType = string> extends CommonOptions<EncodingType> {223+ /**224+ Write some input to the `stdin` of your binary.225+ */226+ readonly input?: string | Buffer | ReadableStream;227+}228 230- interface SyncOptions<EncodingType = string> extends CommonOptions<EncodingType> {231- /**232- Write some input to the `stdin` of your binary.233- */234- readonly input?: string | Buffer;235- }229+export interface SyncOptions<EncodingType = string> extends CommonOptions<EncodingType> {230+ /**231+ Write some input to the `stdin` of your binary.232+ */233+ readonly input?: string | Buffer;234+}235 237- interface NodeOptions<EncodingType = string> extends Options<EncodingType> {238- /**239- The Node.js executable to use.236+export interface NodeOptions<EncodingType = string> extends Options<EncodingType> {237+ /**238+ The Node.js executable to use.239 241- @default process.execPath242- */243- readonly nodePath?: string;240+ @default process.execPath241+ */242+ readonly nodePath?: string;243 245- /**246- List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.244+ /**245+ List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the Node.js executable.246 248- @default process.execArgv249- */250- readonly nodeOptions?: string[];251- }247+ @default process.execArgv248+ */249+ readonly nodeOptions?: string[];250+}251 253- interface ExecaReturnBase<StdoutStderrType> {254- /**255- The file and arguments that were run, for logging purposes.252+export interface ExecaReturnBase<StdoutStderrType> {253+ /**254+ The file and arguments that were run, for logging purposes.255 257- This is not escaped and should not be executed directly as a process, including using `execa()` or `execa.command()`.258- */259- command: string;256+ This is not escaped and should not be executed directly as a process, including using `execa()` or `execaCommand()`.257+ */258+ command: string;259 261- /**262- Same as `command` but escaped.260+ /**261+ Same as `command` but escaped.262 264- This is meant to be copy and pasted into a shell, for debugging purposes.265- Since the escaping is fairly basic, this should not be executed directly as a process, including using `execa()` or `execa.command()`.266- */267- escapedCommand: string;263+ This is meant to be copy and pasted into a shell, for debugging purposes.264+ Since the escaping is fairly basic, this should not be executed directly as a process, including using `execa()` or `execaCommand()`.265+ */266+ escapedCommand: string;267 269- /**270- The numeric exit code of the process that was run.271- */272- exitCode: number;268+ /**269+ The numeric exit code of the process that was run.270+ */271+ exitCode: number;272 274- /**275- The output of the process on stdout.276- */277- stdout: StdoutStderrType;273+ /**274+ The output of the process on stdout.275+ */276+ stdout: StdoutStderrType;277 279- /**280- The output of the process on stderr.281- */282- stderr: StdoutStderrType;278+ /**279+ The output of the process on stderr.280+ */281+ stderr: StdoutStderrType;282 284- /**285- Whether the process failed to run.286- */287- failed: boolean;283+ /**284+ Whether the process failed to run.285+ */286+ failed: boolean;287 289- /**290- Whether the process timed out.291- */292- timedOut: boolean;288+ /**289+ Whether the process timed out.290+ */291+ timedOut: boolean;292 294- /**295- Whether the process was killed.296- */297- killed: boolean;293+ /**294+ Whether the process was killed.295+ */296+ killed: boolean;297 299- /**300- The name of the signal that was used to terminate the process. For example, `SIGFPE`.298+ /**299+ The name of the signal that was used to terminate the process. For example, `SIGFPE`.300 302- If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.303- */304- signal?: string;301+ If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`.302+ */303+ signal?: string;304 306- /**307- A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.305+ /**306+ A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.307 309- If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.310- */311- signalDescription?: string;312- }308+ If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.309+ */310+ signalDescription?: string;311+}312 314- interface ExecaSyncReturnValue<StdoutErrorType = string>315- extends ExecaReturnBase<StdoutErrorType> {316- }313+export interface ExecaSyncReturnValue<StdoutErrorType = string>314+ extends ExecaReturnBase<StdoutErrorType> {315+}316 317+/**318+Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.319+320+The child process fails when:321+- its exit code is not `0`322+- it was killed with a signal323+- timing out324+- being canceled325+- there's not enough memory or there are already too many child processes326+*/327+export interface ExecaReturnValue<StdoutErrorType = string>328+ extends ExecaSyncReturnValue<StdoutErrorType> {329 /**319- Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.330+ The output of the process with `stdout` and `stderr` interleaved.331 321- The child process fails when:322- - its exit code is not `0`323- - it was killed with a signal324- - timing out325- - being canceled326- - there's not enough memory or there are already too many child processes332+ This is `undefined` if either:333+ - the `all` option is `false` (default value)334+ - `execaSync()` was used335 */328- interface ExecaReturnValue<StdoutErrorType = string>329- extends ExecaSyncReturnValue<StdoutErrorType> {330- /**331- The output of the process with `stdout` and `stderr` interleaved.336+ all?: StdoutErrorType;337 333- This is `undefined` if either:334- - the `all` option is `false` (default value)335- - `execa.sync()` was used336- */337- all?: StdoutErrorType;338+ /**339+ Whether the process was canceled.340+ */341+ isCanceled: boolean;342+}343 339- /**340- Whether the process was canceled.341- */342- isCanceled: boolean;343- }344+export interface ExecaSyncError<StdoutErrorType = string>345+ extends Error,346+ ExecaReturnBase<StdoutErrorType> {347+ /**348+ Error message when the child process failed to run. In addition to the underlying error message, it also contains some information related to why the child process errored.349 345- interface ExecaSyncError<StdoutErrorType = string>346- extends Error,347- ExecaReturnBase<StdoutErrorType> {348- /**349- Error message when the child process failed to run. In addition to the underlying error message, it also contains some information related to why the child process errored.350+ The child process stderr then stdout are appended to the end, separated with newlines and not interleaved.351+ */352+ message: string;353 354+ /**351- The child process stderr then stdout are appended to the end, separated with newlines and not interleaved.352- */353- message: string;355+ This is the same as the `message` property except it does not include the child process stdout/stderr.356+ */357+ shortMessage: string;358 355- /**356- This is the same as the `message` property except it does not include the child process stdout/stderr.357- */358- shortMessage: string;359+ /**360+ Original error message. This is the same as the `message` property except it includes neither the child process stdout/stderr nor some additional information added by Execa.361 360- /**361- Original error message. This is the same as the `message` property except it includes neither the child process stdout/stderr nor some additional information added by Execa.362+ This is `undefined` unless the child process exited due to an `error` event or a timeout.363+ */364+ originalMessage?: string;365+}366 363- This is `undefined` unless the child process exited due to an `error` event or a timeout.364- */365- originalMessage?: string;366- }367+export interface ExecaError<StdoutErrorType = string>368+ extends ExecaSyncError<StdoutErrorType> {369+ /**370+ The output of the process with `stdout` and `stderr` interleaved.371 368- interface ExecaError<StdoutErrorType = string>369- extends ExecaSyncError<StdoutErrorType> {370- /**371- The output of the process with `stdout` and `stderr` interleaved.372+ This is `undefined` if either:373+ - the `all` option is `false` (default value)374+ - `execaSync()` was used375+ */376+ all?: StdoutErrorType;377 373- This is `undefined` if either:374- - the `all` option is `false` (default value)375- - `execa.sync()` was used376- */377- all?: StdoutErrorType;378+ /**379+ Whether the process was canceled.380+ */381+ isCanceled: boolean;382+}383 379- /**380- Whether the process was canceled.381- */382- isCanceled: boolean;383- }384+export interface KillOptions {385+ /**386+ Milliseconds to wait for the child process to terminate before sending `SIGKILL`.387 385- interface KillOptions {386- /**387- Milliseconds to wait for the child process to terminate before sending `SIGKILL`.388+ Can be disabled with `false`.389 389- Can be disabled with `false`.390+ @default 5000391+ */392+ forceKillAfterTimeout?: number | false;393+}394 391- @default 5000392- */393- forceKillAfterTimeout?: number | false;394- }395+export interface ExecaChildPromise<StdoutErrorType> {396+ /**397+ Stream combining/interleaving [`stdout`](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [`stderr`](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr).398 396- interface ExecaChildPromise<StdoutErrorType> {397- /**398- Stream combining/interleaving [`stdout`](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [`stderr`](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr).399+ This is `undefined` if either:400+ - the `all` option is `false` (the default value)401+ - both `stdout` and `stderr` options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)402+ */403+ all?: ReadableStream;404 400- This is `undefined` if either:401- - the `all` option is `false` (the default value)402- - both `stdout` and `stderr` options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)403- */404- all?: ReadableStream;405+ catch<ResultType = never>(406+ onRejected?: (reason: ExecaError<StdoutErrorType>) => ResultType | PromiseLike<ResultType>407+ ): Promise<ExecaReturnValue<StdoutErrorType> | ResultType>;408 406- catch<ResultType = never>(407- onRejected?: (reason: ExecaError<StdoutErrorType>) => ResultType | PromiseLike<ResultType>408- ): Promise<ExecaReturnValue<StdoutErrorType> | ResultType>;409+ /**410+ Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal), except if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.411+ */412+ kill(signal?: string, options?: KillOptions): void;413 410- /**411- Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal), except if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.412- */413- kill(signal?: string, options?: KillOptions): void;414-415- /**416- Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This is preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`.417- */418- cancel(): void;419- }420-421- type ExecaChildProcess<StdoutErrorType = string> = ChildProcess &422- ExecaChildPromise<StdoutErrorType> &423- Promise<ExecaReturnValue<StdoutErrorType>>;414+ /**415+ Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This is preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`.416+ */417+ cancel(): void;418 }419 426-declare const execa: {427- /**428- Execute a file.420+export type ExecaChildProcess<StdoutErrorType = string> = ChildProcess &421+ExecaChildPromise<StdoutErrorType> &422+Promise<ExecaReturnValue<StdoutErrorType>>;423 430- Think of this as a mix of `child_process.execFile` and `child_process.spawn`.424+/**425+Execute a file.426 432- @param file - The program/script to execute.433- @param arguments - Arguments to pass to `file` on execution.434- @returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.427+Think of this as a mix of `child_process.execFile` and `child_process.spawn`.428 436- @example437- ```438- import execa = require('execa');429+@param file - The program/script to execute.430+@param arguments - Arguments to pass to `file` on execution.431+@returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.432 440- (async () => {441- const {stdout} = await execa('echo', ['unicorns']);442- console.log(stdout);443- //=> 'unicorns'433+@example434+```435+import {execa} from 'execa';436 445- // Cancelling a spawned process437+const {stdout} = await execa('echo', ['unicorns']);438+console.log(stdout);439+//=> 'unicorns'440 447- const subprocess = execa('node');441+// Cancelling a spawned process442 449- setTimeout(() => {450- subprocess.cancel()451- }, 1000);443+const subprocess = execa('node');444 453- try {454- await subprocess;455- } catch (error) {456- console.log(subprocess.killed); // true457- console.log(error.isCanceled); // true458- }459- })();445+setTimeout(() => {446+ subprocess.cancel()447+}, 1000);448 461- // Pipe the child process stdout to the current stdout462- execa('echo', ['unicorns']).stdout.pipe(process.stdout);463- ```464- */465- (466- file: string,467- arguments?: readonly string[],468- options?: execa.Options469- ): execa.ExecaChildProcess;470- (471- file: string,472- arguments?: readonly string[],473- options?: execa.Options<null>474- ): execa.ExecaChildProcess<Buffer>;475- (file: string, options?: execa.Options): execa.ExecaChildProcess;476- (file: string, options?: execa.Options<null>): execa.ExecaChildProcess<477- Buffer478- >;449+try {450+ await subprocess;451+} catch (error) {452+ console.log(subprocess.killed); // true453+ console.log(error.isCanceled); // true454+}455 480- /**481- Execute a file synchronously.456+// Pipe the child process stdout to the current stdout457+execa('echo', ['unicorns']).stdout.pipe(process.stdout);458+```459+*/460+export function execa(461+ file: string,462+ arguments?: readonly string[],463+ options?: Options464+): ExecaChildProcess;465+export function execa(466+ file: string,467+ arguments?: readonly string[],468+ options?: Options<null>469+): ExecaChildProcess<Buffer>;470+export function execa(file: string, options?: Options): ExecaChildProcess;471+export function execa(file: string, options?: Options<null>): ExecaChildProcess<Buffer>;472 483- This method throws an `Error` if the command fails.473+/**474+Execute a file synchronously.475 485- @param file - The program/script to execute.486- @param arguments - Arguments to pass to `file` on execution.487- @returns A result `Object` with `stdout` and `stderr` properties.488- */489- sync(490- file: string,491- arguments?: readonly string[],492- options?: execa.SyncOptions493- ): execa.ExecaSyncReturnValue;494- sync(495- file: string,496- arguments?: readonly string[],497- options?: execa.SyncOptions<null>498- ): execa.ExecaSyncReturnValue<Buffer>;499- sync(file: string, options?: execa.SyncOptions): execa.ExecaSyncReturnValue;500- sync(501- file: string,502- options?: execa.SyncOptions<null>503- ): execa.ExecaSyncReturnValue<Buffer>;476+This method throws an `Error` if the command fails.477 505- /**506- Same as `execa()` except both file and arguments are specified in a single `command` string. For example, `execa('echo', ['unicorns'])` is the same as `execa.command('echo unicorns')`.478+@param file - The program/script to execute.479+@param arguments - Arguments to pass to `file` on execution.480+@returns A result `Object` with `stdout` and `stderr` properties.481+*/482+export function execaSync(483+ file: string,484+ arguments?: readonly string[],485+ options?: SyncOptions486+): ExecaSyncReturnValue;487+export function execaSync(488+ file: string,489+ arguments?: readonly string[],490+ options?: SyncOptions<null>491+): ExecaSyncReturnValue<Buffer>;492+export function execaSync(file: string, options?: SyncOptions): ExecaSyncReturnValue;493+export function execaSync(494+ file: string,495+ options?: SyncOptions<null>496+): ExecaSyncReturnValue<Buffer>;497 508- If the file or an argument contains spaces, they must be escaped with backslashes. This matters especially if `command` is not a constant but a variable, for example with `__dirname` or `process.cwd()`. Except for spaces, no escaping/quoting is needed.498+/**499+Same as `execa()` except both file and arguments are specified in a single `command` string. For example, `execa('echo', ['unicorns'])` is the same as `execaCommand('echo unicorns')`.500 510- The `shell` option must be used if the `command` uses shell-specific features (for example, `&&` or `||`), as opposed to being a simple `file` followed by its `arguments`.501+If the file or an argument contains spaces, they must be escaped with backslashes. This matters especially if `command` is not a constant but a variable, for example with `__dirname` or `process.cwd()`. Except for spaces, no escaping/quoting is needed.502 512- @param command - The program/script to execute and its arguments.513- @returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.503+The `shell` option must be used if the `command` uses shell-specific features (for example, `&&` or `||`), as opposed to being a simple `file` followed by its `arguments`.504 515- @example516- ```517- import execa = require('execa');505+@param command - The program/script to execute and its arguments.506+@returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.507 519- (async () => {520- const {stdout} = await execa.command('echo unicorns');521- console.log(stdout);522- //=> 'unicorns'523- })();524- ```525- */526- command(command: string, options?: execa.Options): execa.ExecaChildProcess;527- command(command: string, options?: execa.Options<null>): execa.ExecaChildProcess<Buffer>;508+@example509+```510+import {execaCommand} from 'execa';511 529- /**530- Same as `execa.command()` but synchronous.512+const {stdout} = await execaCommand('echo unicorns');513+console.log(stdout);514+//=> 'unicorns'515+```516+*/517+export function execaCommand(command: string, options?: Options): ExecaChildProcess;518+export function execaCommand(command: string, options?: Options<null>): ExecaChildProcess<Buffer>;519 532- @param command - The program/script to execute and its arguments.533- @returns A result `Object` with `stdout` and `stderr` properties.534- */535- commandSync(command: string, options?: execa.SyncOptions): execa.ExecaSyncReturnValue;536- commandSync(command: string, options?: execa.SyncOptions<null>): execa.ExecaSyncReturnValue<Buffer>;520+/**521+Same as `execaCommand()` but synchronous.522 538- /**539- Execute a Node.js script as a child process.523+@param command - The program/script to execute and its arguments.524+@returns A result `Object` with `stdout` and `stderr` properties.525+*/526+export function execaCommandSync(command: string, options?: SyncOptions): ExecaSyncReturnValue;527+export function execaCommandSync(command: string, options?: SyncOptions<null>): ExecaSyncReturnValue<Buffer>;528 541- Same as `execa('node', [scriptPath, ...arguments], options)` except (like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)):542- - the current Node version and options are used. This can be overridden using the `nodePath` and `nodeArguments` options.543- - the `shell` option cannot be used544- - an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)529+/**530+Execute a Node.js script as a child process.531 546- @param scriptPath - Node.js script to execute.547- @param arguments - Arguments to pass to `scriptPath` on execution.548- @returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.549- */550- node(551- scriptPath: string,552- arguments?: readonly string[],553- options?: execa.NodeOptions554- ): execa.ExecaChildProcess;555- node(556- scriptPath: string,557- arguments?: readonly string[],558- options?: execa.Options<null>559- ): execa.ExecaChildProcess<Buffer>;560- node(scriptPath: string, options?: execa.Options): execa.ExecaChildProcess;561- node(scriptPath: string, options?: execa.Options<null>): execa.ExecaChildProcess<Buffer>;562-};532+Same as `execa('node', [scriptPath, ...arguments], options)` except (like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)):533+ - the current Node version and options are used. This can be overridden using the `nodePath` and `nodeArguments` options.534+ - the `shell` option cannot be used535+ - an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)536 564-export = execa;537+@param scriptPath - Node.js script to execute.538+@param arguments - Arguments to pass to `scriptPath` on execution.539+@returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.540+*/541+export function execaNode(542+ scriptPath: string,543+ arguments?: readonly string[],544+ options?: NodeOptions545+): ExecaChildProcess;546+export function execaNode(547+ scriptPath: string,548+ arguments?: readonly string[],549+ options?: Options<null>550+): ExecaChildProcess<Buffer>;551+export function execaNode(scriptPath: string, options?: Options): ExecaChildProcess;552+export function execaNode(scriptPath: string, options?: Options<null>): ExecaChildProcess<Buffer>;modified:index.js+34 added-35 removed
1-'use strict';2-const path = require('path');3-const childProcess = require('child_process');4-const crossSpawn = require('cross-spawn');5-const stripFinalNewline = require('strip-final-newline');6-const npmRunPath = require('npm-run-path');7-const onetime = require('onetime');8-const makeError = require('./lib/error');9-const normalizeStdio = require('./lib/stdio');10-const {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} = require('./lib/kill');11-const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = require('./lib/stream');12-const {mergePromise, getSpawnedPromise} = require('./lib/promise');13-const {joinCommand, parseCommand, getEscapedCommand} = require('./lib/command');1+import {Buffer} from 'node:buffer';2+import path from 'node:path';3+import childProcess from 'node:child_process';4+import process from 'node:process';5+import crossSpawn from 'cross-spawn';6+import stripFinalNewline from 'strip-final-newline';7+import {npmRunPathEnv} from 'npm-run-path';8+import onetime from 'onetime';9+import {makeError} from './lib/error.js';10+import {normalizeStdio, normalizeStdioNode} from './lib/stdio.js';11+import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';12+import {handleInput, getSpawnedResult, makeAllStream, validateInputSync} from './lib/stream.js';13+import {mergePromise, getSpawnedPromise} from './lib/promise.js';14+import {joinCommand, parseCommand, getEscapedCommand} from './lib/command.js';15 16 const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;17 18 const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {19 const env = extendEnv ? {...process.env, ...envOption} : envOption;20 21 if (preferLocal) {21- return npmRunPath.env({env, cwd: localDir, execPath});22+ return npmRunPathEnv({env, cwd: localDir, execPath});23 }24 25 return env;26 };16 unmodified lines43 reject: true,44 cleanup: true,45 all: false,46 windowsHide: true,46- ...options47+ ...options,48 };49 50 options.env = getEnv(options);51 8 unmodified lines60 };61 62 const handleOutput = (options, value, error) => {63 if (typeof value !== 'string' && !Buffer.isBuffer(value)) {63- // When `execa.sync()` errors, we normalize it to '' to mimic `execa()`64+ // When `execaSync()` errors, we normalize it to '' to mimic `execa()`65 return error === undefined ? undefined : '';66 }67 68 if (options.stripFinalNewline) {2 unmodified lines71 72 return value;73 };74 74-const execa = (file, args, options) => {75+export const execa = (file, args, options) => {76 const parsed = handleArguments(file, args, options);77 const command = joinCommand(file, args);78 const escapedCommand = getEscapedCommand(file, args);79 14 unmodified lines94 escapedCommand,95 parsed,96 timedOut: false,97 isCanceled: false,97- killed: false98+ killed: false,99 }));100 return mergePromise(dummySpawned, errorPromise);101 }102 24 unmodified lines127 escapedCommand,128 parsed,129 timedOut,130 isCanceled: context.isCanceled,130- killed: spawned.killed131+ killed: spawned.killed,132 });133 134 if (!parsed.options.reject) {135 return returnedError;11 unmodified lines147 all,148 failed: false,149 timedOut: false,150 isCanceled: false,150- killed: false151+ killed: false,152 };153 };154 155 const handlePromiseOnce = onetime(handlePromise);4 unmodified lines160 161 return mergePromise(spawned, handlePromiseOnce);162 };163 163-module.exports = execa;164-165-module.exports.sync = (file, args, options) => {164+export const execaSync = (file, args, options) => {165 const parsed = handleArguments(file, args, options);166 const command = joinCommand(file, args);167 const escapedCommand = getEscapedCommand(file, args);168 12 unmodified lines181 escapedCommand,182 parsed,183 timedOut: false,184 isCanceled: false,186- killed: false185+ killed: false,186 });187 }188 189 const stdout = handleOutput(parsed.options, result.stdout, result.error);10 unmodified lines200 escapedCommand,201 parsed,202 timedOut: result.error && result.error.code === 'ETIMEDOUT',203 isCanceled: false,205- killed: result.signal !== null204+ killed: result.signal !== null,205 });206 207 if (!parsed.options.reject) {208 return error;10 unmodified lines219 stderr,220 failed: false,221 timedOut: false,222 isCanceled: false,224- killed: false223+ killed: false,224 };225 };226 228-module.exports.command = (command, options) => {227+export const execaCommand = (command, options) => {228 const [file, ...args] = parseCommand(command);229 return execa(file, args, options);230 };231 233-module.exports.commandSync = (command, options) => {232+export const execaCommandSync = (command, options) => {233 const [file, ...args] = parseCommand(command);235- return execa.sync(file, args, options);234+ return execaSync(file, args, options);235 };236 238-module.exports.node = (scriptPath, args, options = {}) => {237+export const execaNode = (scriptPath, args, options = {}) => {238 if (args && !Array.isArray(args) && typeof args === 'object') {239 options = args;240 args = [];241 }242 244- const stdio = normalizeStdio.node(options);243+ const stdio = normalizeStdioNode(options);244 const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect'));245 246 const {247 nodePath = process.execPath,249- nodeOptions = defaultExecArgv248+ nodeOptions = defaultExecArgv,249 } = options;250 251 return execa(252 nodePath,253 [254 ...nodeOptions,255 scriptPath,257- ...(Array.isArray(args) ? args : [])256+ ...(Array.isArray(args) ? args : []),257 ],258 {259 ...options,260 stdin: undefined,261 stdout: undefined,262 stderr: undefined,263 stdio,265- shell: false266- }264+ shell: false,265+ },266 );267 };modified:index.test-d.ts+51 added-39 removed
1+import {Buffer} from 'node:buffer';2+// For some reason a default import of `process` causes3+// `process.stdin`, `process.stderr`, and `process.stdout`4+// to get treated as `any` by `@typescript-eslint/no-unsafe-assignment`.5+import * as process from 'node:process';6+import {Readable as ReadableStream} from 'node:stream';7 import {expectType, expectError} from 'tsd';2-import {Readable as ReadableStream} from 'stream';3-import execa = require('.');8 import {9+ execa,10+ execaSync,11+ execaCommand,12+ execaCommandSync,13+ execaNode,14 ExecaReturnValue,15 ExecaChildProcess,16 ExecaError,17 ExecaSyncReturnValue,9- ExecaSyncError10-} from '.';18+ ExecaSyncError,19+} from './index.js';20 21 try {22 const execaPromise = execa('unicorns');23 execaPromise.cancel();30 unmodified lines54 expectType<string | undefined>(execaError.originalMessage);55 }56 57 try {49- const unicornsResult = execa.sync('unicorns');58+ const unicornsResult = execaSync('unicorns');59 expectType<string>(unicornsResult.command);60 expectType<string>(unicornsResult.escapedCommand);61 expectType<number>(unicornsResult.exitCode);62 expectType<string>(unicornsResult.stdout);22 unmodified lines85 expectType<string>(execaError.shortMessage);86 expectType<string | undefined>(execaError.originalMessage);87 }88 89+/* eslint-disable @typescript-eslint/no-floating-promises */90 execa('unicorns', {cleanup: false});91 execa('unicorns', {preferLocal: false});92 execa('unicorns', {localDir: '.'});93 execa('unicorns', {execPath: '/path'});26 unmodified lines120 execa('unicorns', {reject: false});121 execa('unicorns', {stripFinalNewline: false});122 execa('unicorns', {extendEnv: false});123 execa('unicorns', {cwd: '.'});124+// eslint-disable-next-line @typescript-eslint/naming-convention125 execa('unicorns', {env: {PATH: ''}});126 execa('unicorns', {argv0: ''});127 execa('unicorns', {stdio: 'pipe'});128 execa('unicorns', {stdio: 'ignore'});129 execa('unicorns', {stdio: 'inherit'});130 execa('unicorns', {120- stdio: ['pipe', 'ipc', 'ignore', 'inherit', process.stdin, 1, undefined]131+ stdio: ['pipe', 'ipc', 'ignore', 'inherit', process.stdin, 1, undefined],132 });133 execa('unicorns', {serialization: 'advanced'});134 execa('unicorns', {detached: true});135 execa('unicorns', {uid: 0});5 unmodified lines141 execa('unicorns', {killSignal: 'SIGTERM'});142 execa('unicorns', {killSignal: 9});143 execa('unicorns', {windowsVerbatimArguments: true});144 execa('unicorns', {windowsHide: false});145+/* eslint-enable @typescript-eslint/no-floating-promises */146 execa('unicorns').kill();147 execa('unicorns').kill('SIGKILL');148 execa('unicorns').kill(undefined);149 execa('unicorns').kill('SIGKILL', {});150 execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: false});151 execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: 42});152 execa('unicorns').kill('SIGKILL', {forceKillAfterTimeout: undefined});153 142-expectType<ExecaChildProcess<string>>(execa('unicorns'));143-expectType<ExecaReturnValue<string>>(await execa('unicorns'));144-expectType<ExecaReturnValue<string>>(145- await execa('unicorns', {encoding: 'utf8'})154+expectType<ExecaChildProcess>(execa('unicorns'));155+expectType<ExecaReturnValue>(await execa('unicorns'));156+expectType<ExecaReturnValue>(157+ await execa('unicorns', {encoding: 'utf8'}),158 );159 expectType<ExecaReturnValue<Buffer>>(await execa('unicorns', {encoding: null}));148-expectType<ExecaReturnValue<string>>(149- await execa('unicorns', ['foo'], {encoding: 'utf8'})160+expectType<ExecaReturnValue>(161+ await execa('unicorns', ['foo'], {encoding: 'utf8'}),162 );163 expectType<ExecaReturnValue<Buffer>>(152- await execa('unicorns', ['foo'], {encoding: null})164+ await execa('unicorns', ['foo'], {encoding: null}),165 );166 155-expectType<ExecaSyncReturnValue<string>>(execa.sync('unicorns'));156-expectType<ExecaSyncReturnValue<string>>(157- execa.sync('unicorns', {encoding: 'utf8'})167+expectType<ExecaSyncReturnValue>(execaSync('unicorns'));168+expectType<ExecaSyncReturnValue>(169+ execaSync('unicorns', {encoding: 'utf8'}),170 );171 expectType<ExecaSyncReturnValue<Buffer>>(160- execa.sync('unicorns', {encoding: null})172+ execaSync('unicorns', {encoding: null}),173 );162-expectType<ExecaSyncReturnValue<string>>(163- execa.sync('unicorns', ['foo'], {encoding: 'utf8'})174+expectType<ExecaSyncReturnValue>(175+ execaSync('unicorns', ['foo'], {encoding: 'utf8'}),176 );177 expectType<ExecaSyncReturnValue<Buffer>>(166- execa.sync('unicorns', ['foo'], {encoding: null})178+ execaSync('unicorns', ['foo'], {encoding: null}),179 );180 169-expectType<ExecaChildProcess<string>>(execa.command('unicorns'));170-expectType<ExecaReturnValue<string>>(await execa.command('unicorns'));171-expectType<ExecaReturnValue<string>>(await execa.command('unicorns', {encoding: 'utf8'}));172-expectType<ExecaReturnValue<Buffer>>(await execa.command('unicorns', {encoding: null}));173-expectType<ExecaReturnValue<string>>(await execa.command('unicorns foo', {encoding: 'utf8'}));174-expectType<ExecaReturnValue<Buffer>>(await execa.command('unicorns foo', {encoding: null}));181+expectType<ExecaChildProcess>(execaCommand('unicorns'));182+expectType<ExecaReturnValue>(await execaCommand('unicorns'));183+expectType<ExecaReturnValue>(await execaCommand('unicorns', {encoding: 'utf8'}));184+expectType<ExecaReturnValue<Buffer>>(await execaCommand('unicorns', {encoding: null}));185+expectType<ExecaReturnValue>(await execaCommand('unicorns foo', {encoding: 'utf8'}));186+expectType<ExecaReturnValue<Buffer>>(await execaCommand('unicorns foo', {encoding: null}));187 176-expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns'));177-expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns', {encoding: 'utf8'}));178-expectType<ExecaSyncReturnValue<Buffer>>(execa.commandSync('unicorns', {encoding: null}));179-expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns foo', {encoding: 'utf8'}));180-expectType<ExecaSyncReturnValue<Buffer>>(execa.commandSync('unicorns foo', {encoding: null}));188+expectType<ExecaSyncReturnValue>(execaCommandSync('unicorns'));189+expectType<ExecaSyncReturnValue>(execaCommandSync('unicorns', {encoding: 'utf8'}));190+expectType<ExecaSyncReturnValue<Buffer>>(execaCommandSync('unicorns', {encoding: null}));191+expectType<ExecaSyncReturnValue>(execaCommandSync('unicorns foo', {encoding: 'utf8'}));192+expectType<ExecaSyncReturnValue<Buffer>>(execaCommandSync('unicorns foo', {encoding: null}));193 182-expectType<ExecaChildProcess<string>>(execa.node('unicorns'));183-expectType<ExecaReturnValue<string>>(await execa.node('unicorns'));184-expectType<ExecaReturnValue<string>>(185- await execa.node('unicorns', {encoding: 'utf8'})194+expectType<ExecaChildProcess>(execaNode('unicorns'));195+expectType<ExecaReturnValue>(await execaNode('unicorns'));196+expectType<ExecaReturnValue>(197+ await execaNode('unicorns', {encoding: 'utf8'}),198 );187-expectType<ExecaReturnValue<Buffer>>(await execa.node('unicorns', {encoding: null}));188-expectType<ExecaReturnValue<string>>(189- await execa.node('unicorns', ['foo'], {encoding: 'utf8'})199+expectType<ExecaReturnValue<Buffer>>(await execaNode('unicorns', {encoding: null}));200+expectType<ExecaReturnValue>(201+ await execaNode('unicorns', ['foo'], {encoding: 'utf8'}),202 );203 expectType<ExecaReturnValue<Buffer>>(192- await execa.node('unicorns', ['foo'], {encoding: null})204+ await execaNode('unicorns', ['foo'], {encoding: null}),205 );modified:package.json+14 added-12 removed
9 unmodified lines10 "email": "sindresorhus@gmail.com",11 "url": "https://sindresorhus.com"12 },13 "engines": {14- "node": ">=10"14+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"15 },16+ "type": "module",17+ "exports": "./index.js",18 "scripts": {17- "test": "xo && nyc ava && tsd"19+ "test": "xo && c8 ava && tsd"20 },21 "files": [22 "index.js",23 "index.d.ts",18 unmodified lines42 ],43 "dependencies": {44 "cross-spawn": "^7.0.3",45 "get-stream": "^6.0.0",44- "human-signals": "^2.1.0",45- "is-stream": "^2.0.0",46+ "human-signals": "^3.0.1",47+ "is-stream": "^3.0.0",48 "merge-stream": "^2.0.0",47- "npm-run-path": "^4.0.1",48- "onetime": "^5.1.2",49+ "npm-run-path": "^5.0.1",50+ "onetime": "^6.0.0",51 "signal-exit": "^3.0.3",50- "strip-final-newline": "^2.0.0"52+ "strip-final-newline": "^3.0.0"53 },54 "devDependencies": {53- "@types/node": "^14.14.10",54- "ava": "^2.4.0",55+ "@types/node": "^16.11.7",56+ "ava": "^3.15.0",57+ "c8": "^7.10.0",58 "get-node": "^11.0.1",59 "is-running": "^2.1.0",57- "nyc": "^15.1.0",60 "p-event": "^4.2.0",61 "tempfile": "^3.0.0",62 "tsd": "^0.13.1",61- "xo": "^0.35.0"63+ "xo": "^0.46.4"64 },63- "nyc": {65+ "c8": {66 "reporter": [67 "text",68 "lcov"69 ],7 unmodified linesmodified:readme.md+64 added-73 removed
27 unmodified lines28 29 ## Usage30 31 ```js32-const execa = require('execa');32+import {execa} from 'execa';33 34-(async () => {35- const {stdout} = await execa('echo', ['unicorns']);36- console.log(stdout);37- //=> 'unicorns'34+const {stdout} = await execa('echo', ['unicorns']);35+console.log(stdout);36+//=> 'unicorns'38-})();37 ```38 39 ### Pipe the child process stdout to the parent40 41 ```js44-const execa = require('execa');42+import {execa} from 'execa';43 44 execa('echo', ['unicorns']).stdout.pipe(process.stdout);45 ```46 47 ### Handling Errors48 49 ```js52-const execa = require('execa');50+import {execa} from 'execa';51 54-(async () => {55- // Catching an error56- try {57- await execa('unknown', ['command']);58- } catch (error) {59- console.log(error);60- /*61- {62- message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',63- errno: -2,64- code: 'ENOENT',65- syscall: 'spawn unknown',66- path: 'unknown',67- spawnargs: ['command'],68- originalMessage: 'spawn unknown ENOENT',69- shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',70- command: 'unknown command',71- escapedCommand: 'unknown command',72- stdout: '',73- stderr: '',74- all: '',75- failed: true,76- timedOut: false,77- isCanceled: false,78- killed: false52+// Catching an error53+try {54+ await execa('unknown', ['command']);55+} catch (error) {56+ console.log(error);57+ /*58+ {59+ message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',60+ errno: -2,61+ code: 'ENOENT',62+ syscall: 'spawn unknown',63+ path: 'unknown',64+ spawnargs: ['command'],65+ originalMessage: 'spawn unknown ENOENT',66+ shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',67+ command: 'unknown command',68+ escapedCommand: 'unknown command',69+ stdout: '',70+ stderr: '',71+ all: '',72+ failed: true,73+ timedOut: false,74+ isCanceled: false,75+ killed: false79- }80- */76 }82-83-})();77+ */78+}79 ```80 81 ### Cancelling a spawned process82 83 ```js89-const execa = require('execa');84+import {execa} from 'execa';85 91-(async () => {92- const subprocess = execa('node');86+const subprocess = execa('node');87 94- setTimeout(() => {95- subprocess.cancel();96- }, 1000);88+setTimeout(() => {89+ subprocess.cancel();90+}, 1000);91 98- try {99- await subprocess;100- } catch (error) {101- console.log(subprocess.killed); // true102- console.log(error.isCanceled); // true103- }104-})()92+try {93+ await subprocess;94+} catch (error) {95+ console.log(subprocess.killed); // true96+ console.log(error.isCanceled); // true97+}98 ```99 100 ### Catching an error with the sync method101 102 ```js103+import {execaSync} from 'execa';104+105 try {111- execa.sync('unknown', ['command']);106+ execaSync('unknown', ['command']);107 } catch (error) {108 console.log(error);109 /*110 {73 unmodified lines184 This is `undefined` if either:185 - the [`all` option](#all-2) is `false` (the default value)186 - both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)187 193-### execa.sync(file, arguments?, options?)188+### execaSync(file, arguments?, options?)189 190 Execute a file synchronously.191 192 Returns or throws a [`childProcessResult`](#childProcessResult).193 199-### execa.command(command, options?)194+### execaCommand(command, options?)195 201-Same as [`execa()`](#execafile-arguments-options) except both file and arguments are specified in a single `command` string. For example, `execa('echo', ['unicorns'])` is the same as `execa.command('echo unicorns')`.196+Same as [`execa()`](#execafile-arguments-options) except both file and arguments are specified in a single `command` string. For example, `execa('echo', ['unicorns'])` is the same as `execaCommand('echo unicorns')`.197 198 If the file or an argument contains spaces, they must be escaped with backslashes. This matters especially if `command` is not a constant but a variable, for example with `__dirname` or `process.cwd()`. Except for spaces, no escaping/quoting is needed.199 200 The [`shell` option](#shell) must be used if the `command` uses shell-specific features (for example, `&&` or `||`), as opposed to being a simple `file` followed by its `arguments`.201 207-### execa.commandSync(command, options?)202+### execaCommandSync(command, options?)203 209-Same as [`execa.command()`](#execacommand-command-options) but synchronous.204+Same as [`execaCommand()`](#execacommand-command-options) but synchronous.205 206 Returns or throws a [`childProcessResult`](#childProcessResult).207 213-### execa.node(scriptPath, arguments?, options?)208+### execaNode(scriptPath, arguments?, options?)209 210 Execute a Node.js script as a child process.211 212 Same as `execa('node', [scriptPath, ...arguments], options)` except (like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)):19 unmodified lines232 Type: `string`233 234 The file and arguments that were run, for logging purposes.235 241-This is not escaped and should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execa.command()`](#execacommandcommand-options).236+This is not escaped and should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).237 238 #### escapedCommand239 240 Type: `string`241 242 Same as [`command`](#command) but escaped.243 244 This is meant to be copy and pasted into a shell, for debugging purposes.250-Since the escaping is fairly basic, this should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execa.command()`](#execacommandcommand-options).245+Since the escaping is fairly basic, this should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).246 247 #### exitCode248 249 Type: `number`19 unmodified lines269 The output of the process with `stdout` and `stderr` interleaved.270 271 This is `undefined` if either:272 - the [`all` option](#all-2) is `false` (the default value)278- - `execa.sync()` was used273+ - `execaSync()` was used274 275 #### failed276 277 Type: `boolean`197 unmodified lines475 476 Type: `string`\477 Default: `'json'`478 484-Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execa.node()`](#execanodescriptpath-arguments-options):479+Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execaNode()`](#execanodescriptpath-arguments-options):480 - `json`: Uses `JSON.stringify()` and `JSON.parse()`.481 - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)482 483 Requires Node.js `13.2.0` or later.92 unmodified lines576 577 Gracefully handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:578 579 ```js585-const pRetry = require('p-retry');580+import pRetry from 'p-retry';581 582 const run = async () => {583 const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']);584 return results;585 };586 592-(async () => {593- console.log(await pRetry(run, {retries: 5}));587+console.log(await pRetry(run, {retries: 5}));594-})();588 ```589 590 ### Save and pipe output from a child process591 592 Let's say you want to show the output of a child process in real-time while also saving it to a variable.593 594 ```js602-const execa = require('execa');595+import {execa} from 'execa';596 597 const subprocess = execa('echo', ['foo']);598 subprocess.stdout.pipe(process.stdout);599 607-(async () => {608- const {stdout} = await subprocess;609- console.log('child output:', stdout);600+const {stdout} = await subprocess;601+console.log('child output:', stdout);610-})();602 ```603 604 ### Redirect output to a file605 606 ```js616-const execa = require('execa');607+import {execa} from 'execa';608 609 const subprocess = execa('echo', ['foo'])610 subprocess.stdout.pipe(fs.createWriteStream('stdout.txt'))611 ```612 613 ### Redirect input from a file614 615 ```js625-const execa = require('execa');616+import {execa} from 'execa';617 618 const subprocess = execa('cat')619 fs.createReadStream('stdin.txt').pipe(subprocess.stdin)620 ```621 622 ### Execute the current package's binary623 624 ```js634-const {getBinPathSync} = require('get-bin-path');625+import {getBinPathSync} from 'get-bin-path';626 627 const binPath = getBinPathSync();628 const subprocess = execa(binPath);629 ```25 unmodified lines