Skip to content
Myr

Add `ExecaError` and `ExecaSyncError` classes (#911)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ehmicky · committed by GitHub · parent a29352f · Browse files · 28 files+634 added−511 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

28 files+634 added−511 removed

  • tests:+291 added−271 removed
  • other:+343 added−240 removed

28 files+634 added−511 removed

modified:docs/scripts.md+12 added-12 removed
515 unmodified lines
516 isCanceled,517 isTerminated,518 // and other error-related properties: code, etc.519} = await $({timeout: 1})`sleep 2`;520// file:///home/me/code/execa/lib/kill.js:60521// reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));522// ^523// Error: Command timed out after 1 milliseconds: sleep 2520// ExecaError: Command timed out after 1 milliseconds: sleep 2524// Timed out521// at file:///home/me/Desktop/example.js:2:20526// timedOut: true,527// signal: 'SIGTERM',528// originalMessage: 'Timed out',522// at ... {523// shortMessage: 'Command timed out after 1 milliseconds: sleep 2\nTimed out',524// originalMessage: '',525// command: 'sleep 2',526// escapedCommand: 'sleep 2',532// exitCode: undefined,527// cwd: '/path/to/cwd',528// durationMs: 19.95693,529// failed: true,530// timedOut: true,531// isCanceled: false,532// isTerminated: true,533// signal: 'SIGTERM',534// signalDescription: 'Termination',535// stdout: '',536// stderr: '',536// failed: true,537// isCanceled: false,538// isTerminated: false537// stdio: [undefined, '', ''],538// pipedFrom: []539// }540```541542### Exit codes
262 unmodified lines
modified:lib/exit/code.js+16 added-2 removed
modified:lib/exit/kill.js+1 added-1 removed
modified:lib/exit/timeout.js+1 added-1 removed
modified:lib/pipe/throw.js+1 added
added:lib/return/cause.js+37 added
deleted:lib/return/clone.js-70 removed
1export const getFinalError = (initialError, message) => {2 const error = createFinalError(initialError, message);3 previousErrors.add(error);4 return error;5};67const createFinalError = (error, message) => {8 if (!isErrorInstance(error)) {9 return new Error(message);10 }1112 return previousErrors.has(error)13 ? cloneError(error, message)14 : setErrorMessage(error, message);15};1617export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';1819const cloneError = (oldError, newMessage) => {20 const {name, message, stack} = oldError;21 const error = new Error(newMessage);22 error.stack = fixStack(stack, message, newMessage);23 Object.defineProperty(error, 'name', {value: name, enumerable: false, configurable: true, writable: true});24 copyErrorProperties(error, oldError);25 return error;26};2728const copyErrorProperties = (newError, previousError) => {29 for (const propertyName of COPIED_ERROR_PROPERTIES) {30 const descriptor = Object.getOwnPropertyDescriptor(previousError, propertyName);31 if (descriptor !== undefined) {32 Object.defineProperty(newError, propertyName, descriptor);33 }34 }35};3637// Known error properties38const COPIED_ERROR_PROPERTIES = [39 'cause',40 'errors',41 'code',42 'errno',43 'syscall',44 'path',45 'dest',46 'address',47 'port',48 'info',49];5051// Sets `error.message`.52// Fixes `error.stack` not being updated when it has been already accessed, since it is memoized by V8.53// For example, this happens when calling `stream.destroy(error)`.54// See https://github.com/nodejs/node/issues/5171555const setErrorMessage = (error, newMessage) => {56 const {message, stack} = error;57 error.message = newMessage;58 error.stack = fixStack(stack, message, newMessage);59 return error;60};6162const fixStack = (stack, message, newMessage) => stack.includes(newMessage)63 ? stack64 : stack.replace(`: ${message}`, `: ${newMessage}`);6566// Two `execa()` calls might return the same error.67// So we must close those before directly mutating them.68export const isPreviousError = error => previousErrors.has(error);6970const previousErrors = new WeakSet();
modified:lib/return/early-error.js+1 added-1 removed
10 unmodified lines
1112 const subprocess = new ChildProcess();13 createDummyStreams(subprocess, stdioStreamsGroups);1415 const earlyError = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime});15 const earlyError = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime, isSync: false});16 const promise = handleDummyPromise(earlyError, verboseInfo, options);17 return {subprocess, promise};18};19
17 unmodified lines
modified:lib/return/error.js+16 added-19 removed
2 unmodified lines
3import {isBinary, binaryToString} from '../utils.js';4import {fixCwdError} from '../arguments/cwd.js';5import {escapeLines} from '../arguments/escape.js';6import {getDurationMs} from './duration.js';7import {getFinalError, isPreviousError} from './clone.js';7import {getFinalError, DiscardedError, isExecaError} from './cause.js';89export const makeSuccessResult = ({10 command,11 escapedCommand,
24 unmodified lines
36 escapedCommand,37 stdioStreamsGroups,38 options,39 startTime,40 isSync,41}) => makeError({42 error,43 command,44 escapedCommand,
1 unmodified line
46 timedOut: false,47 isCanceled: false,48 stdio: Array.from({length: stdioStreamsGroups.length}),49 options,50 isSync,51});5253export const makeError = ({52 error: rawError,54 error: originalError,55 command,56 escapedCommand,57 startTime,58 timedOut,
2 unmodified lines
61 signal: rawSignal,62 stdio,63 all,64 options: {timeoutDuration, timeout = timeoutDuration, cwd},65 isSync,66}) => {64 const initialError = rawError instanceof DiscardedError ? undefined : rawError;67 const {exitCode, signal, signalDescription} = normalizeExitPayload(rawExitCode, rawSignal);68 const {originalMessage, shortMessage, message} = createMessages({69 stdio,70 all,69 error: initialError,71 originalError,72 signal,73 signalDescription,74 exitCode,75 escapedCommand,
1 unmodified line
77 isCanceled,78 timeout,79 cwd,80 });79 const error = getFinalError(initialError, message);81 const error = getFinalError(originalError, message, isSync);8283 error.shortMessage = shortMessage;84 error.originalMessage = originalMessage;85 error.command = command;
7 unmodified lines
93 error.isTerminated = signal !== undefined;94 error.exitCode = exitCode;95 error.signal = signal;96 error.signalDescription = signalDescription;97 error.code = error.cause?.code;9899 error.stdout = stdio[1];100 error.stderr = stdio[2];101
1 unmodified line
103 error.all = all;104 }105106 error.stdio = stdio;104105 if ('bufferedData' in error) {106 delete error.bufferedData;107 }108107 error.pipedFrom = [];108109 return error;110};111114// Indicates that the error is used only to interrupt control flow, but not in the return value115export class DiscardedError extends Error {}116112// `signal` and `exitCode` emitted on `subprocess.on('exit')` event can be `null`.113// We normalize them to `undefined`114const normalizeExitPayload = (rawExitCode, rawSignal) => {115 const exitCode = rawExitCode === null ? undefined : rawExitCode;
4 unmodified lines
120121const createMessages = ({122 stdio,123 all,129 error,124 originalError,125 signal,126 signalDescription,127 exitCode,128 escapedCommand,
1 unmodified line
130 isCanceled,131 timeout,132 cwd,133}) => {139 const errorCode = error?.code;134 const errorCode = originalError?.code;135 const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});141 const originalMessage = getOriginalMessage(error, cwd);136 const originalMessage = getOriginalMessage(originalError, cwd);137 const newline = originalMessage === '' ? '' : '\n';138 const shortMessage = `${prefix}: ${escapedCommand}${newline}${originalMessage}`;139 const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all];140 const message = [shortMessage, ...messageStdio, ...stdio.slice(3)]
26 unmodified lines
167168 return 'Command failed';169};170176const getOriginalMessage = (error, cwd) => {177 if (error === undefined) {171const getOriginalMessage = (originalError, cwd) => {172 if (originalError instanceof DiscardedError) {173 return '';174 }175181 const originalMessage = isPreviousError(error) ? error.originalMessage : String(error?.message ?? error);176 const originalMessage = isExecaError(originalError)177 ? originalError.originalMessage178 : String(originalError?.message ?? originalError);179 return escapeLines(fixCwdError(originalMessage, cwd));180};181182const serializeMessagePart = messagePart => Array.isArray(messagePart)
14 unmodified lines
modified:lib/async.js+1 added
97 unmodified lines
98 stdio,99 all,100 options,101 startTime,102 isSync: false,103 })104 : makeSuccessResult({command, escapedCommand, stdio, all, options, startTime});
modified:lib/sync.js+11 added-9 removed
2 unmodified lines
3import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';4import {handleOutput, handleResult} from './return/output.js';5import {handleInputSync, pipeOutputSync} from './stdio/sync.js';6import {logEarlyResult} from './verbose/complete.js';7import {isFailedExit} from './exit/code.js';7import {getSyncExitResult} from './exit/code.js';89export const execaSync = (rawFile, rawArgs, rawOptions) => {10 const {file, args, command, escapedCommand, startTime, verboseInfo, options, stdioStreamsGroups} = handleSyncArguments(rawFile, rawArgs, rawOptions);11 const result = spawnSubprocessSync({file, args, options, command, escapedCommand, stdioStreamsGroups, startTime});
28 unmodified lines
40 let syncResult;41 try {42 syncResult = spawnSync(file, args, options);43 } catch (error) {44 return makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime});44 return makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime, isSync: true});45 }4647 const {error, exitCode, signal} = getSyncExitResult(syncResult);48 pipeOutputSync(stdioStreamsGroups, syncResult);4950 const output = syncResult.output || Array.from({length: 3});51 const stdio = output.map(stdioOutput => handleOutput(options, stdioOutput));51 return getSyncResult(syncResult, {stdio, options, command, escapedCommand, startTime});52 return getSyncResult({error, exitCode, signal, stdio, options, command, escapedCommand, startTime});53};5454const getSyncResult = ({error, status, signal}, {stdio, options, command, escapedCommand, startTime}) => error !== undefined || isFailedExit(status, signal)55 ? makeError({55const getSyncResult = ({error, exitCode, signal, stdio, options, command, escapedCommand, startTime}) => error === undefined56 ? makeSuccessResult({command, escapedCommand, stdio, options, startTime})57 : makeError({58 error,59 command,60 escapedCommand,59 timedOut: error && error.code === 'ETIMEDOUT',61 timedOut: error.code === 'ETIMEDOUT',62 isCanceled: false,61 exitCode: status,63 exitCode,64 signal,65 stdio,66 options,67 startTime,66 })67 : makeSuccessResult({command, escapedCommand, stdio, options, startTime});68 isSync: true,69 });
modified:test/exit/kill.js+55 added-49 removed
185 unmodified lines
186187test('.kill(error) propagates error', async t => {188 const subprocess = execa('forever.js');189 const originalMessage = 'test';190 const error = new Error(originalMessage);191 t.true(subprocess.kill(error));192 t.is(await t.throwsAsync(subprocess), error);190 const cause = new Error(originalMessage);191 t.true(subprocess.kill(cause));192 const error = await t.throwsAsync(subprocess);193 t.is(error.cause, cause);194 t.true(cause.stack.includes(import.meta.url));195 t.is(error.exitCode, undefined);196 t.is(error.signal, 'SIGTERM');197 t.true(error.isTerminated);198 t.is(error.originalMessage, originalMessage);199 t.true(error.message.includes(originalMessage));200 t.true(error.message.includes('was killed with SIGTERM'));199 t.true(error.stack.includes(import.meta.url));201});202203test('.kill(error) uses killSignal', async t => {204 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});204 const error = new Error('test');205 subprocess.kill(error);206 t.is(await t.throwsAsync(subprocess), error);205 const cause = new Error('test');206 subprocess.kill(cause);207 const error = await t.throwsAsync(subprocess);208 t.is(error.cause, cause);209 t.is(error.signal, 'SIGINT');210});211212test('.kill(signal, error) uses signal', async t => {213 const subprocess = execa('forever.js');212 const error = new Error('test');213 subprocess.kill('SIGINT', error);214 t.is(await t.throwsAsync(subprocess), error);214 const cause = new Error('test');215 subprocess.kill('SIGINT', cause);216 const error = await t.throwsAsync(subprocess);217 t.is(error.cause, cause);218 t.is(error.signal, 'SIGINT');219});220221test('.kill(error) is a noop if subprocess already exited', async t => {
4 unmodified lines
226});227228test('.kill(error) terminates but does not change the error if the subprocess already errored but did not exit yet', async t => {229 const subprocess = execa('forever.js');227 const error = new Error('first');228 subprocess.stdout.destroy(error);230 const cause = new Error('first');231 subprocess.stdout.destroy(cause);232 await setImmediate();233 const secondError = new Error('second');234 t.true(subprocess.kill(secondError));232 t.is(await t.throwsAsync(subprocess), error);235 const error = await t.throwsAsync(subprocess);236 t.is(error.cause, cause);237 t.is(error.exitCode, undefined);238 t.is(error.signal, 'SIGTERM');239 t.true(error.isTerminated);240 t.false(error.message.includes(secondError.message));241});242243test('.kill(error) twice in a row', async t => {244 const subprocess = execa('forever.js');241 const error = new Error('first');242 subprocess.kill(error);243 const secondError = new Error('second');244 subprocess.kill(secondError);245 t.is(await t.throwsAsync(subprocess), error);246 t.false(error.message.includes(secondError.message));245 const cause = new Error('first');246 subprocess.kill(cause);247 const secondCause = new Error('second');248 subprocess.kill(secondCause);249 const error = await t.throwsAsync(subprocess);250 t.is(error.cause, cause);251 t.false(error.message.includes(secondCause.message));252});253254test('.kill(error) does not emit the "error" event', async t => {255 const subprocess = execa('forever.js');251 const error = new Error('test');252 subprocess.kill(error);253 t.is(await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]), error);256 const cause = new Error('test');257 subprocess.kill(cause);258 const error = await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]);259 t.is(error.cause, cause);260});261262test('subprocess errors are handled before spawn', async t => {263 const subprocess = execa('forever.js');258 const error = new Error('test');259 subprocess.emit('error', error);264 const cause = new Error('test');265 subprocess.emit('error', cause);266 subprocess.kill();261 const thrownError = await t.throwsAsync(subprocess);262 t.is(thrownError, error);263 t.is(thrownError.exitCode, undefined);264 t.is(thrownError.signal, undefined);265 t.false(thrownError.isTerminated);267 const error = await t.throwsAsync(subprocess);268 t.is(error.cause, cause);269 t.is(error.exitCode, undefined);270 t.is(error.signal, undefined);271 t.false(error.isTerminated);272});273274test('subprocess errors are handled after spawn', async t => {275 const subprocess = execa('forever.js');276 await once(subprocess, 'spawn');271 const error = new Error('test');272 subprocess.emit('error', error);277 const cause = new Error('test');278 subprocess.emit('error', cause);279 subprocess.kill();274 const thrownError = await t.throwsAsync(subprocess);275 t.is(thrownError, error);276 t.is(thrownError.exitCode, undefined);277 t.is(thrownError.signal, 'SIGTERM');278 t.true(thrownError.isTerminated);280 const error = await t.throwsAsync(subprocess);281 t.is(error.cause, cause);282 t.is(error.exitCode, undefined);283 t.is(error.signal, 'SIGTERM');284 t.true(error.isTerminated);285});286287test('subprocess double errors are handled after spawn', async t => {288 const abortController = new AbortController();289 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});290 await once(subprocess, 'spawn');285 const error = new Error('test');286 subprocess.emit('error', error);291 const cause = new Error('test');292 subprocess.emit('error', cause);293 await setImmediate();294 abortController.abort();289 const thrownError = await t.throwsAsync(subprocess);290 t.is(thrownError, error);291 t.is(thrownError.exitCode, undefined);292 t.is(thrownError.signal, 'SIGTERM');293 t.true(thrownError.isTerminated);295 const error = await t.throwsAsync(subprocess);296 t.is(error.cause, cause);297 t.is(error.exitCode, undefined);298 t.is(error.signal, 'SIGTERM');299 t.true(error.isTerminated);300});301302test('subprocess errors use killSignal', async t => {303 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});304 await once(subprocess, 'spawn');299 const error = new Error('test');300 subprocess.emit('error', error);305 const cause = new Error('test');306 subprocess.emit('error', cause);307 subprocess.kill();302 const thrownError = await t.throwsAsync(subprocess);303 t.is(thrownError, error);304 t.true(thrownError.isTerminated);305 t.is(thrownError.signal, 'SIGINT');308 const error = await t.throwsAsync(subprocess);309 t.is(error.cause, cause);310 t.true(error.isTerminated);311 t.is(error.signal, 'SIGINT');312});
modified:test/exit/timeout.js+4 added-3 removed
66 unmodified lines
67});6869test('timedOut is true if the timeout happened after a different error occurred', async t => {70 const subprocess = execa('forever.js', {timeout: 1e3});71 const error = new Error('test');72 subprocess.emit('error', error);73 t.is(await t.throwsAsync(subprocess), error);71 const cause = new Error('test');72 subprocess.emit('error', cause);73 const error = await t.throwsAsync(subprocess);74 t.is(error.cause, cause);75 t.true(error.timedOut);76});
modified:test/pipe/sequence.js+18 added-18 removed
25 unmodified lines
26test('Source stream error -> destination success', async t => {27 const source = execa('noop-repeat.js');28 const destination = execa('stdin.js');29 const pipePromise = source.pipe(destination);30 const error = new Error('test');31 source.stdout.destroy(error);30 const cause = new Error('test');31 source.stdout.destroy(cause);3233 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));34 t.like(await t.throwsAsync(source), {originalMessage: error.originalMessage, exitCode: 1});34 t.like(await t.throwsAsync(source), {originalMessage: cause.message, exitCode: 1});35 await destination;36});3738test('Destination stream abort -> source failure', async t => {
10 unmodified lines
49test('Destination stream error -> source failure', async t => {50 const source = execa('noop-repeat.js');51 const destination = execa('stdin.js');52 const pipePromise = source.pipe(destination);53 const error = new Error('test');54 destination.stdin.destroy(error);53 const cause = new Error('test');54 destination.stdin.destroy(cause);5556 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));57 t.like(await t.throwsAsync(destination), {originalMessage: error.originalMessage, exitCode: 0});57 t.like(await t.throwsAsync(destination), {originalMessage: cause.message, exitCode: 0});58 t.like(await t.throwsAsync(source), {exitCode: 1});59});6061test('Source success -> destination success', async t => {
128 unmodified lines
190});191192test('Source already errored -> failure', async t => {193 const source = execa('noop.js', [foobarString]);194 const error = new Error('test');195 source.stdout.destroy(error);194 const cause = new Error('test');195 source.stdout.destroy(cause);196 const destination = execa('stdin.js');197 const pipePromise = source.pipe(destination);198199 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));200 t.is(await t.throwsAsync(source), error);200 t.like(await t.throwsAsync(source), {cause});201 t.like(await destination, {stdout: ''});202});203204test('Destination already ended -> ignore source', async t => {
20 unmodified lines
225});226227test('Destination already errored -> failure', async t => {228 const destination = execa('stdin.js');229 const error = new Error('test');230 destination.stdin.destroy(error);231 t.is(await t.throwsAsync(destination), error);229 const cause = new Error('test');230 destination.stdin.destroy(cause);231 t.like(await t.throwsAsync(destination), {cause});232 const source = execa('noop.js', [foobarString]);233 const pipePromise = source.pipe(destination);234235 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));
14 unmodified lines
250 const source = execa('noop.js', ['']);251 const destination = execa('stdin.js');252 const pipePromise = source.pipe(destination);253254 const sourceError = new Error(foobarString);255 source.emit('error', sourceError);256 const destinationError = new Error('other');257 destination.emit('error', destinationError);254 const sourceCause = new Error(foobarString);255 source.emit('error', sourceCause);256 const destinationCause = new Error('other');257 destination.emit('error', destinationCause);258259 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));260 t.like(await t.throwsAsync(source), {originalMessage: sourceError.originalMessage});261 t.like(await t.throwsAsync(destination), {originalMessage: destinationError.originalMessage});260 t.like(await t.throwsAsync(source), {cause: {originalMessage: sourceCause.originalMessage}});261 t.like(await t.throwsAsync(destination), {cause: {originalMessage: destinationCause.originalMessage}});262});263264test('Does not need to await individual promises', async t => {265 const source = execa('fail.js');
48 unmodified lines
added:test/return/cause.js+158 added
1import test from 'ava';2import {execa, execaSync, ExecaError, ExecaSyncError} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString} from '../helpers/input.js';5import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';67setFixtureDir();89const testUnusualError = async (t, error, expectedOriginalMessage = String(error)) => {10 const subprocess = execa('empty.js');11 subprocess.emit('error', error);12 const {originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);13 t.is(originalMessage, expectedOriginalMessage);14 t.true(shortMessage.includes(expectedOriginalMessage));15 t.is(message, shortMessage);16};1718test('error instance can be null', testUnusualError, null);19test('error instance can be false', testUnusualError, false);20test('error instance can be a string', testUnusualError, 'test');21test('error instance can be a number', testUnusualError, 0);22test('error instance can be a BigInt', testUnusualError, 0n);23test('error instance can be a symbol', testUnusualError, Symbol('test'));24test('error instance can be a function', testUnusualError, () => {});25test('error instance can be an array', testUnusualError, ['test', 'test']);26// eslint-disable-next-line unicorn/error-message27test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');28test('error instance can be undefined', testUnusualError, undefined, 'undefined');2930test('error instance can be a plain object', async t => {31 const subprocess = execa('empty.js');32 subprocess.emit('error', {message: foobarString});33 await t.throwsAsync(subprocess, {message: new RegExp(foobarString)});34});3536const runAndFail = (t, fixtureName, argument, error) => {37 const subprocess = execa(fixtureName, [argument]);38 subprocess.emit('error', error);39 return t.throwsAsync(subprocess);40};4142const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {43 const fixtureName = 'empty.js';44 const firstArgument = 'foo';4546 const previousArgument = await getPreviousArgument(t, fixtureName);47 const previousError = await runAndFail(t, fixtureName, firstArgument, previousArgument);48 const error = await runAndFail(t, fixtureName, argument, previousError);49 const message = `Command failed: ${fixtureName} ${argument}\n${foobarString}`;5051 t.not(error, previousError);52 t.is(error.cause, previousError);53 t.is(error.command, `${fixtureName} ${argument}`);54 t.is(error.message, message);55 t.true(error.stack.includes(message));56 t.is(error.shortMessage, message);57 t.is(error.originalMessage, foobarString);58};5960test('error instance can be shared', testErrorCopy, () => new Error(foobarString));61test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));62test('error string can be shared', testErrorCopy, () => foobarString);63test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));64test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');6566test('error.cause is not set if error.exitCode is not 0', async t => {67 const {exitCode, cause} = await t.throwsAsync(execa('fail.js'));68 t.is(exitCode, 2);69 t.is(cause, undefined);70});7172test('error.cause is not set if error.isTerminated', async t => {73 const subprocess = execa('forever.js');74 subprocess.kill();75 const {isTerminated, cause} = await t.throwsAsync(subprocess);76 t.true(isTerminated);77 t.is(cause, undefined);78});7980test('error.cause is not set if error.timedOut', async t => {81 const {timedOut, cause} = await t.throwsAsync(execa('forever.js', {timeout: 1}));82 t.true(timedOut);83 t.is(cause, undefined);84});8586test('error.cause is set on error event', async t => {87 const subprocess = execa('empty.js');88 const error = new Error(foobarString);89 subprocess.emit('error', error);90 const {cause} = await t.throwsAsync(subprocess);91 t.is(cause, error);92});9394test('error.cause is set if error.isCanceled', async t => {95 const controller = new AbortController();96 const subprocess = execa('forever.js', {cancelSignal: controller.signal});97 const error = new Error('test');98 controller.abort(error);99 const {isCanceled, isTerminated, cause} = await t.throwsAsync(subprocess);100 t.true(isCanceled);101 t.false(isTerminated);102 t.is(cause.cause, error);103});104105test('error.cause is not set if error.isTerminated with .kill(error)', async t => {106 const subprocess = execa('forever.js');107 const error = new Error('test');108 subprocess.kill(error);109 const {isTerminated, cause} = await t.throwsAsync(subprocess);110 t.true(isTerminated);111 t.is(cause, error);112});113114test('Error is instanceof ExecaError', async t => {115 await t.throwsAsync(execa('fail.js'), {instanceOf: ExecaError});116});117118test('Early error is instanceof ExecaError', async t => {119 await t.throwsAsync(getEarlyErrorSubprocess(), {instanceOf: ExecaError});120});121122test('Error is instanceof ExecaSyncError', t => {123 t.throws(() => {124 execaSync('fail.js');125 }, {instanceOf: ExecaSyncError});126});127128test('Early error is instanceof ExecaSyncError', t => {129 t.throws(() => {130 getEarlyErrorSubprocessSync();131 }, {instanceOf: ExecaSyncError});132});133134test('Pipe error is instanceof ExecaError', async t => {135 await t.throwsAsync(execa('empty.js').pipe(false), {instanceOf: ExecaError});136});137138const assertNameShape = (t, error) => {139 t.false(Object.hasOwn(error, 'name'));140 t.true(Object.hasOwn(Object.getPrototypeOf(error), 'name'));141 t.false(propertyIsEnumerable.call(Object.getPrototypeOf(error), 'name'));142};143144const {propertyIsEnumerable} = Object.prototype;145146test('error.name is properly set', async t => {147 const error = await t.throwsAsync(execa('fail.js'));148 t.is(error.name, 'ExecaError');149 assertNameShape(t, error);150});151152test('error.name is properly set - sync', async t => {153 const error = await t.throws(() => {154 execaSync('fail.js');155 });156 t.is(error.name, 'ExecaSyncError');157 assertNameShape(t, error);158});
deleted:test/return/clone.js-150 removed
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString} from '../helpers/input.js';56setFixtureDir();78const testUnusualError = async (t, error, expectedOriginalMessage = String(error)) => {9 const subprocess = execa('empty.js');10 subprocess.emit('error', error);11 const {originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);12 t.is(originalMessage, expectedOriginalMessage);13 t.true(shortMessage.includes(expectedOriginalMessage));14 t.is(message, shortMessage);15};1617test('error instance can be null', testUnusualError, null);18test('error instance can be false', testUnusualError, false);19test('error instance can be a string', testUnusualError, 'test');20test('error instance can be a number', testUnusualError, 0);21test('error instance can be a BigInt', testUnusualError, 0n);22test('error instance can be a symbol', testUnusualError, Symbol('test'));23test('error instance can be a function', testUnusualError, () => {});24test('error instance can be an array', testUnusualError, ['test', 'test']);25// eslint-disable-next-line unicorn/error-message26test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');27test('error instance can be undefined', testUnusualError, undefined, '');2829test('error instance can be a plain object', async t => {30 const subprocess = execa('empty.js');31 subprocess.emit('error', {message: foobarString});32 await t.throwsAsync(subprocess, {message: new RegExp(foobarString)});33});3435const runAndFail = (t, fixtureName, argument, error) => {36 const subprocess = execa(fixtureName, [argument]);37 subprocess.emit('error', error);38 return t.throwsAsync(subprocess);39};4041const runAndClone = async (t, initialError) => {42 const previousError = await runAndFail(t, 'empty.js', 'foo', initialError);43 t.is(previousError, initialError);4445 return runAndFail(t, 'empty.js', 'bar', previousError);46};4748const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {49 const fixtureName = 'empty.js';50 const firstArgument = 'foo';5152 const previousArgument = await getPreviousArgument(t, fixtureName);53 const previousError = await runAndFail(t, fixtureName, firstArgument, previousArgument);54 const error = await runAndFail(t, fixtureName, argument, previousError);55 const message = `Command failed: ${fixtureName} ${argument}\n${foobarString}`;5657 t.not(error, previousError);58 t.is(error.command, `${fixtureName} ${argument}`);59 t.is(error.message, message);60 t.true(error.stack.includes(message));61 t.is(error.stack, previousError.stack.replace(firstArgument, argument));62 t.is(error.shortMessage, message);63 t.is(error.originalMessage, foobarString);64};6566test('error instance can be shared', testErrorCopy, () => new Error(foobarString));67test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));68test('error string can be shared', testErrorCopy, () => foobarString);69test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));70test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');7172const testErrorCopyProperty = async (t, propertyName, isCopied) => {73 const propertyValue = 'test';74 const initialError = new Error(foobarString);75 initialError[propertyName] = propertyValue;7677 const error = await runAndClone(t, initialError);78 t.is(error[propertyName] === propertyValue, isCopied);79};8081test('error.code can be copied', testErrorCopyProperty, 'code', true);82test('error.errno can be copied', testErrorCopyProperty, 'errno', true);83test('error.syscall can be copied', testErrorCopyProperty, 'syscall', true);84test('error.path can be copied', testErrorCopyProperty, 'path', true);85test('error.dest can be copied', testErrorCopyProperty, 'dest', true);86test('error.address can be copied', testErrorCopyProperty, 'address', true);87test('error.port can be copied', testErrorCopyProperty, 'port', true);88test('error.info can be copied', testErrorCopyProperty, 'info', true);89test('error.other cannot be copied', testErrorCopyProperty, 'other', false);9091test('error.name can be copied', async t => {92 const initialError = new TypeError('test');93 const error = await runAndClone(t, initialError);94 t.deepEqual(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(initialError), 'name'), Object.getOwnPropertyDescriptor(error, 'name'));95});9697test('error.cause can be copied', async t => {98 const initialError = new Error('test', {cause: new Error('innerTest')});99 const error = await runAndClone(t, initialError);100 t.deepEqual(Object.getOwnPropertyDescriptor(initialError, 'cause'), Object.getOwnPropertyDescriptor(error, 'cause'));101});102103test('error.errors can be copied', async t => {104 const initialError = new AggregateError([], 'test');105 const error = await runAndClone(t, initialError);106 t.deepEqual(Object.getOwnPropertyDescriptor(initialError, 'errors'), Object.getOwnPropertyDescriptor(error, 'errors'));107});108109test('error.stack is set even if memoized', async t => {110 const message = 'test';111 const error = new Error(message);112 t.is(typeof error.stack, 'string');113114 const newMessage = 'newTest';115 error.message = newMessage;116 t.false(error.stack.includes(newMessage));117 error.message = message;118119 const subprocess = execa('empty.js');120 subprocess.emit('error', error);121 t.is(await t.throwsAsync(subprocess), error);122 t.is(error.message, `Command failed: empty.js\n${message}`);123 t.true(error.stack.startsWith(`Error: ${error.message}`));124});125126test('error.stack is set even if memoized with an unusual error.name', async t => {127 const subprocess = execa('empty.js');128 subprocess.stdin.destroy();129 const error = await t.throwsAsync(subprocess);130 t.is(error.message, 'Command failed with ERR_STREAM_PREMATURE_CLOSE: empty.js\nPremature close');131 t.true(error.stack.startsWith(`Error [ERR_STREAM_PREMATURE_CLOSE]: ${error.message}`));132});133134test('Cloned errors keep the stack trace', async t => {135 const message = 'test';136 const error = new Error(message);137 const stack = error.stack.split('\n').filter(line => line.trim().startsWith('at ')).join('\n');138139 const subprocess = execa('empty.js');140 subprocess.emit('error', error);141 t.is(await t.throwsAsync(subprocess), error);142143 const secondSubprocess = execa('empty.js');144 secondSubprocess.emit('error', error);145 const secondError = await t.throwsAsync(secondSubprocess);146 t.not(secondError, error);147 t.is(secondError.message, `Command failed: empty.js\n${message}`);148 t.is(secondError.stack, `Error: Command failed: empty.js\n${message}\n${stack}`);149});150
modified:test/return/error.js+1 added
45 unmodified lines
46 'isTerminated',47 'exitCode',48 'signal',49 'signalDescription',50 'code',51 'stdout',52 'stderr',53 'all',54 'stdio',
135 unmodified lines
modified:test/stdio/node-stream.js+14 added-13 removed
70 unmodified lines
71 return {stream, filePath};72};7374const assertFileStreamError = async (t, subprocess, stream, filePath) => {75 const error = new Error('test');76 stream.destroy(error);75 const cause = new Error('test');76 stream.destroy(cause);7778 t.is(await t.throwsAsync(subprocess), error);78 const error = await t.throwsAsync(subprocess);79 t.is(error.cause, cause);80 t.is(error.exitCode, 0);81 t.is(error.signal, undefined);8283 await rm(filePath);
142 unmodified lines
226 t.true(waitedForDestroy);227});228229test('Handles custom streams destroy errors on subprocess success', async t => {229 const error = new Error('test');230 const cause = new Error('test');231 const stream = new Writable({232 destroy(destroyError, done) {232 done(destroyError ?? error);233 done(destroyError ?? cause);234 },235 });235 const thrownError = await t.throwsAsync(execa('empty.js', {stdout: [stream, 'pipe']}));236 t.is(thrownError, error);236 const error = await t.throwsAsync(execa('empty.js', {stdout: [stream, 'pipe']}));237 t.is(error.cause, cause);238});239240const testStreamEarlyExit = async (t, stream, streamName) => {241 await t.throwsAsync(execa('noop.js', {[streamName]: [stream, 'pipe'], uid: -1}));
39 unmodified lines
281test('subprocess.stdio[*] is ended when an input stream aborts', testInputStreamAbort, 3);282283const testInputStreamError = async (t, fdNumber) => {284 const stream = new PassThrough();284 const error = new Error(foobarString);285 stream.destroy(error);285 const cause = new Error(foobarString);286 stream.destroy(cause);287288 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));288 t.is(await t.throwsAsync(subprocess), error);289 t.like(await t.throwsAsync(subprocess), {cause});290 t.true(subprocess.stdio[fdNumber].writableEnded);291};292293test('subprocess.stdin is ended when an input stream errors', testInputStreamError, 0);294test('subprocess.stdio[*] is ended when an input stream errors', testInputStreamError, 3);295296const testOutputStreamError = async (t, fdNumber) => {297 const stream = new PassThrough();297 const error = new Error(foobarString);298 stream.destroy(error);298 const cause = new Error(foobarString);299 stream.destroy(cause);300301 const subprocess = execa('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe']));301 t.is(await t.throwsAsync(subprocess), error);302 t.like(await t.throwsAsync(subprocess), {cause});303 t.true(subprocess.stdio[fdNumber].readableAborted);304 t.is(subprocess.stdio[fdNumber].errored, null);305};306
3 unmodified lines
modified:test/stdio/pipeline.js+3 added-4 removed
24 unmodified lines
25test('Does not destroy process.stderr on subprocess early errors', testDestroyStandardSpawn, 2);2627const testDestroyStandardStream = async (t, fdNumber) => {28 const subprocess = execa('forever.js', getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']));29 const error = new Error('test');30 subprocess.stdio[fdNumber].destroy(error);29 const cause = new Error('test');30 subprocess.stdio[fdNumber].destroy(cause);31 subprocess.kill();32 const thrownError = await t.throwsAsync(subprocess);33 t.is(thrownError, error);32 t.like(await t.throwsAsync(subprocess), {cause});33 t.false(STANDARD_STREAMS[fdNumber].destroyed);34};3536test('Does not destroy process.stdin on stream subprocess errors', testDestroyStandardStream, 0);
2 unmodified lines
modified:test/stdio/transform.js+3 added-3 removed
189 unmodified lines
190test('Running generators are canceled on subprocess error', testGeneratorCancel, new Error('test'));191192const testGeneratorDestroy = async (t, transform) => {193 const subprocess = execa('forever.js', {stdout: transform});194 const error = new Error('test');195 subprocess.stdout.destroy(error);194 const cause = new Error('test');195 subprocess.stdout.destroy(cause);196 subprocess.kill();197 t.is(await t.throwsAsync(subprocess), error);197 t.like(await t.throwsAsync(subprocess), {cause});198};199200test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));201test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator);
4 unmodified lines
modified:test/stdio/web-stream.js+8 added-8 removed
58 unmodified lines
59test('stderr waits for WritableStream completion', testLongWritableStream, 2);60test('stdio[*] waits for WritableStream completion', testLongWritableStream, 3);6162const testWritableStreamError = async (t, fdNumber) => {63 const error = new Error('foobar');63 const cause = new Error('foobar');64 const writableStream = new WritableStream({65 start(controller) {66 controller.error(error);66 controller.error(cause);67 },68 });69 const thrownError = await t.throwsAsync(execa('noop.js', getStdio(fdNumber, writableStream)));70 t.is(thrownError, error);69 const error = await t.throwsAsync(execa('noop.js', getStdio(fdNumber, writableStream)));70 t.is(error.cause, cause);71};7273test('stdout option handles errors in WritableStream', testWritableStreamError, 1);74test('stderr option handles errors in WritableStream', testWritableStreamError, 2);75test('stdio[*] option handles errors in WritableStream', testWritableStreamError, 3);7677const testReadableStreamError = async (t, fdNumber) => {78 const error = new Error('foobar');78 const cause = new Error('foobar');79 const readableStream = new ReadableStream({80 start(controller) {81 controller.error(error);81 controller.error(cause);82 },83 });84 const thrownError = await t.throwsAsync(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, readableStream)));85 t.is(thrownError, error);84 const error = await t.throwsAsync(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, readableStream)));85 t.is(error.cause, cause);86};8788test('stdin option handles errors in ReadableStream', testReadableStreamError, 0);89test('stdio[*] option handles errors in ReadableStream', testReadableStreamError, 3);
9 unmodified lines
modified:test/stream/no-buffer.js+3 added-3 removed
73 unmodified lines
7475const testNoBufferStreamError = async (t, fdNumber, all) => {76 const subprocess = execa('noop-fd.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});77 const stream = all ? subprocess.all : subprocess.stdio[fdNumber];78 const error = new Error('test');79 stream.destroy(error);80 t.is(await t.throwsAsync(subprocess), error);78 const cause = new Error('test');79 stream.destroy(cause);80 t.like(await t.throwsAsync(subprocess), {cause});81};8283test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);84test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);
26 unmodified lines
modified:test/stream/subprocess.js+16 added-12 removed
57 unmodified lines
58test('Aborting output stdio[*] should not make the subprocess exit', testStreamOutputAbort, 3);5960const testStreamInputDestroy = async (t, fdNumber) => {61 const subprocess = getStreamInputSubprocess(fdNumber);62 const error = new Error('test');63 subprocess.stdio[fdNumber].destroy(error);64 t.is(await t.throwsAsync(subprocess), error);62 const cause = new Error('test');63 subprocess.stdio[fdNumber].destroy(cause);64 const error = await t.throwsAsync(subprocess);65 t.is(error.cause, cause);66 assertStreamInputError(t, error);67};6869test('Destroying stdin should not make the subprocess exit', testStreamInputDestroy, 0);70test('Destroying input stdio[*] should not make the subprocess exit', testStreamInputDestroy, 3);7172const testStreamOutputDestroy = async (t, fdNumber) => {73 const subprocess = getStreamOutputSubprocess(fdNumber);73 const error = new Error('test');74 subprocess.stdio[fdNumber].destroy(error);75 t.is(await t.throwsAsync(subprocess), error);74 const cause = new Error('test');75 subprocess.stdio[fdNumber].destroy(cause);76 const error = await t.throwsAsync(subprocess);77 t.is(error.cause, cause);78 assertStreamOutputError(t, fdNumber, error);79};8081test('Destroying stdout should not make the subprocess exit', testStreamOutputDestroy, 1);
1 unmodified line
83test('Destroying output stdio[*] should not make the subprocess exit', testStreamOutputDestroy, 3);8485const testStreamInputError = async (t, fdNumber) => {86 const subprocess = getStreamInputSubprocess(fdNumber);85 const error = new Error('test');87 const cause = new Error('test');88 const stream = subprocess.stdio[fdNumber];87 stream.emit('error', error);89 stream.emit('error', cause);90 stream.end();89 t.is(await t.throwsAsync(subprocess), error);91 const error = await t.throwsAsync(subprocess);92 t.is(error.cause, cause);93 assertStreamInputError(t, error);94};9596test('Errors on stdin should not make the subprocess exit', testStreamInputError, 0);97test('Errors on input stdio[*] should not make the subprocess exit', testStreamInputError, 3);9899const testStreamOutputError = async (t, fdNumber) => {100 const subprocess = getStreamOutputSubprocess(fdNumber);98 const error = new Error('test');101 const cause = new Error('test');102 const stream = subprocess.stdio[fdNumber];100 stream.emit('error', error);101 t.is(await t.throwsAsync(subprocess), error);103 stream.emit('error', cause);104 const error = await t.throwsAsync(subprocess);105 t.is(error.cause, cause);106 assertStreamOutputError(t, fdNumber, error);107};108109test('Errors on stdout should not make the subprocess exit', testStreamOutputError, 1);
13 unmodified lines
modified:test/stream/wait.js+8 added-8 removed
164 unmodified lines
165166// eslint-disable-next-line max-params167const testStreamError = async (t, streamMethod, stream, fdNumber, useTransform) => {168 const subprocess = execa('empty.js', getStreamStdio(fdNumber, stream, useTransform));169 const error = new Error('test');170 streamMethod({stream, subprocess, fdNumber, error});169 const cause = new Error('test');170 streamMethod({stream, subprocess, fdNumber, error: cause});171172 t.is(await t.throwsAsync(subprocess), error);173 const {exitCode, signal, isTerminated, failed} = error;174 t.is(exitCode, 0);175 t.is(signal, undefined);176 t.false(isTerminated);177 t.true(failed);172 const error = await t.throwsAsync(subprocess);173 t.is(error.cause, cause);174 t.is(error.exitCode, 0);175 t.is(error.signal, undefined);176 t.false(error.isTerminated);177 t.true(error.failed);178 t.true(stream.destroyed);179};180181test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);
35 unmodified lines
modified:index.d.ts+119 added-40 removed
482 unmodified lines
483 */484 readonly encoding?: EncodingOption;485486 /**487 If `timeout` is greater than `0`, the subprocess will be [terminated](#killsignal) if it runs for longer than that amount of milliseconds.487 If `timeout` is greater than `0`, the subprocess will be terminated if it runs for longer than that amount of milliseconds.488489 @default 0490 */491 readonly timeout?: number;
118 unmodified lines
610611 /**612 You can abort the subprocess using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).613614 When `AbortController.abort()` is called, [`.isCanceled`](https://github.com/sindresorhus/execa#iscanceled) becomes `true`.614 When `AbortController.abort()` is called, `.isCanceled` becomes `true`.615616 @example617 ```618 import {execa} from 'execa';
18 unmodified lines
637638export type Options = CommonOptions<false>;639export type SyncOptions = CommonOptions<true>;640641/**642Result of a subprocess execution. On success this is a plain object. On failure this is also an `Error` instance.643644The subprocess fails when:645- its exit code is not `0`646- it was terminated with a signal647- timing out648- being canceled649- there's not enough memory or there are already too many subprocesses650*/651type ExecaCommonResult<IsSync extends boolean = boolean, OptionsType extends CommonOptions = CommonOptions> = {641declare abstract class CommonResult<642 IsSync extends boolean = boolean,643 OptionsType extends CommonOptions = CommonOptions,644> {645 /**646 The file and arguments that were run, for logging purposes.647648 This is not escaped and should not be executed directly as a subprocess, including using `execa()` or `execaCommand()`.
12 unmodified lines
661662 /**663 The numeric exit code of the subprocess that was run.664672 This is `undefined` when the subprocess could not be spawned or was terminated by a [signal](#signal).665 This is `undefined` when the subprocess could not be spawned or was terminated by a signal.666 */667 exitCode?: number;668669 /**
81 unmodified lines
751752 This array is initially empty and is populated each time the `.pipe()` method resolves.753 */754 pipedFrom: IfAsync<IsSync, ExecaResult[], []>;762 // Workaround for a TypeScript bug: https://github.com/microsoft/TypeScript/issues/57062763} & {};755765export type ExecaResult<OptionsType extends Options = Options> = ExecaCommonResult<false, OptionsType> & ErrorUnlessReject<OptionsType['reject']>;766export type ExecaSyncResult<OptionsType extends SyncOptions = SyncOptions> = ExecaCommonResult<true, OptionsType> & ErrorUnlessReject<OptionsType['reject']>;767768type ErrorUnlessReject<RejectOption extends CommonOptions['reject']> = RejectOption extends false769 ? Partial<ExecaCommonError>770 : {};771772type ExecaCommonError = {756 /**757 Error message when the subprocess failed to run. In addition to the underlying error message, it also contains some information related to why the subprocess errored.758759 The subprocess `stderr`, `stdout` and other file descriptors' output are appended to the end, separated with newlines and not interleaved.760 */778 message: string;761 message?: string;762763 /**764 This is the same as the `message` property except it does not include the subprocess `stdout`/`stderr`/`stdio`.765 */783 shortMessage: string;766 shortMessage?: string;767768 /**769 Original error message. This is the same as the `message` property excluding the subprocess `stdout`/`stderr`/`stdio` and some additional information added by Execa.770788 This is `undefined` unless the subprocess exited due to an `error` event or a timeout.771 This exists only if the subprocess exited due to an `error` event or a timeout.772 */773 originalMessage?: string;791} & Error;774793export type ExecaError<OptionsType extends Options = Options> = ExecaCommonResult<false, OptionsType> & ExecaCommonError;794export type ExecaSyncError<OptionsType extends SyncOptions = SyncOptions> = ExecaCommonResult<true, OptionsType> & ExecaCommonError;775 /**776 Underlying error, if there is one. For example, this is set by `.kill(error)`.777778 This is usually an `Error` instance.779 */780 cause?: unknown;781782 /**783 Node.js-specific [error code](https://nodejs.org/api/errors.html#errorcode), when available.784 */785 code?: string;786787 // We cannot `extend Error` because `message` must be optional. So we copy its types here.788 readonly name?: Error['name'];789 stack?: Error['stack'];790}791792type CommonResultInstance<793 IsSync extends boolean = boolean,794 OptionsType extends CommonOptions = CommonOptions,795> = InstanceType<typeof CommonResult<IsSync, OptionsType>>;796797type SuccessResult<798 IsSync extends boolean = boolean,799 OptionsType extends CommonOptions = CommonOptions,800> = CommonResultInstance<IsSync, OptionsType> & OmitErrorIfReject<OptionsType['reject']>;801802type OmitErrorIfReject<RejectOption extends CommonOptions['reject']> = RejectOption extends false803 ? {}804 : {[ErrorProperty in ErrorProperties]: never};805806type ErrorProperties =807 | 'name'808 | 'message'809 | 'stack'810 | 'cause'811 | 'shortMessage'812 | 'originalMessage'813 | 'code';814815/**816Result of a subprocess execution.817818When the subprocess fails, it is rejected with an `ExecaError` instead.819*/820export type ExecaResult<OptionsType extends Options = Options> = SuccessResult<false, OptionsType>;821822/**823Result of a subprocess execution.824825When the subprocess fails, it is rejected with an `ExecaError` instead.826*/827export type ExecaSyncResult<OptionsType extends SyncOptions = SyncOptions> = SuccessResult<true, OptionsType>;828829declare abstract class CommonError<830 IsSync extends boolean = boolean,831 OptionsType extends CommonOptions = CommonOptions,832> extends CommonResult<IsSync, OptionsType> {833 readonly name: NonNullable<CommonResult['name']>;834 message: NonNullable<CommonResult['message']>;835 stack: NonNullable<CommonResult['stack']>;836 shortMessage: NonNullable<CommonResult['shortMessage']>;837 originalMessage: NonNullable<CommonResult['originalMessage']>;838}839840/**841Exception thrown when the subprocess fails, either:842- its exit code is not `0`843- it was terminated with a signal, including `.kill()`844- timing out845- being canceled846- there's not enough memory or there are already too many subprocesses847848This has the same shape as successful results, with a few additional properties.849*/850export class ExecaError<OptionsType extends Options = Options> extends CommonError<false, OptionsType> {851 readonly name: 'ExecaError';852}853854/**855Exception thrown when the subprocess fails, either:856- its exit code is not `0`857- it was terminated with a signal, including `.kill()`858- timing out859- being canceled860- there's not enough memory or there are already too many subprocesses861862This has the same shape as successful results, with a few additional properties.863*/864export class ExecaSyncError<OptionsType extends SyncOptions = SyncOptions> extends CommonError<true, OptionsType> {865 readonly name: 'ExecaSyncError';866}867868type StreamUnlessIgnored<869 FdNumber extends string,870 OptionsType extends Options = Options,871> = SubprocessStream<FdNumber, IgnoresStreamResult<FdNumber, OptionsType>, OptionsType>;
117 unmodified lines
989 Sends a [signal](https://nodejs.org/api/os.html#signal-constants) to the subprocess. The default signal is the `killSignal` option. `killSignal` defaults to `SIGTERM`, which terminates the subprocess.990991 This returns `false` when the signal could not be sent, for example when the subprocess has already exited.992921 When an error is passed as argument, its message and stack trace are kept in the subprocess' error. The subprocess is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).993 When an error is passed as argument, it is set to the subprocess' `error.cause`. The subprocess is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).994995 [More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)996 */997 kill(signal: Parameters<ChildProcess['kill']>[0], error?: Error): ReturnType<ChildProcess['kill']>;
80 unmodified lines
1078 await execa('unknown', ['command']);1079} catch (error) {1080 console.log(error);1081 /*1010 {1011 message: 'Command failed with ENOENT: unknown command\nspawn unknown ENOENT',1012 errno: -2,1013 code: 'ENOENT',1014 syscall: 'spawn unknown',1015 path: 'unknown',1016 spawnargs: ['command'],1082 ExecaError: Command failed with ENOENT: unknown command1083 spawn unknown ENOENT1084 at ...1085 at ... {1086 shortMessage: 'Command failed with ENOENT: unknown command\nspawn unknown ENOENT',1087 originalMessage: 'spawn unknown ENOENT',1088 command: 'unknown command',1089 escapedCommand: 'unknown command',
2 unmodified lines
1092 failed: true,1093 timedOut: false,1094 isCanceled: false,1095 isTerminated: false,1096 code: 'ENOENT',1097 stdout: '',1098 stderr: '',1099 stdio: [undefined, '', ''],1100 pipedFrom: []1101 [cause]: Error: spawn unknown ENOENT1102 at ...1103 at ... {1104 errno: -2,1105 code: 'ENOENT',1106 syscall: 'spawn unknown',1107 path: 'unknown',1108 spawnargs: [ 'command' ]1109 }1110 }1111 \*\/1112}1113```
133 unmodified lines
1247 command: string,1248 options?: OptionsType1249): ExecaSyncResult<OptionsType>;12501172type TemplateExpression = string | number | ExecaCommonResult1173| Array<string | number | ExecaCommonResult>;1251type TemplateExpression = string | number | CommonResultInstance1252| Array<string | number | CommonResultInstance>;12531254type Execa$<OptionsType extends CommonOptions = {}> = {1255 /**1256 Returns a new instance of `$` but with different default `options`. Consecutive calls are merged to previous ones.
221 unmodified lines
modified:index.js+1 added
1 unmodified line
2export {execaSync} from './lib/sync.js';3export {execaCommand, execaCommandSync} from './lib/command.js';4export {execaNode} from './lib/arguments/node.js';5export {$} from './lib/script.js';6export {ExecaError, ExecaSyncError} from './lib/return/cause.js';
modified:index.test-d.ts+56 added-45 removed
10 unmodified lines
11 execaSync,12 execaCommand,13 execaCommandSync,14 execaNode,15 ExecaError,16 ExecaSyncError,17 type Options,18 type ExecaResult,19 type ExecaSubprocess,18 type ExecaError,20 type SyncOptions,21 type ExecaSyncResult,21 type ExecaSyncError,22} from './index.js';2324const fileUrl = new URL('file:///test');25
549 unmodified lines
575 expectType<string>(falseFalseObjectTransformResult.stderr);576 expectType<string>(falseFalseObjectTransformResult.all);577 expectType<[undefined, string, string]>(falseFalseObjectTransformResult.stdio);578} catch (error: unknown) {579 const execaError = error as ExecaError;579 if (error instanceof ExecaError) {580 expectAssignable<ExecaError>(error);581 expectType<'ExecaError'>(error.name);582 expectType<string>(error.message);583 expectType<number | undefined>(error.exitCode);584 expectType<boolean>(error.failed);585 expectType<boolean>(error.timedOut);586 expectType<boolean>(error.isCanceled);587 expectType<boolean>(error.isTerminated);588 expectType<string | undefined>(error.signal);589 expectType<string | undefined>(error.signalDescription);590 expectType<string>(error.cwd);591 expectType<number>(error.durationMs);592 expectType<string>(error.shortMessage);593 expectType<string>(error.originalMessage);594 expectType<string | undefined>(error.code);595 expectType<unknown>(error.cause);596 expectType<ExecaResult[]>(error.pipedFrom);597 }598581 expectType<string>(execaError.message);582 expectType<number | undefined>(execaError.exitCode);583 expectType<boolean>(execaError.failed);584 expectType<boolean>(execaError.timedOut);585 expectType<boolean>(execaError.isCanceled);586 expectType<boolean>(execaError.isTerminated);587 expectType<string | undefined>(execaError.signal);588 expectType<string | undefined>(execaError.signalDescription);589 expectType<string>(execaError.cwd);590 expectType<number>(execaError.durationMs);591 expectType<string>(execaError.shortMessage);592 expectType<string | undefined>(execaError.originalMessage);593 expectType<ExecaResult[]>(execaError.pipedFrom);594595 expectType<undefined>(execaError.stdio[0]);596599 const noAllError = error as ExecaError<{}>;600 expectType<undefined>(noAllError.stdio[0]);601 expectType<undefined>(noAllError.all);602603 const execaStringError = error as ExecaError<{all: true}>;604 expectType<string>(execaStringError.stdout);
107 unmodified lines
712 expectType<[undefined, string, string]>(falseObjectTransformStdioError.stdio);713}714715const rejectsResult = await execa('unicorns');713expectError(rejectsResult.stack);714expectError(rejectsResult.message);715expectError(rejectsResult.shortMessage);716expectError(rejectsResult.originalMessage);716expectError(rejectsResult.stack?.toString());717expectError(rejectsResult.message?.toString());718expectError(rejectsResult.shortMessage?.toString());719expectError(rejectsResult.originalMessage?.toString());720expectError(rejectsResult.code?.toString());721expectError(rejectsResult.cause?.valueOf());722723const noRejectsResult = await execa('unicorns', {reject: false});724expectType<string | undefined>(noRejectsResult.stack);725expectType<string | undefined>(noRejectsResult.message);726expectType<string | undefined>(noRejectsResult.shortMessage);727expectType<string | undefined>(noRejectsResult.originalMessage);728expectType<string | undefined>(noRejectsResult.code);729expectType<unknown>(noRejectsResult.cause);730731try {732 const unicornsResult = execaSync('unicorns');733
67 unmodified lines
801 expectType<string>(numberStderrResult.stdout);802 expectType<undefined>(numberStderrResult.stderr);803 expectError(numberStderrResult.all.toString());804} catch (error: unknown) {798 const execaError = error as ExecaSyncError;805 if (error instanceof ExecaSyncError) {806 expectAssignable<ExecaSyncError>(error);807 expectType<'ExecaSyncError'>(error.name);808 expectType<string>(error.message);809 expectType<number | undefined>(error.exitCode);810 expectType<boolean>(error.failed);811 expectType<boolean>(error.timedOut);812 expectType<boolean>(error.isCanceled);813 expectType<boolean>(error.isTerminated);814 expectType<string | undefined>(error.signal);815 expectType<string | undefined>(error.signalDescription);816 expectType<string>(error.cwd);817 expectType<number>(error.durationMs);818 expectType<string>(error.shortMessage);819 expectType<string>(error.originalMessage);820 expectType<string | undefined>(error.code);821 expectType<unknown>(error.cause);822 expectType<[]>(error.pipedFrom);823 }824800 expectType<ExecaSyncError>(execaError);801 expectType<string>(execaError.message);802 expectType<number | undefined>(execaError.exitCode);803 expectType<boolean>(execaError.failed);804 expectType<boolean>(execaError.timedOut);805 expectType<boolean>(execaError.isCanceled);806 expectType<boolean>(execaError.isTerminated);807 expectType<string | undefined>(execaError.signal);808 expectType<string | undefined>(execaError.signalDescription);809 expectType<string>(execaError.cwd);810 expectType<number>(execaError.durationMs);811 expectType<string>(execaError.shortMessage);812 expectType<string | undefined>(execaError.originalMessage);813 expectType<[]>(execaError.pipedFrom);814815 expectType<undefined>(execaError.stdio[0]);816825 const execaStringError = error as ExecaSyncError<{}>;826 expectType<undefined>(execaStringError.stdio[0]);827 expectType<string>(execaStringError.stdout);828 expectType<string>(execaStringError.stdio[1]);829 expectType<string>(execaStringError.stderr);830 expectType<string>(execaStringError.stdio[2]);
49 unmodified lines
880 expectError(numberStderrError.all.toString());881}882883const rejectsSyncResult = execaSync('unicorns');875expectError(rejectsSyncResult.stack);876expectError(rejectsSyncResult.message);877expectError(rejectsSyncResult.shortMessage);878expectError(rejectsSyncResult.originalMessage);884expectError(rejectsSyncResult.stack?.toString());885expectError(rejectsSyncResult.message?.toString());886expectError(rejectsSyncResult.shortMessage?.toString());887expectError(rejectsSyncResult.originalMessage?.toString());888expectError(rejectsSyncResult.code?.toString());889expectError(rejectsSyncResult.cause?.valueOf());890891const noRejectsSyncResult = execaSync('unicorns', {reject: false});892expectType<string | undefined>(noRejectsSyncResult.stack);893expectType<string | undefined>(noRejectsSyncResult.message);
708 unmodified lines
modified:readme.md+70 added-40 removed
217 unmodified lines
218 await execa('unknown', ['command']);219} catch (error) {220 console.log(error);221 /*222 {223 message: 'Command failed with ENOENT: unknown command\nspawn unknown ENOENT',224 errno: -2,225 code: 'ENOENT',226 syscall: 'spawn unknown',227 path: 'unknown',228 spawnargs: ['command'],222 ExecaError: Command failed with ENOENT: unknown command223 spawn unknown ENOENT224 at ...225 at ... {226 shortMessage: 'Command failed with ENOENT: unknown command\nspawn unknown ENOENT',227 originalMessage: 'spawn unknown ENOENT',228 command: 'unknown command',229 escapedCommand: 'unknown command',
2 unmodified lines
232 failed: true,233 timedOut: false,234 isCanceled: false,235 isTerminated: false,236 code: 'ENOENT',237 stdout: '',238 stderr: '',239 stdio: [undefined, '', ''],240 pipedFrom: []241 [cause]: Error: spawn unknown ENOENT242 at ...243 at ... {244 errno: -2,245 code: 'ENOENT',246 syscall: 'spawn unknown',247 path: 'unknown',248 spawnargs: [ 'command' ]249 }250 }251 */252}253```
109 unmodified lines
363`arguments`: `string[]`\364`options`: [`Options`](#options-1) and [`PipeOptions`](#pipeoptions)\365_Returns_: [`Promise<SubprocessResult>`](#subprocessresult)366360[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the subprocess' `stdout` to a second Execa subprocess' `stdin`. This resolves with that second subprocess' [result](#subprocessresult). If either subprocess is rejected, this is rejected with that subprocess' [error](#subprocessresult) instead.367[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the subprocess' `stdout` to a second Execa subprocess' `stdin`. This resolves with that second subprocess' [result](#subprocessresult). If either subprocess is rejected, this is rejected with that subprocess' [error](#execaerror) instead.368369This follows the same syntax as [`execa(file, arguments?, options?)`](#execafile-arguments-options) except both [regular options](#options-1) and [pipe-specific options](#pipeoptions) can be specified.370371This can be called multiple times to chain a series of subprocesses.
61 unmodified lines
433Sends a [signal](https://nodejs.org/api/os.html#signal-constants) to the subprocess. The default signal is the [`killSignal`](#killsignal) option. `killSignal` defaults to `SIGTERM`, which [terminates](#isterminated) the subprocess.434435This returns `false` when the signal could not be sent, for example when the subprocess has already exited.436430When an error is passed as argument, its message and stack trace are kept in the [subprocess' error](#subprocessresult). The subprocess is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).437When an error is passed as argument, it is set to the subprocess' [`error.cause`](#cause). The subprocess is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).438439[More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)440441### SubprocessResult442443Type: `object`444438Result of a subprocess execution. On success this is a plain object. On failure this is also an `Error` instance.445Result of a subprocess execution.446440The subprocess [fails](#failed) when:441- its [exit code](#exitcode) is not `0`442- it was [terminated](#isterminated) with a [signal](#signal)443- [timing out](#timedout)444- [being canceled](#iscanceled)445- there's not enough memory or there are already too many subprocesses447When the subprocess [fails](#failed), it is rejected with an [`ExecaError`](#execaerror) instead.448449#### command450451Type: `string`
60 unmodified lines
512The output of the subprocess on [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1) and [other file descriptors](#stdio-1).513514Items are `undefined` when their corresponding [`stdio`](#stdio-1) option is set to [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). Items are arrays when their corresponding `stdio` option is a [transform in object mode](docs/transform.md#object-mode).515514#### message515516Type: `string`517518Error message when the subprocess failed to run. In addition to the [underlying error message](#originalMessage), it also contains some information related to why the subprocess errored.519520The subprocess [`stderr`](#stderr), [`stdout`](#stdout) and other [file descriptors' output](#stdio) are appended to the end, separated with newlines and not interleaved.521522#### shortMessage523524Type: `string`525526This is the same as the [`message` property](#message) except it does not include the subprocess [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio).527528#### originalMessage529530Type: `string | undefined`531532Original error message. This is the same as the `message` property excluding the subprocess [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio) and some additional information added by Execa.533534This is `undefined` unless the subprocess exited due to an `error` event or a timeout.535516#### failed517518Type: `boolean`519
46 unmodified lines
566If a signal terminated the subprocess, 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.567568#### pipedFrom569590Type: [`SubprocessResult[]`](#subprocessresult)570Type: [`Array<SubprocessResult | ExecaError>`](#subprocessresult)571572Results of the other subprocesses that were [piped](#pipe-multiple-subprocesses) into this subprocess. This is useful to inspect a series of subprocesses piped with each other.573574This array is initially empty and is populated each time the [`.pipe()`](#pipefile-arguments-options) method resolves.575576### ExecaError577### ExecaSyncError578579Type: `Error`580581Exception thrown when the subprocess [fails](#failed), either:582- its [exit code](#exitcode) is not `0`583- it was [terminated](#isterminated) with a [signal](#signal), including [`.kill()`](#killerror)584- [timing out](#timedout)585- [being canceled](#iscanceled)586- there's not enough memory or there are already too many subprocesses587588This has the same shape as [successful results](#subprocessresult), with the following additional properties.589590#### message591592Type: `string`593594Error message when the subprocess failed to run. In addition to the [underlying error message](#originalMessage), it also contains some information related to why the subprocess errored.595596The subprocess [`stderr`](#stderr), [`stdout`](#stdout) and other [file descriptors' output](#stdio) are appended to the end, separated with newlines and not interleaved.597598#### shortMessage599600Type: `string`601602This is the same as the [`message` property](#message) except it does not include the subprocess [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio).603604#### originalMessage605606Type: `string | undefined`607608Original error message. This is the same as the `message` property excluding the subprocess [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio) and some additional information added by Execa.609610This exists only if the subprocess exited due to an `error` event or a timeout.611612#### cause613614Type: `unknown | undefined`615616Underlying error, if there is one. For example, this is set by [`.kill(error)`](#killerror).617618This is usually an `Error` instance.619620#### code621622Type: `string | undefined`623624Node.js-specific [error code](https://nodejs.org/api/errors.html#errorcode), when available.625626### options627628Type: `object`629
3 unmodified lines
633634Type: `boolean`\635Default: `true`636607Setting this to `false` resolves the promise with the error instead of rejecting it.637Setting this to `false` resolves the promise with the [error](#execaerror) instead of rejecting it.638639#### shell640641Type: `boolean | string | URL`\
460 unmodified lines