Skip to content
Myr

Add `gracefulCancel` option (#1109)

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

authored by ehmicky · committed by GitHub · parent a5a4d69 · Browse files · 57 files+1163 added−95 removed
This commit

State

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

Diff stats

57 files+1163 added−95 removed

  • tests:+556 added−20 removed
  • other:+607 added−75 removed

57 files+1163 added−95 removed

modified:docs/api.md+37 added-4 removed
171 unmodified lines
172Keep the subprocess alive while `getEachMessage()` is waiting.173174[More info.](ipc.md#keeping-the-subprocess-alive)175176### getCancelSignal()177178_Returns_: [`Promise<AbortSignal>`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)179180Retrieves the [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) shared by the [`cancelSignal`](#optionscancelsignal) option.181182This can only be called inside a subprocess. This requires the [`gracefulCancel`](#optionsgracefulcancel) option to be `true`.183184[More info.](termination.md#graceful-termination)185186## Return value187188_TypeScript:_ [`ResultPromise`](typescript.md)\189_Type:_ `Promise<object> | Subprocess`
470 unmodified lines
660Whether the subprocess was canceled using the [`cancelSignal`](#optionscancelsignal) option.661662[More info.](termination.md#canceling)663664### error.isGracefullyCanceled665666_Type:_ `boolean`667668Whether the subprocess was canceled using both the [`cancelSignal`](#optionscancelsignal) and the [`gracefulCancel`](#optionsgracefulcancel) options.669670[More info.](termination.md#graceful-termination)671672### error.isMaxBuffer673674_Type:_ `boolean`675
284 unmodified lines
960Largest amount of data allowed on [`stdout`](#resultstdout), [`stderr`](#resultstderr) and [`stdio`](#resultstdio).961962By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](output.md#stdoutstderr-specific-options).963964When reached, [`error.isMaxBuffer`](#errorismaxbuffer) becomes `true`.965966[More info.](output.md#big-output)967968### options.buffer969
8 unmodified lines
978979### options.ipc980981_Type:_ `boolean`\962_Default:_ `true` if either the [`node`](#optionsnode) option or the [`ipcInput`](#optionsipcinput) is set, `false` otherwise982_Default:_ `true` if the [`node`](#optionsnode), [`ipcInput`](#optionsipcinput) or [`gracefulCancel`](#optionsgracefulcancel) option is set, `false` otherwise983984Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage-sendmessageoptions), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).985986The subprocess must be a Node.js file.
47 unmodified lines
1034_Default:_ `0`10351036If `timeout` is greater than `0`, the subprocess will be [terminated](#optionskillsignal) if it runs for longer than that amount of milliseconds.10371018On timeout, [`result.timedOut`](#errortimedout) becomes `true`.1038On timeout, [`error.timedOut`](#errortimedout) becomes `true`.10391040[More info.](termination.md#timeout)10411042### options.cancelSignal10431044_Type:_ [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)10451026You can abort the subprocess using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).1046When the `cancelSignal` is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), terminate the subprocess using a `SIGTERM` signal.10471028When `AbortController.abort()` is called, [`result.isCanceled`](#erroriscanceled) becomes `true`.1048When aborted, [`error.isCanceled`](#erroriscanceled) becomes `true`.10491050[More info.](termination.md#canceling)10511052### options.gracefulCancel10531054_Type:_ `boolean`\1055_Default:_: `false`10561057When the [`cancelSignal`](#optionscancelsignal) option is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), do not send any [`SIGTERM`](termination.md#canceling). Instead, abort the [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) returned by [`getCancelSignal()`](#getcancelsignal). The subprocess should use it to terminate gracefully.10581059The subprocess must be a [Node.js file](#optionsnode).10601061When aborted, [`error.isGracefullyCanceled`](#errorisgracefullycanceled) becomes `true`.10621063[More info.](termination.md#graceful-termination)10641065### options.forceKillAfterDelay10661067_Type:_ `number | false`\1068_Default:_ `5000`
134 unmodified lines
modified:docs/bash.md+33 added-1 removed
8 unmodified lines
9This page describes the differences between [Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)), Execa, and [zx](https://github.com/google/zx). Execa intends to be more:10- [Simple](#simplicity): minimalistic API, no [globals](#global-variables), no [binary](#main-binary), no builtin CLI utilities.11- [Cross-platform](#shell): [no shell](shell.md) is used, only JavaScript.12- [Secure](#escaping): no shell injection.13- [Featureful](#simplicity): all Execa features are available ([text lines iteration](#iterate-over-output-lines), [advanced piping](#piping-stdout-to-another-command), [simple IPC](#ipc), [passing any input type](#pass-any-input-type), [returning any output type](#return-any-output-type), [transforms](#transforms), [web streams](#web-streams), [convert to Duplex stream](#convert-to-duplex-stream), [cleanup on exit](termination.md#current-process-exit), [forceful termination](termination.md#forceful-termination), and [more](../readme.md#documentation)).13- [Featureful](#simplicity): all Execa features are available ([text lines iteration](#iterate-over-output-lines), [advanced piping](#piping-stdout-to-another-command), [simple IPC](#ipc), [passing any input type](#pass-any-input-type), [returning any output type](#return-any-output-type), [transforms](#transforms), [web streams](#web-streams), [convert to Duplex stream](#convert-to-duplex-stream), [cleanup on exit](termination.md#current-process-exit), [graceful termination](#graceful-termination), [forceful termination](termination.md#forceful-termination), and [more](../readme.md#documentation)).14- [Easy to debug](#debugging): [verbose mode](#verbose-mode-single-command), [detailed errors](#detailed-errors), [messages and stack traces](#cancelation), stateless API.15- [Performant](#performance)1617## Flexibility
1023 unmodified lines
1041```10421043[More info.](termination.md#canceling)10441045### Graceful termination10461047```sh1048# Bash1049trap cleanup SIGTERM1050```10511052```js1053// zx1054// This does not work on Windows1055process.on('SIGTERM', () => {1056 // ...1057});1058```10591060```js1061// Execa - main.js1062const controller = new AbortController();1063await $({1064 cancelSignal: controller.signal,1065 gracefulCancel: true,1066})`node build.js`;1067```10681069```js1070// Execa - build.js1071import {getCancelSignal} from 'execa';10721073const cancelSignal = await getCancelSignal();1074await fetch('https://example.com', {signal: cancelSignal});1075```10761077### Interleaved output10781079```sh1080# Bash prints stdout and stderr interleaved
194 unmodified lines
modified:docs/errors.md+2 added-1 removed
modified:docs/termination.md+97 added-10 removed
6 unmodified lines
7# 🏁 Termination89## Alternatives1011Terminating a subprocess ends it abruptly. This prevents rolling back the subprocess' operations and leaves them incomplete. When possible, graceful exits should be preferred, such as:12- Letting the subprocess end on its own.13- [Performing cleanup](#sigterm) in termination [signal handlers](https://nodejs.org/api/process.html#process_signal_events).14- [Sending a message](ipc.md) to the subprocess so it aborts its operations and cleans up.11Terminating a subprocess ends it abruptly. This prevents rolling back the subprocess' operations and leaves them incomplete.1213Ideally subprocesses should end on their own. If that's not possible, [graceful termination](#graceful-termination) should be preferred.1415## Canceling1618The [`cancelSignal`](api.md#optionscancelsignal) option can be used to cancel a subprocess. When [`abortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), a [`SIGTERM` signal](#default-signal) is sent to the subprocess.17The [`cancelSignal`](api.md#optionscancelsignal) option can be used to cancel a subprocess. When it is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), a [`SIGTERM` signal](#default-signal) is sent to the subprocess.1819```js21import {execa} from 'execa';20import {execaNode} from 'execa';2123const abortController = new AbortController();22const controller = new AbortController();23const cancelSignal = controller.signal;2425setTimeout(() => {26 abortController.abort();26 controller.abort();27}, 5000);2829try {30 await execa({cancelSignal: abortController.signal})`npm run build`;30 await execaNode({cancelSignal})`build.js`;31} catch (error) {32 if (error.isCanceled) {33 console.error('Aborted by cancelSignal.');33 console.error('Canceled by cancelSignal.');34 }3536 throw error;37}38```3940## Graceful termination4142### Share a `cancelSignal`4344When the [`gracefulCancel`](api.md#optionsgracefulcancel) option is `true`, the [`cancelSignal`](api.md#optionscancelsignal) option does not send any [`SIGTERM`](#sigterm). Instead, the subprocess calls [`getCancelSignal()`](api.md#getcancelsignal) to retrieve and handle the [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). This allows the subprocess to properly clean up and abort operations.4546This option only works with Node.js files.4748This is cross-platform. If you do not need to support Windows, [signal handlers](#handling-signals) can also be used.4950```js51// main.js52import {execaNode} from 'execa';5354const controller = new AbortController();55const cancelSignal = controller.signal;5657setTimeout(() => {58 controller.abort();59}, 5000);6061try {62 await execaNode({cancelSignal, gracefulCancel: true})`build.js`;63} catch (error) {64 if (error.isGracefullyCanceled) {65 console.error('Cancelled gracefully.');66 }6768 throw error;69}70```7172```js73// build.js74import {getCancelSignal} from 'execa';7576const cancelSignal = await getCancelSignal();77```7879### Abort operations8081The [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) returned by [`getCancelSignal()`](api.md#getcancelsignal) can be passed to most long-running Node.js methods: [`setTimeout()`](https://nodejs.org/api/timers.html#timerspromisessettimeoutdelay-value-options), [`setInterval()`](https://nodejs.org/api/timers.html#timerspromisessetintervaldelay-value-options), [events](https://nodejs.org/api/events.html#eventsonemitter-eventname-options), [streams](https://nodejs.org/api/stream.html#new-streamreadableoptions), [REPL](https://nodejs.org/api/readline.html#rlquestionquery-options), HTTP/TCP [requests](https://nodejs.org/api/http.html#httprequesturl-options-callback) or [servers](https://nodejs.org/api/net.html#serverlistenoptions-callback), [reading](https://nodejs.org/api/fs.html#fspromisesreadfilepath-options) / [writing](https://nodejs.org/api/fs.html#fspromiseswritefilefile-data-options) / [watching](https://nodejs.org/api/fs.html#fspromiseswatchfilename-options) files, or spawning another subprocess.8283When aborted, those methods throw the `Error` instance which was passed to [`abortController.abort(error)`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort). Since those methods keep the subprocess alive, aborting them makes the subprocess end on its own.8485```js86import {getCancelSignal} from 'execa';87import {watch} from 'node:fs/promises';8889const cancelSignal = await getCancelSignal();9091try {92 for await (const fileChange of watch('./src', {signal: cancelSignal})) {93 onFileChange(fileChange);94 }95} catch (error) {96 if (error.isGracefullyCanceled) {97 console.log(error.cause === cancelSignal.reason); // true98 }99}100```101102### Cleanup logic103104For other kinds of operations, the [`abort`](https://nodejs.org/api/globals.html#event-abort) event should be listened to. Although [`cancelSignal.addEventListener('abort')`](https://nodejs.org/api/events.html#eventtargetaddeventlistenertype-listener-options) can be used, [`events.addAbortListener(cancelSignal)`](https://nodejs.org/api/events.html#eventsaddabortlistenersignal-listener) is preferred since it works even if the `cancelSignal` is already aborted.105106### Graceful exit107108We recommend explicitly [stopping](#abort-operations) each pending operation when the subprocess is aborted. This allows it to end on its own.109110```js111import {getCancelSignal} from 'execa';112import {addAbortListener} from 'node:events';113114const cancelSignal = await getCancelSignal();115addAbortListener(cancelSignal, async () => {116 await cleanup();117 process.exitCode = 1;118});119```120121However, if any operation is still ongoing, the subprocess will keep running. It can be forcefully ended using [`process.exit(exitCode)`](https://nodejs.org/api/process.html#processexitcode) instead of [`process.exitCode`](https://nodejs.org/api/process.html#processexitcode_1).122123If the subprocess is still alive after 5 seconds, it is forcefully terminated with [`SIGKILL`](#sigkill). This can be [configured or disabled](#forceful-termination) using the [`forceKillAfterDelay`](api.md#optionsforcekillafterdelay) option.124125## Timeout126127If the subprocess lasts longer than the [`timeout`](api.md#optionstimeout) option, a [`SIGTERM` signal](#default-signal) is sent to it.128
82 unmodified lines
211```212213Unfortunately this [usually does not work](https://github.com/ehmicky/cross-platform-node-guide/blob/main/docs/6_networking_ipc/signals.md#cross-platform-signals) on Windows. The only signal that is somewhat cross-platform is [`SIGINT`](#sigint): on Windows, its handler is triggered when the user types `CTRL-C` in the terminal. However `subprocess.kill('SIGINT')` is only handled on Unix.214215Execa provides the [`gracefulCancel`](#graceful-termination) option as a cross-platform alternative to signal handlers.216217### Signal name and description218219When a subprocess was terminated by a signal, [`error.isTerminated`](api.md#erroristerminated) is `true`.220
91 unmodified lines
modified:lib/arguments/options.js+5 added-1 removed
3 unmodified lines
4import {npmRunPathEnv} from 'npm-run-path';5import {normalizeForceKillAfterDelay} from '../terminate/kill.js';6import {normalizeKillSignal} from '../terminate/signal.js';7import {validateCancelSignal} from '../terminate/cancel.js';8import {validateGracefulCancel} from '../terminate/graceful.js';9import {validateTimeout} from '../terminate/timeout.js';10import {handleNodeOption} from '../methods/node.js';11import {validateIpcInputOption} from '../ipc/ipc-input.js';12import {validateEncoding, BINARY_ENCODINGS} from './encoding-option.js';
14 unmodified lines
27 validateTimeout(options);28 validateEncoding(options);29 validateIpcInputOption(options);30 validateCancelSignal(options);31 validateGracefulCancel(options);32 options.shell = normalizeFileUrl(options.shell);33 options.env = getEnv(options);34 options.killSignal = normalizeKillSignal(options.killSignal);35 options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);
18 unmodified lines
54 all = false,55 windowsHide = true,56 killSignal = 'SIGTERM',57 forceKillAfterDelay = true,58 gracefulCancel = false,59 ipcInput,57 ipc = ipcInput !== undefined,60 ipc = ipcInput !== undefined || gracefulCancel,61 serialization = 'advanced',62 ...options63}) => ({64 ...options,
7 unmodified lines
72 all,73 windowsHide,74 killSignal,75 forceKillAfterDelay,76 gracefulCancel,77 ipcInput,78 ipc,79 serialization,80});
16 unmodified lines
added:lib/ipc/graceful.js+72 added
modified:lib/ipc/incoming.js+4 added-1 removed
1 unmodified line
2import {scheduler} from 'node:timers/promises';3import {waitForOutgoingMessages} from './outgoing.js';4import {redoAddedReferences} from './reference.js';5import {handleStrictRequest, handleStrictResponse} from './strict.js';6import {handleAbort, abortOnDisconnect} from './graceful.js';78// By default, Node.js buffers `message` events.9// - Buffering happens when there is a `message` event is emitted but there is no handler.10// - As soon as a `message` event handler is set, all buffered `message` events are emitted, emptying the buffer.
12 unmodified lines
23// The default behavior does not allow users to realize they made that mistake.24// To solve those problems, instead of buffering messages, we debounce them.25// The `message` event so it is emitted at most once per macrotask.26export const onMessage = async ({anyProcess, channel, isSubprocess, ipcEmitter}, wrappedMessage) => {26 if (handleStrictResponse(wrappedMessage)) {27 if (handleStrictResponse(wrappedMessage) || handleAbort(wrappedMessage)) {28 return;29 }3031 if (!INCOMING_MESSAGES.has(anyProcess)) {
29 unmodified lines
61};6263// If the `message` event is currently debounced, the `disconnect` event must wait for it64export const onDisconnect = async ({anyProcess, channel, isSubprocess, ipcEmitter, boundOnMessage}) => {65 abortOnDisconnect();6667 const incomingMessages = INCOMING_MESSAGES.get(anyProcess);68 while (incomingMessages?.length > 0) {69 // eslint-disable-next-line no-await-in-loop70 await once(ipcEmitter, 'message:done');
9 unmodified lines
modified:lib/ipc/methods.js+16 added-1 removed
modified:lib/ipc/send.js+30 added-8 removed
11 unmodified lines
12// We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.13// Users would still need to `await subprocess` after the method is done.14// Also, this would prevent `unhandledRejection` event from being emitted, making it silent.15export const sendMessage = ({anyProcess, channel, isSubprocess, ipc}, message, {strict = false} = {}) => {16 const methodName = 'sendMessage';17 validateIpcMethod({17 methodName: 'sendMessage',18 methodName,19 isSubprocess,20 ipc,21 isConnected: anyProcess.connected,22 });2324 return sendMessageAsync({25 anyProcess,26 channel,27 methodName,28 isSubprocess,29 message,30 strict,31 });32};3332const sendMessageAsync = async ({anyProcess, channel, isSubprocess, message, strict}) => {33 const sendMethod = getSendMethod(anyProcess);34const sendMessageAsync = async ({anyProcess, channel, methodName, isSubprocess, message, strict}) => {35 const wrappedMessage = handleSendStrict({36 anyProcess,37 channel,38 isSubprocess,39 message,40 strict,41 });42 const outgoingMessagesState = startSendMessage(anyProcess, wrappedMessage, strict);43 try {44 await sendOneMessage({45 anyProcess,46 methodName,47 isSubprocess,48 wrappedMessage,49 message,50 });51 } catch (error) {52 disconnect(anyProcess);53 throw error;54 } finally {55 endSendMessage(outgoingMessagesState);56 }57};5859// Used internally by `cancelSignal`60export const sendOneMessage = async ({anyProcess, methodName, isSubprocess, wrappedMessage, message}) => {61 const sendMethod = getSendMethod(anyProcess);6263 try {64 await Promise.all([65 waitForStrictResponse(wrappedMessage, anyProcess, isSubprocess),66 sendMethod(wrappedMessage),67 ]);68 } catch (error) {49 disconnect(anyProcess);50 handleEpipeError(error, isSubprocess);51 handleSerializationError(error, isSubprocess, message);69 handleEpipeError({error, methodName, isSubprocess});70 handleSerializationError({71 error,72 methodName,73 isSubprocess,74 message,75 });76 throw error;53 } finally {54 endSendMessage(outgoingMessagesState);77 }78};7980// [sub]process.send() promisified, memoized
11 unmodified lines
modified:lib/ipc/validation.js+29 added-16 removed
5 unmodified lines
67// Better error message when forgetting to set `ipc: true` and using the IPC methods8const validateIpcOption = (methodName, isSubprocess, ipc) => {9 if (!ipc) {10 throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() can only be used if the \`ipc\` option is \`true\`.`);10 throw new Error(`${getMethodName(methodName, isSubprocess)} can only be used if the \`ipc\` option is \`true\`.`);11 }12};1314// Better error message when one process does not send/receive messages once the other process has disconnected.15// This also makes it clear that any buffered messages are lost once either process has disconnected.16// Also when aborting `cancelSignal` after disconnecting the IPC.16const validateConnection = (methodName, isSubprocess, isConnected) => {17export const validateConnection = (methodName, isSubprocess, isConnected) => {18 if (!isConnected) {18 throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);19 throw new Error(`${getMethodName(methodName, isSubprocess)} cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);20 }21};2223// When `getOneMessage()` could not complete due to an early disconnection24export const throwOnEarlyDisconnect = isSubprocess => {24 throw new Error(`${getNamespaceName(isSubprocess)}getOneMessage() could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);25 throw new Error(`${getMethodName('getOneMessage', isSubprocess)} could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);26};2728// When both processes use `sendMessage()` with `strict` at the same time29export const throwOnStrictDeadlockError = isSubprocess => {29 throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed: the ${getOtherProcessName(isSubprocess)} is sending a message too, instead of listening to incoming messages.30 throw new Error(`${getMethodName('sendMessage', isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} is sending a message too, instead of listening to incoming messages.31This can be fixed by both sending a message and listening to incoming messages at the same time:3233const [receivedMessage] = await Promise.all([33 ${getNamespaceName(isSubprocess)}getOneMessage(),34 ${getNamespaceName(isSubprocess)}sendMessage(message, {strict: true}),34 ${getMethodName('getOneMessage', isSubprocess)},35 ${getMethodName('sendMessage', isSubprocess, 'message, {strict: true}')},36]);`);37};3839// When the other process used `strict` but the current process had I/O error calling `sendMessage()` for the response39export const getStrictResponseError = (error, isSubprocess) => new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed when sending an acknowledgment response to the ${getOtherProcessName(isSubprocess)}.`, {cause: error});40export const getStrictResponseError = (error, isSubprocess) => new Error(`${getMethodName('sendMessage', isSubprocess)} failed when sending an acknowledgment response to the ${getOtherProcessName(isSubprocess)}.`, {cause: error});4142// When using `strict` but the other process was not listening for messages43export const throwOnMissingStrict = isSubprocess => {43 throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed: the ${getOtherProcessName(isSubprocess)} is not listening to incoming messages.`);44 throw new Error(`${getMethodName('sendMessage', isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} is not listening to incoming messages.`);45};4647// When using `strict` but the other process disconnected before receiving the message48export const throwOnStrictDisconnect = isSubprocess => {48 throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed: the ${getOtherProcessName(isSubprocess)} exited without listening to incoming messages.`);49 throw new Error(`${getMethodName('sendMessage', isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} exited without listening to incoming messages.`);50};5151const getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';52// When the current process disconnects while the subprocess is listening to `cancelSignal`53export const getAbortDisconnectError = () => new Error(`\`cancelSignal\` aborted: the ${getOtherProcessName(true)} disconnected.`);5453const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';55// When the subprocess uses `cancelSignal` but not the current process56export const throwOnMissingParent = () => {57 throw new Error('`getCancelSignal()` cannot be used without setting the `cancelSignal` subprocess option.');58};5960// EPIPE can happen when sending a message to a subprocess that is closing but has not disconnected yet56export const handleEpipeError = (error, isSubprocess) => {61export const handleEpipeError = ({error, methodName, isSubprocess}) => {62 if (error.code === 'EPIPE') {58 throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() cannot be used: the ${getOtherProcessName(isSubprocess)} is disconnecting.`, {cause: error});63 throw new Error(`${getMethodName(methodName, isSubprocess)} cannot be used: the ${getOtherProcessName(isSubprocess)} is disconnecting.`, {cause: error});64 }65};6667// Better error message when sending messages which cannot be serialized.68// Works with both `serialization: 'advanced'` and `serialization: 'json'`.64export const handleSerializationError = (error, isSubprocess, message) => {69export const handleSerializationError = ({error, methodName, isSubprocess, message}) => {70 if (isSerializationError(error)) {66 throw new Error(`${getNamespaceName(isSubprocess)}sendMessage()'s argument type is invalid: the message cannot be serialized: ${String(message)}.`, {cause: error});71 throw new Error(`${getMethodName(methodName, isSubprocess)}'s argument type is invalid: the message cannot be serialized: ${String(message)}.`, {cause: error});72 }73};7475const isSerializationError = ({code, message}) => SERIALIZATION_ERROR_CODES.has(code)
16 unmodified lines
92 // Message has cycles inside toJSON(), with `serialization: 'json'`93 'call stack size exceeded',94];9596const getMethodName = (methodName, isSubprocess, parameters = '') => methodName === 'cancelSignal'97 ? '`cancelSignal`\'s `controller.abort()`'98 : `${getNamespaceName(isSubprocess)}${methodName}(${parameters})`;99100const getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';101102const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';103104// When any error arises, we disconnect the IPC.105// Otherwise, it is likely that one of the processes will stop sending/receiving messages.106// This would leave the other process hanging.107export const disconnect = anyProcess => {
4 unmodified lines
modified:lib/methods/main-async.js+4 added-3 removed
100 unmodified lines
101 const originalStreams = [...subprocess.stdio];102 pipeOutputAsync(subprocess, fileDescriptors, controller);103 cleanupOnExit(subprocess, options, controller);104105 const context = {timedOut: false, isCanceled: false};105 const context = {};106 const onInternalError = createDeferred();107 subprocess.kill = subprocessKill.bind(undefined, {108 kill: subprocess.kill.bind(subprocess),109 options,
64 unmodified lines
174 ? makeError({175 error: errorInfo.error,176 command,177 escapedCommand,178 timedOut: context.timedOut,179 isCanceled: context.isCanceled,178 timedOut: context.terminationReason === 'timeout',179 isCanceled: context.terminationReason === 'cancel' || context.terminationReason === 'gracefulCancel',180 isGracefullyCanceled: context.terminationReason === 'gracefulCancel',181 isMaxBuffer: errorInfo.error instanceof MaxBufferError,182 isForcefullyTerminated: context.isForcefullyTerminated,183 exitCode,184 signal,
16 unmodified lines
modified:lib/methods/main-sync.js+1 added
153 unmodified lines
154 command,155 escapedCommand,156 timedOut,157 isCanceled: false,158 isGracefullyCanceled: false,159 isMaxBuffer,160 isForcefullyTerminated: false,161 exitCode,162 signal,
7 unmodified lines
modified:lib/resolve/wait-subprocess.js+19 added-1 removed
1import {once} from 'node:events';2import {isStream as isNodeStream} from 'is-stream';3import {throwOnTimeout} from '../terminate/timeout.js';4import {throwOnCancel} from '../terminate/cancel.js';5import {throwOnGracefulCancel} from '../terminate/graceful.js';6import {isStandardStream} from '../utils/standard-stream.js';7import {TRANSFORM_TYPES} from '../stdio/type.js';8import {getBufferedData} from '../io/contents.js';9import {waitForIpcOutput, getBufferedIpcOutput} from '../ipc/buffer-messages.js';
12 unmodified lines
22 maxBuffer,23 lines,24 timeoutDuration: timeout,25 cancelSignal,26 gracefulCancel,27 forceKillAfterDelay,28 stripFinalNewline,29 ipc,30 ipcInput,31 },
59 unmodified lines
91 ]),92 onInternalError,93 throwOnSubprocessError(subprocess, controller),94 ...throwOnTimeout(subprocess, timeout, context, controller),92 ...throwOnCancel(subprocess, cancelSignal, context, controller),95 ...throwOnCancel({96 subprocess,97 cancelSignal,98 gracefulCancel,99 context,100 controller,101 }),102 ...throwOnGracefulCancel({103 subprocess,104 cancelSignal,105 gracefulCancel,106 forceKillAfterDelay,107 context,108 controller,109 }),110 ]);111 } catch (error) {112 context.terminationReason ??= 'other';113 return Promise.all([114 {error},115 exitPromise,116 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise))),
30 unmodified lines
modified:lib/return/message.js+13 added
17 unmodified lines
18 exitCode,19 escapedCommand,20 timedOut,21 isCanceled,22 isGracefullyCanceled,23 isMaxBuffer,24 isForcefullyTerminated,25 forceKillAfterDelay,26 killSignal,
12 unmodified lines
39 signal,40 signalDescription,41 exitCode,42 isCanceled,43 isGracefullyCanceled,44 isForcefullyTerminated,45 forceKillAfterDelay,46 killSignal,47 });
23 unmodified lines
71 signal,72 signalDescription,73 exitCode,74 isCanceled,75 isGracefullyCanceled,76 isForcefullyTerminated,77 forceKillAfterDelay,78 killSignal,79}) => {
2 unmodified lines
82 if (timedOut) {83 return `Command timed out after ${timeout} milliseconds${forcefulSuffix}`;84 }8586 if (isGracefullyCanceled) {87 if (signal === undefined) {88 return `Command was gracefully canceled with exit code ${exitCode}`;89 }9091 return isForcefullyTerminated92 ? `Command was gracefully canceled${forcefulSuffix}`93 : `Command was gracefully canceled with ${signal} (${signalDescription})`;94 }9596 if (isCanceled) {97 return `Command was canceled${forcefulSuffix}`;98 }99
58 unmodified lines
modified:lib/return/result.js+7 added
18 unmodified lines
19 durationMs: getDurationMs(startTime),20 failed: false,21 timedOut: false,22 isCanceled: false,23 isGracefullyCanceled: false,24 isTerminated: false,25 isMaxBuffer: false,26 isForcefullyTerminated: false,27 exitCode: 0,
20 unmodified lines
48 escapedCommand,49 startTime,50 timedOut: false,51 isCanceled: false,52 isGracefullyCanceled: false,53 isMaxBuffer: false,54 isForcefullyTerminated: false,55 stdio: Array.from({length: fileDescriptors.length}),56 ipcOutput: [],
8 unmodified lines
65 escapedCommand,66 startTime,67 timedOut,68 isCanceled,69 isGracefullyCanceled,70 isMaxBuffer,71 isForcefullyTerminated,72 exitCode: rawExitCode,73 signal: rawSignal,
21 unmodified lines
95 exitCode,96 escapedCommand,97 timedOut,98 isCanceled,99 isGracefullyCanceled,100 isMaxBuffer,101 isForcefullyTerminated,102 forceKillAfterDelay,103 killSignal,
8 unmodified lines
112 escapedCommand,113 startTime,114 timedOut,115 isCanceled,116 isGracefullyCanceled,117 isMaxBuffer,118 isForcefullyTerminated,119 exitCode,120 signal,
14 unmodified lines
135 escapedCommand,136 startTime,137 timedOut,138 isCanceled,139 isGracefullyCanceled,140 isMaxBuffer,141 isForcefullyTerminated,142 exitCode,143 signal,
13 unmodified lines
157 durationMs: getDurationMs(startTime),158 failed: true,159 timedOut,160 isCanceled,161 isGracefullyCanceled,162 isTerminated: signal !== undefined,163 isMaxBuffer,164 isForcefullyTerminated,165 exitCode,
21 unmodified lines
modified:lib/terminate/cancel.js+4 added-10 removed
1import {once} from 'node:events';1import {onAbortedSignal} from '../utils/abort-signal.js';23// Validate the `cancelSignal` option4export const validateCancelSignal = ({cancelSignal}) => {5 if (cancelSignal !== undefined && Object.prototype.toString.call(cancelSignal) !== '[object AbortSignal]') {6 throw new Error(`The \`cancelSignal\` option must be an AbortSignal: ${String(cancelSignal)}`);7 }8};910// Terminate the subprocess when aborting the `cancelSignal` option11export const throwOnCancel = (subprocess, cancelSignal, context, controller) => cancelSignal === undefined10// Terminate the subprocess when aborting the `cancelSignal` option and `gracefulSignal` is `false`11export const throwOnCancel = ({subprocess, cancelSignal, gracefulCancel, context, controller}) => cancelSignal === undefined || gracefulCancel12 ? []13 : [terminateOnCancel(subprocess, cancelSignal, context, controller)];1415const terminateOnCancel = async (subprocess, cancelSignal, context, {signal}) => {16 await onAbortedSignal(cancelSignal, signal);17 context.isCanceled = true;17 context.terminationReason ??= 'cancel';18 subprocess.kill();19 throw cancelSignal.reason;20};2122const onAbortedSignal = async (cancelSignal, signal) => {23 if (!cancelSignal.aborted) {24 await once(cancelSignal, 'abort', {signal});25 }26};
added:lib/terminate/graceful.js+71 added
1import {onAbortedSignal} from '../utils/abort-signal.js';2import {sendAbort} from '../ipc/graceful.js';3import {killOnTimeout} from './kill.js';45// Validate the `gracefulCancel` option6export const validateGracefulCancel = ({gracefulCancel, cancelSignal, ipc, serialization}) => {7 if (!gracefulCancel) {8 return;9 }1011 if (cancelSignal === undefined) {12 throw new Error('The `cancelSignal` option must be defined when setting the `gracefulCancel` option.');13 }1415 if (!ipc) {16 throw new Error('The `ipc` option cannot be false when setting the `gracefulCancel` option.');17 }1819 if (serialization === 'json') {20 throw new Error('The `serialization` option cannot be \'json\' when setting the `gracefulCancel` option.');21 }22};2324// Send abort reason to the subprocess when aborting the `cancelSignal` option and `gracefulCancel` is `true`25export const throwOnGracefulCancel = ({26 subprocess,27 cancelSignal,28 gracefulCancel,29 forceKillAfterDelay,30 context,31 controller,32}) => gracefulCancel33 ? [sendOnAbort({34 subprocess,35 cancelSignal,36 forceKillAfterDelay,37 context,38 controller,39 })]40 : [];4142const sendOnAbort = async ({subprocess, cancelSignal, forceKillAfterDelay, context, controller: {signal}}) => {43 await onAbortedSignal(cancelSignal, signal);44 const reason = getReason(cancelSignal);45 await sendAbort(subprocess, reason);46 killOnTimeout({47 kill: subprocess.kill,48 forceKillAfterDelay,49 context,50 controllerSignal: signal,51 });52 context.terminationReason ??= 'gracefulCancel';53 throw cancelSignal.reason;54};5556// The default `reason` is a DOMException, which is not serializable with V857// See https://github.com/nodejs/node/issues/5322558const getReason = ({reason}) => {59 if (!(reason instanceof DOMException)) {60 return reason;61 }6263 const error = new Error(reason.message);64 Object.defineProperty(error, 'stack', {65 value: reason.stack,66 enumerable: false,67 configurable: true,68 writable: true,69 });70 return error;71};
modified:lib/terminate/kill.js-1 removed
89 unmodified lines
90 context.isForcefullyTerminated ??= true;91 }92 } catch {}93};94
modified:lib/terminate/timeout.js+1 added-1 removed
13 unmodified lines
14 : [killAfterTimeout(subprocess, timeout, context, controller)];1516const killAfterTimeout = async (subprocess, timeout, context, {signal}) => {17 await setTimeout(timeout, undefined, {signal});18 context.timedOut = true;18 context.terminationReason ??= 'timeout';19 subprocess.kill();20 throw new DiscardedError();21};
added:lib/utils/abort-signal.js+8 added
1import {once} from 'node:events';23// Combines `util.aborted()` and `events.addAbortListener()`: promise-based and cleaned up with a stop signal4export const onAbortedSignal = async (mainSignal, stopSignal) => {5 if (!mainSignal.aborted) {6 await once(mainSignal, 'abort', {signal: stopSignal});7 }8};
added:test/fixtures/graceful-disconnect.js+12 added
1#!/usr/bin/env node2import process from 'node:process';3import {once} from 'node:events';4import {getCancelSignal, sendMessage} from 'execa';5import {onAbortedSignal} from '../helpers/graceful.js';67const cancelSignal = await getCancelSignal();8await onAbortedSignal(cancelSignal);9await Promise.all([10 once(process, 'disconnect'),11 sendMessage(cancelSignal.reason),12]);
added:test/fixtures/graceful-echo.js+5 added
1#!/usr/bin/env node2import {getCancelSignal, sendMessage, getOneMessage} from 'execa';34await getCancelSignal();5await sendMessage(await getOneMessage());
added:test/fixtures/graceful-listener.js+12 added
1#!/usr/bin/env node2import {getCancelSignal, sendMessage} from 'execa';34const id = setTimeout(() => {}, 1e8);5const cancelSignal = await getCancelSignal();6// eslint-disable-next-line unicorn/prefer-add-event-listener7cancelSignal.onabort = async () => {8 await sendMessage(cancelSignal.reason);9 clearTimeout(id);10};1112await sendMessage('.');
added:test/fixtures/graceful-none.js+4 added
1#!/usr/bin/env node2import {getCancelSignal} from 'execa';34await getCancelSignal();
added:test/fixtures/graceful-print.js+7 added
1#!/usr/bin/env node2import {getCancelSignal} from 'execa';3import {onAbortedSignal} from '../helpers/graceful.js';45const cancelSignal = await getCancelSignal();6await onAbortedSignal(cancelSignal);7console.log(cancelSignal.reason);
added:test/fixtures/graceful-ref.js+6 added
1#!/usr/bin/env node2import {once} from 'node:events';3import {getCancelSignal} from 'execa';45const cancelSignal = await getCancelSignal();6once(cancelSignal, 'abort');
added:test/fixtures/graceful-send-echo.js+9 added
1#!/usr/bin/env node2import {getCancelSignal, getOneMessage, sendMessage} from 'execa';3import {onAbortedSignal} from '../helpers/graceful.js';45const message = await getOneMessage();6const cancelSignal = await getCancelSignal();7await sendMessage(message);8await onAbortedSignal(cancelSignal);9await sendMessage(cancelSignal.reason);
added:test/fixtures/graceful-send-fast.js+5 added
1#!/usr/bin/env node2import {getCancelSignal, sendMessage} from 'execa';34const cancelSignal = await getCancelSignal();5await sendMessage(cancelSignal.aborted);
added:test/fixtures/graceful-send-print.js+8 added
1#!/usr/bin/env node2import {getCancelSignal, sendMessage} from 'execa';3import {onAbortedSignal} from '../helpers/graceful.js';45const cancelSignal = await getCancelSignal();6await sendMessage(cancelSignal.aborted);7await onAbortedSignal(cancelSignal);8console.log(cancelSignal.reason);
added:test/fixtures/graceful-send-string.js+6 added
1#!/usr/bin/env node2import {getCancelSignal, sendMessage} from 'execa';3import {foobarString} from '../helpers/input.js';45await getCancelSignal();6await sendMessage(foobarString);
added:test/fixtures/graceful-send-twice.js+8 added
1#!/usr/bin/env node2import {getCancelSignal, sendMessage} from 'execa';3import {onAbortedSignal} from '../helpers/graceful.js';45const cancelSignal = await getCancelSignal();6await sendMessage(cancelSignal.aborted);7await onAbortedSignal(cancelSignal);8await sendMessage(cancelSignal.reason);
added:test/fixtures/graceful-send.js+7 added
1#!/usr/bin/env node2import {getCancelSignal, sendMessage} from 'execa';3import {onAbortedSignal} from '../helpers/graceful.js';45const cancelSignal = await getCancelSignal();6await onAbortedSignal(cancelSignal);7await sendMessage(cancelSignal.reason);
added:test/fixtures/graceful-twice.js+8 added
1#!/usr/bin/env node2import {getCancelSignal, sendMessage} from 'execa';3import {onAbortedSignal} from '../helpers/graceful.js';45await getCancelSignal();6const cancelSignal = await getCancelSignal();7await onAbortedSignal(cancelSignal);8await sendMessage(cancelSignal.reason);
added:test/fixtures/graceful-wait.js+6 added
1#!/usr/bin/env node2import {getCancelSignal} from 'execa';3import {onAbortedSignal} from '../helpers/graceful.js';45const cancelSignal = await getCancelSignal();6await onAbortedSignal(cancelSignal);
added:test/fixtures/ipc-get.js+4 added
1#!/usr/bin/env node2import {getOneMessage} from '../../index.js';34await getOneMessage();
added:test/fixtures/wait-fail.js+6 added
1#!/usr/bin/env node2import process from 'node:process';3import {setTimeout} from 'node:timers/promises';45await setTimeout(1e3);6process.exitCode = 2;
added:test/helpers/graceful.js+8 added
1import {setTimeout} from 'node:timers/promises';23// Combines `util.aborted()` and `events.addAbortListener()`: promise-based and cleaned up with a stop signal4export const onAbortedSignal = async signal => {5 try {6 await setTimeout(1e8, undefined, {signal});7 } catch {}8};
added:test/ipc/graceful.js+216 added
1import {getEventListeners} from 'node:events';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString} from '../helpers/input.js';78setFixtureDirectory();910test('Graceful cancelSignal can be already aborted', async t => {11 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(execa('graceful-send.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false}));12 t.true(isCanceled);13 t.true(isGracefullyCanceled);14 t.false(isTerminated);15 t.is(exitCode, 0);16 t.deepEqual(ipcOutput, [foobarString]);17});1819test('Graceful cancelSignal can be aborted', async t => {20 const controller = new AbortController();21 const subprocess = execa('graceful-send-twice.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});22 t.false(await subprocess.getOneMessage());23 controller.abort(foobarString);24 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);25 t.true(isCanceled);26 t.true(isGracefullyCanceled);27 t.false(isTerminated);28 t.is(exitCode, 0);29 t.deepEqual(ipcOutput, [false, foobarString]);30});3132test('Graceful cancelSignal can be never aborted', async t => {33 const controller = new AbortController();34 const subprocess = execa('graceful-send-fast.js', {cancelSignal: controller.signal, gracefulCancel: true});35 t.false(await subprocess.getOneMessage());36 await subprocess;37});3839test('Graceful cancelSignal can be already aborted but not used', async t => {40 const subprocess = execa('ipc-send-get.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false});41 t.is(await subprocess.getOneMessage(), foobarString);42 await setTimeout(1e3);43 await subprocess.sendMessage('.');44 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);45 t.true(isCanceled);46 t.true(isGracefullyCanceled);47 t.false(isTerminated);48 t.is(exitCode, 0);49 t.deepEqual(ipcOutput, [foobarString]);50});5152test('Graceful cancelSignal can be aborted but not used', async t => {53 const controller = new AbortController();54 const subprocess = execa('ipc-send-get.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});55 t.is(await subprocess.getOneMessage(), foobarString);56 controller.abort(foobarString);57 await setTimeout(1e3);58 await subprocess.sendMessage(foobarString);59 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);60 t.true(isCanceled);61 t.true(isGracefullyCanceled);62 t.false(isTerminated);63 t.is(exitCode, 0);64 t.deepEqual(ipcOutput, [foobarString]);65});6667test('Graceful cancelSignal can be never aborted nor used', async t => {68 const controller = new AbortController();69 const subprocess = execa('empty.js', {cancelSignal: controller.signal, gracefulCancel: true});70 t.is(getEventListeners(controller.signal, 'abort').length, 1);71 await subprocess;72 t.is(getEventListeners(controller.signal, 'abort').length, 0);73});7475test('Graceful cancelSignal can be aborted twice', async t => {76 const controller = new AbortController();77 const subprocess = execa('graceful-send-twice.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});78 t.false(await subprocess.getOneMessage());79 controller.abort(foobarString);80 controller.abort('.');81 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);82 t.true(isCanceled);83 t.true(isGracefullyCanceled);84 t.false(isTerminated);85 t.is(exitCode, 0);86 t.deepEqual(ipcOutput, [false, foobarString]);87});8889test('Graceful cancelSignal cannot be manually aborted after disconnection', async t => {90 const controller = new AbortController();91 const subprocess = execa('empty.js', {cancelSignal: controller.signal, gracefulCancel: true});92 subprocess.disconnect();93 controller.abort(foobarString);94 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput, originalMessage} = await t.throwsAsync(subprocess);95 t.false(isCanceled);96 t.false(isGracefullyCanceled);97 t.false(isTerminated);98 t.is(exitCode, 0);99 t.deepEqual(ipcOutput, []);100 t.is(originalMessage, '`cancelSignal`\'s `controller.abort()` cannot be used: the subprocess has already exited or disconnected.');101});102103test('Graceful cancelSignal can disconnect after being manually aborted', async t => {104 const controller = new AbortController();105 const subprocess = execa('graceful-disconnect.js', {cancelSignal: controller.signal, gracefulCancel: true});106 controller.abort(foobarString);107 t.is(await subprocess.getOneMessage(), foobarString);108 subprocess.disconnect();109 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);110 t.true(isCanceled);111 t.true(isGracefullyCanceled);112 t.false(isTerminated);113 t.is(exitCode, 0);114 t.deepEqual(ipcOutput, [foobarString]);115});116117test('Graceful cancelSignal is automatically aborted on disconnection', async t => {118 const controller = new AbortController();119 const subprocess = execa('graceful-send-print.js', {cancelSignal: controller.signal, gracefulCancel: true});120 t.false(await subprocess.getOneMessage());121 subprocess.disconnect();122 const {isCanceled, isGracefullyCanceled, ipcOutput, stdout} = await subprocess;123 t.false(isCanceled);124 t.false(isGracefullyCanceled);125 t.deepEqual(ipcOutput, [false]);126 t.true(stdout.includes('Error: `cancelSignal` aborted: the parent process disconnected.'));127});128129test('getCancelSignal() aborts if already disconnected', async t => {130 const controller = new AbortController();131 const subprocess = execa('graceful-print.js', {cancelSignal: controller.signal, gracefulCancel: true});132 subprocess.disconnect();133 const {isCanceled, isGracefullyCanceled, ipcOutput, stdout} = await subprocess;134 t.false(isCanceled);135 t.false(isGracefullyCanceled);136 t.deepEqual(ipcOutput, []);137 t.true(stdout.includes('Error: `cancelSignal` aborted: the parent process disconnected.'));138});139140test('getCancelSignal() fails if no IPC', async t => {141 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput, stderr} = await t.throwsAsync(execa('graceful-none.js'));142 t.false(isCanceled);143 t.false(isGracefullyCanceled);144 t.false(isTerminated);145 t.is(exitCode, 1);146 t.deepEqual(ipcOutput, []);147 t.true(stderr.includes('Error: `getCancelSignal()` cannot be used without setting the `cancelSignal` subprocess option.'));148});149150test.serial('getCancelSignal() hangs if cancelSignal without gracefulCancel', async t => {151 const controller = new AbortController();152 const {timedOut, isCanceled, isGracefullyCanceled, signal, ipcOutput} = await t.throwsAsync(execa('graceful-wait.js', {ipc: true, cancelSignal: controller.signal, timeout: 1e3}));153 t.true(timedOut);154 t.false(isCanceled);155 t.false(isGracefullyCanceled);156 t.is(signal, 'SIGTERM');157 t.deepEqual(ipcOutput, []);158});159160test('Subprocess cancelSignal does not keep subprocess alive', async t => {161 const controller = new AbortController();162 const {ipcOutput} = await execa('graceful-ref.js', {cancelSignal: controller.signal, gracefulCancel: true});163 t.deepEqual(ipcOutput, []);164});165166test('Subprocess can send a message right away', async t => {167 const controller = new AbortController();168 const {ipcOutput} = await execa('graceful-send-string.js', {cancelSignal: controller.signal, gracefulCancel: true});169 t.deepEqual(ipcOutput, [foobarString]);170});171172test('Subprocess can receive a message right away', async t => {173 const controller = new AbortController();174 const {ipcOutput} = await execa('graceful-echo.js', {cancelSignal: controller.signal, gracefulCancel: true, ipcInput: foobarString});175 t.deepEqual(ipcOutput, [foobarString]);176});177178test('getCancelSignal() can be called twice', async t => {179 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(execa('graceful-twice.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false}));180 t.true(isCanceled);181 t.true(isGracefullyCanceled);182 t.false(isTerminated);183 t.is(exitCode, 0);184 t.deepEqual(ipcOutput, [foobarString]);185});186187test('Graceful cancelSignal can use cancelSignal.onabort', async t => {188 const controller = new AbortController();189 const subprocess = execa('graceful-listener.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});190 t.is(await subprocess.getOneMessage(), '.');191 controller.abort(foobarString);192 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);193 t.true(isCanceled);194 t.true(isGracefullyCanceled);195 t.false(isTerminated);196 t.is(exitCode, 0);197 t.deepEqual(ipcOutput, ['.', foobarString]);198});199200test('Graceful cancelSignal abort reason cannot be directly received', async t => {201 const subprocess = execa('graceful-send-echo.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false});202 await setTimeout(0);203 await subprocess.sendMessage('.');204 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);205 t.true(isCanceled);206 t.true(isGracefullyCanceled);207 t.false(isTerminated);208 t.is(exitCode, 0);209 t.deepEqual(ipcOutput, ['.', foobarString]);210});211212test('error.isGracefullyCanceled is always false with execaSync()', t => {213 const {isCanceled, isGracefullyCanceled} = execaSync('empty.js');214 t.false(isCanceled);215 t.false(isGracefullyCanceled);216});
modified:test/return/result.js+2 added
16 unmodified lines
17 'durationMs',18 'failed',19 'timedOut',20 'isCanceled',21 'isGracefullyCanceled',22 'isTerminated',23 'isMaxBuffer',24 'isForcefullyTerminated',25 'exitCode',
22 unmodified lines
48 'durationMs',49 'failed',50 'timedOut',51 'isCanceled',52 'isGracefullyCanceled',53 'isTerminated',54 'isMaxBuffer',55 'isForcefullyTerminated',56 'exitCode',
91 unmodified lines
modified:test/terminate/cancel.js+35 added-17 removed
16 unmodified lines
17test('cancelSignal option cannot be null', testValidCancelSignal, null);18test('cancelSignal option cannot be a symbol', testValidCancelSignal, Symbol('test'));1920test('result.isCanceled is false when abort isn\'t called (success)', async t => {21 const {isCanceled} = await execa('noop.js');21 const {isCanceled, isGracefullyCanceled} = await execa('noop.js');22 t.false(isCanceled);23 t.false(isGracefullyCanceled);24});2526test('result.isCanceled is false when abort isn\'t called (failure)', async t => {26 const {isCanceled} = await t.throwsAsync(execa('fail.js'));27 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(execa('fail.js'));28 t.false(isCanceled);29 t.false(isGracefullyCanceled);30});3132test('result.isCanceled is false when abort isn\'t called in sync mode (success)', t => {31 const {isCanceled} = execaSync('noop.js');33 const {isCanceled, isGracefullyCanceled} = execaSync('noop.js');34 t.false(isCanceled);35 t.false(isGracefullyCanceled);36});3738test('result.isCanceled is false when abort isn\'t called in sync mode (failure)', t => {36 const {isCanceled} = t.throws(() => {39 const {isCanceled, isGracefullyCanceled} = t.throws(() => {40 execaSync('fail.js');41 });42 t.false(isCanceled);43 t.false(isGracefullyCanceled);44});4542test('error.isCanceled is true when abort is used', async t => {46const testCancelSuccess = async (t, options) => {47 const abortController = new AbortController();44 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});48 const subprocess = execa('noop.js', {cancelSignal: abortController.signal, ...options});49 abortController.abort();46 const {isCanceled} = await t.throwsAsync(subprocess);50 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);51 t.true(isCanceled);52 t.false(isGracefullyCanceled);48});53};5455test('error.isCanceled is true when abort is used', testCancelSuccess, {});56test('gracefulCancel can be false with cancelSignal', testCancelSuccess, {gracefulCancel: false});57test('ipc can be false with cancelSignal', testCancelSuccess, {ipc: false});58test('serialization can be "json" with cancelSignal', testCancelSuccess, {ipc: true, serialization: 'json'});5960test('error.isCanceled is false when kill method is used', async t => {61 const abortController = new AbortController();62 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});63 subprocess.kill();54 const {isCanceled} = await t.throwsAsync(subprocess);64 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);65 t.false(isCanceled);66 t.false(isGracefullyCanceled);67});6869test('calling abort is considered a signal termination', async t => {70 const abortController = new AbortController();71 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});72 await once(subprocess, 'spawn');73 abortController.abort();63 const {isCanceled, isTerminated, signal} = await t.throwsAsync(subprocess);74 const {isCanceled, isGracefullyCanceled, isTerminated, signal} = await t.throwsAsync(subprocess);75 t.true(isCanceled);76 t.false(isGracefullyCanceled);77 t.true(isTerminated);78 t.is(signal, 'SIGTERM');79});8081test('cancelSignal can already be aborted', async t => {82 const cancelSignal = AbortSignal.abort();71 const {isCanceled, isTerminated, signal} = await t.throwsAsync(execa('forever.js', {cancelSignal}));83 const {isCanceled, isGracefullyCanceled, isTerminated, signal} = await t.throwsAsync(execa('forever.js', {cancelSignal}));84 t.true(isCanceled);85 t.false(isGracefullyCanceled);86 t.true(isTerminated);87 t.is(signal, 'SIGTERM');88 t.deepEqual(getEventListeners(cancelSignal, 'abort'), []);89});
5 unmodified lines
95 subprocess.once('error', errorArgument => {96 error = errorArgument;97 });98 abortController.abort();86 const {isCanceled} = await t.throwsAsync(subprocess);99 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);100 t.true(isCanceled);101 t.false(isGracefullyCanceled);102 t.is(error, undefined);103});104105test('calling abort cleans up listeners on cancelSignal, called', async t => {106 const abortController = new AbortController();107 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});108 t.is(getEventListeners(abortController.signal, 'abort').length, 1);109 abortController.abort();96 const {isCanceled} = await t.throwsAsync(subprocess);110 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);111 t.true(isCanceled);112 t.false(isGracefullyCanceled);113 t.is(getEventListeners(abortController.signal, 'abort').length, 0);114});115116test('calling abort cleans up listeners on cancelSignal, not called', async t => {
7 unmodified lines
124test('calling abort cleans up listeners on cancelSignal, already aborted', async t => {125 const cancelSignal = AbortSignal.abort();126 const subprocess = execa('noop.js', {cancelSignal});127 t.is(getEventListeners(cancelSignal, 'abort').length, 0);113 const {isCanceled} = await t.throwsAsync(subprocess);128 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);129 t.true(isCanceled);130 t.false(isGracefullyCanceled);131 t.is(getEventListeners(cancelSignal, 'abort').length, 0);132});133134test('calling abort throws an error with message "Command was canceled"', async t => {
44 unmodified lines
179 const abortController = new AbortController();180 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});181 abortController.abort();182 abortController.abort();167 const {isCanceled} = await t.throwsAsync(subprocess);183 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);184 t.true(isCanceled);185 t.false(isGracefullyCanceled);186});187188test('calling abort on a successfully completed subprocess does not make result.isCanceled true', async t => {189 const abortController = new AbortController();190 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});174 const result = await subprocess;191 const {isCanceled, isGracefullyCanceled} = await subprocess;192 abortController.abort();176 t.false(result.isCanceled);193 t.false(isCanceled);194 t.false(isGracefullyCanceled);195});196197test('Throws when using the former "signal" option name', t => {198 const abortController = new AbortController();
11 unmodified lines
added:test/terminate/graceful.js+178 added
1import {setTimeout} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {foobarString} from '../helpers/input.js';6import {mockSendIoError} from '../helpers/ipc.js';78setFixtureDirectory();910test('cancelSignal cannot be undefined with gracefulCancel', t => {11 t.throws(() => {12 execa('empty.js', {gracefulCancel: true});13 }, {message: /The `cancelSignal` option must be defined/});14});1516test('ipc cannot be false with gracefulCancel', t => {17 t.throws(() => {18 execa('empty.js', {gracefulCancel: true, cancelSignal: AbortSignal.abort(), ipc: false});19 }, {message: /The `ipc` option cannot be false/});20});2122test('serialization cannot be "json" with gracefulCancel', t => {23 t.throws(() => {24 execa('empty.js', {gracefulCancel: true, cancelSignal: AbortSignal.abort(), serialization: 'json'});25 }, {message: /The `serialization` option cannot be 'json'/});26});2728test('Current process can send a message right away', async t => {29 const controller = new AbortController();30 const subprocess = execa('ipc-echo.js', {cancelSignal: controller.signal, gracefulCancel: true});31 await subprocess.sendMessage(foobarString);32 const {ipcOutput} = await subprocess;33 t.deepEqual(ipcOutput, [foobarString]);34});3536test('Current process can receive a message right away', async t => {37 const controller = new AbortController();38 const subprocess = execa('ipc-send.js', {cancelSignal: controller.signal, gracefulCancel: true});39 t.is(await subprocess.getOneMessage(), foobarString);40 const {ipcOutput} = await subprocess;41 t.deepEqual(ipcOutput, [foobarString]);42});4344test('Does not disconnect during I/O errors when sending the abort reason', async t => {45 const controller = new AbortController();46 const subprocess = execa('ipc-echo.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});47 const error = mockSendIoError(subprocess);48 controller.abort(foobarString);49 await setTimeout(0);50 t.true(subprocess.connected);51 subprocess.kill();52 const {isCanceled, isGracefullyCanceled, signal, ipcOutput, cause} = await t.throwsAsync(subprocess);53 t.false(isCanceled);54 t.false(isGracefullyCanceled);55 t.is(signal, 'SIGTERM');56 t.deepEqual(ipcOutput, []);57 t.is(cause, error);58});5960class AbortError extends Error {61 name = 'AbortError';62}6364test('Abort reason is sent to the subprocess', async t => {65 const controller = new AbortController();66 const subprocess = execa('graceful-send.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});67 const error = new AbortError(foobarString);68 controller.abort(error);69 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await t.throwsAsync(subprocess);70 t.true(isCanceled);71 t.true(isGracefullyCanceled);72 t.false(isTerminated);73 t.is(exitCode, 0);74 t.is(cause, error);75 t.is(ipcOutput[0].message, error.message);76 t.is(ipcOutput[0].stack, error.stack);77 t.is(ipcOutput[0].name, 'Error');78});7980test('Abort default reason is sent to the subprocess', async t => {81 const controller = new AbortController();82 const subprocess = execa('graceful-send.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});83 controller.abort();84 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await t.throwsAsync(subprocess);85 t.true(isCanceled);86 t.true(isGracefullyCanceled);87 t.false(isTerminated);88 t.is(exitCode, 0);89 const {reason} = controller.signal;90 t.is(cause.stack, reason.stack);91 t.is(ipcOutput[0].message, reason.message);92 t.is(ipcOutput[0].stack, reason.stack);93});9495test('Fail when sending non-serializable abort reason', async t => {96 const controller = new AbortController();97 const subprocess = execa('ipc-echo.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});98 controller.abort(() => {});99 await setTimeout(0);100 t.true(subprocess.connected);101 await subprocess.sendMessage(foobarString);102 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await t.throwsAsync(subprocess);103 t.false(isCanceled);104 t.false(isGracefullyCanceled);105 t.false(isTerminated);106 t.is(exitCode, 0);107 t.deepEqual(ipcOutput, [foobarString]);108 t.is(cause.message, '`cancelSignal`\'s `controller.abort()`\'s argument type is invalid: the message cannot be serialized: () => {}.');109 t.is(cause.cause.message, '() => {} could not be cloned.');110});111112test('timeout does not use graceful cancelSignal', async t => {113 const controller = new AbortController();114 const {timedOut, isCanceled, isGracefullyCanceled, isTerminated, signal, exitCode, shortMessage, ipcOutput} = await t.throwsAsync(execa('graceful-send.js', {cancelSignal: controller.signal, gracefulCancel: true, timeout: 1}));115 t.true(timedOut);116 t.false(isCanceled);117 t.false(isGracefullyCanceled);118 t.true(isTerminated);119 t.is(signal, 'SIGTERM');120 t.is(exitCode, undefined);121 t.is(shortMessage, 'Command timed out after 1 milliseconds: graceful-send.js');122 t.deepEqual(ipcOutput, []);123});124125test('error on graceful cancelSignal on non-0 exit code', async t => {126 const {isCanceled, isGracefullyCanceled, isTerminated, isForcefullyTerminated, exitCode, shortMessage} = await t.throwsAsync(execa('wait-fail.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: false}));127 t.true(isCanceled);128 t.true(isGracefullyCanceled);129 t.false(isTerminated);130 t.false(isForcefullyTerminated);131 t.is(exitCode, 2);132 t.is(shortMessage, 'Command was gracefully canceled with exit code 2: wait-fail.js');133});134135test('error on graceful cancelSignal on forceful termination', async t => {136 const {isCanceled, isGracefullyCanceled, isTerminated, signal, isForcefullyTerminated, exitCode, shortMessage} = await t.throwsAsync(execa('forever.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: 1}));137 t.true(isCanceled);138 t.true(isGracefullyCanceled);139 t.true(isTerminated);140 t.is(signal, 'SIGKILL');141 t.true(isForcefullyTerminated);142 t.is(exitCode, undefined);143 t.is(shortMessage, 'Command was gracefully canceled and was forcefully terminated after 1 milliseconds: forever.js');144});145146test('error on graceful cancelSignal on non-forceful termination', async t => {147 const subprocess = execa('ipc-send-get.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: 1e6});148 t.is(await subprocess.getOneMessage(), foobarString);149 subprocess.kill();150 const {isCanceled, isGracefullyCanceled, isTerminated, signal, isForcefullyTerminated, exitCode, shortMessage} = await t.throwsAsync(subprocess);151 t.true(isCanceled);152 t.true(isGracefullyCanceled);153 t.true(isTerminated);154 t.is(signal, 'SIGTERM');155 t.false(isForcefullyTerminated);156 t.is(exitCode, undefined);157 t.is(shortMessage, 'Command was gracefully canceled with SIGTERM (Termination): ipc-send-get.js');158});159160test('`forceKillAfterDelay: false` with the "cancelSignal" option when graceful', async t => {161 const subprocess = execa('forever.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: false});162 await setTimeout(6e3);163 subprocess.kill('SIGKILL');164 const {isCanceled, isGracefullyCanceled, isTerminated, signal, isForcefullyTerminated, exitCode, shortMessage} = await t.throwsAsync(subprocess);165 t.true(isCanceled);166 t.true(isGracefullyCanceled);167 t.true(isTerminated);168 t.is(signal, 'SIGKILL');169 t.false(isForcefullyTerminated);170 t.is(exitCode, undefined);171 t.is(shortMessage, 'Command was gracefully canceled with SIGKILL (Forced termination): forever.js');172});173174test('subprocess.getCancelSignal() is not defined', async t => {175 const subprocess = execa('empty.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true});176 t.is(subprocess.getCancelSignal, undefined);177 await t.throwsAsync(subprocess);178});
modified:test/terminate/kill-force.js+2 added-1 removed
111 unmodified lines
112 const abortController = new AbortController();113 const subprocess = spawnNoKillableSimple({cancelSignal: abortController.signal});114 await once(subprocess, 'spawn');115 abortController.abort('');116 const {isTerminated, signal, isCanceled, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);116 const {isTerminated, signal, isCanceled, isGracefullyCanceled, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);117 t.true(isTerminated);118 t.is(signal, 'SIGKILL');119 t.true(isCanceled);120 t.false(isGracefullyCanceled);121 t.true(isForcefullyTerminated);122 t.is(shortMessage, 'Command was canceled and was forcefully terminated after 1 milliseconds: forever.js');123 });124
94 unmodified lines
modified:test/terminate/timeout.js+2 added-2 removed
64 unmodified lines
65 const {timedOut} = execaSync('noop.js');66 t.false(timedOut);67});6869test('timedOut is true if the timeout happened after a different error occurred', async t => {69test('timedOut is false if the timeout happened after a different error occurred', async t => {70 const subprocess = execa('forever.js', {timeout: 1e3});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);75 t.false(error.timedOut);76});
modified:test-d/arguments/options.test-d.ts+7 added-2 removed
213 unmodified lines
214expectError(execaSync('unicorns', {detached: true}));215expectError(await execa('unicorns', {detached: 'true'}));216expectError(execaSync('unicorns', {detached: 'true'}));217218await execa('unicorns', {cancelSignal: new AbortController().signal});219expectError(execaSync('unicorns', {cancelSignal: new AbortController().signal}));218await execa('unicorns', {cancelSignal: AbortSignal.abort()});219expectError(execaSync('unicorns', {cancelSignal: AbortSignal.abort()}));220expectError(await execa('unicorns', {cancelSignal: false}));221expectError(execaSync('unicorns', {cancelSignal: false}));222223await execa('unicorns', {gracefulCancel: true, cancelSignal: AbortSignal.abort()});224expectError(execaSync('unicorns', {gracefulCancel: true, cancelSignal: AbortSignal.abort()}));225expectError(await execa('unicorns', {gracefulCancel: 'true', cancelSignal: AbortSignal.abort()}));226expectError(execaSync('unicorns', {gracefulCancel: 'true', cancelSignal: AbortSignal.abort()}));
modified:test-d/ipc/get-each.test-d.ts+5 added
23 unmodified lines
24expectError(getEachMessage(''));2526execa('test', {ipcInput: ''}).getEachMessage();27execa('test', {ipcInput: '' as Message}).getEachMessage();28execa('test', {gracefulCancel: true, cancelSignal: AbortSignal.abort()}).getEachMessage();29execa('test', {} as Options).getEachMessage?.();30execa('test', {ipc: true as boolean}).getEachMessage?.();31execa('test', {ipcInput: '' as '' | undefined}).getEachMessage?.();32execa('test', {gracefulCancel: true as boolean | undefined, cancelSignal: AbortSignal.abort()}).getEachMessage?.();3334expectType<undefined>(execa('test').getEachMessage);35expectType<undefined>(execa('test', {}).getEachMessage);36expectType<undefined>(execa('test', {ipc: false}).getEachMessage);37expectType<undefined>(execa('test', {ipcInput: undefined}).getEachMessage);38expectType<undefined>(execa('test', {gracefulCancel: undefined}).getEachMessage);39expectType<undefined>(execa('test', {gracefulCancel: false}).getEachMessage);40expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).getEachMessage);41expectType<undefined>(execa('test', {ipc: false, gracefulCancel: true, cancelSignal: AbortSignal.abort()}).getEachMessage);4243subprocess.getEachMessage({reference: true} as const);44getEachMessage({reference: true} as const);45expectError(subprocess.getEachMessage({reference: 'true'} as const));
1 unmodified line
modified:test-d/ipc/get-one.test-d.ts+5 added
17 unmodified lines
18expectError(await getOneMessage({}, ''));1920await execa('test', {ipcInput: ''}).getOneMessage();21await execa('test', {ipcInput: '' as Message}).getOneMessage();22await execa('test', {gracefulCancel: true, cancelSignal: AbortSignal.abort()}).getOneMessage();23await execa('test', {} as Options).getOneMessage?.();24await execa('test', {ipc: true as boolean}).getOneMessage?.();25await execa('test', {ipcInput: '' as '' | undefined}).getOneMessage?.();26await execa('test', {gracefulCancel: true as boolean | undefined, cancelSignal: AbortSignal.abort()}).getOneMessage?.();2728expectType<undefined>(execa('test').getOneMessage);29expectType<undefined>(execa('test', {}).getOneMessage);30expectType<undefined>(execa('test', {ipc: false}).getOneMessage);31expectType<undefined>(execa('test', {ipcInput: undefined}).getOneMessage);32expectType<undefined>(execa('test', {gracefulCancel: undefined}).getOneMessage);33expectType<undefined>(execa('test', {gracefulCancel: false}).getOneMessage);34expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).getOneMessage);35expectType<undefined>(execa('test', {ipc: false, gracefulCancel: true, cancelSignal: AbortSignal.abort()}).getOneMessage);3637await subprocess.getOneMessage({filter: undefined} as const);38await subprocess.getOneMessage({filter: (message: Message<'advanced'>) => true} as const);39await jsonSubprocess.getOneMessage({filter: (message: Message<'json'>) => true} as const);
29 unmodified lines
added:test-d/ipc/graceful.ts+8 added
1import {expectType, expectError} from 'tsd';2import {getCancelSignal, execa} from '../../index.js';34expectType<Promise<AbortSignal>>(getCancelSignal());56expectError(await getCancelSignal(''));78expectError(execa('test').getCancelSignal);
modified:test-d/ipc/send.test-d.ts+5 added
19 unmodified lines
20expectError(await sendMessage(Symbol('test')));2122await execa('test', {ipcInput: ''}).sendMessage('');23await execa('test', {ipcInput: '' as Message}).sendMessage('');24await execa('test', {gracefulCancel: true, cancelSignal: AbortSignal.abort()}).sendMessage('');25await execa('test', {} as Options).sendMessage?.('');26await execa('test', {ipc: true as boolean}).sendMessage?.('');27await execa('test', {ipcInput: '' as '' | undefined}).sendMessage?.('');28await execa('test', {gracefulCancel: true as boolean | undefined, cancelSignal: AbortSignal.abort()}).sendMessage?.('');2930expectType<undefined>(execa('test').sendMessage);31expectType<undefined>(execa('test', {}).sendMessage);32expectType<undefined>(execa('test', {ipc: false}).sendMessage);33expectType<undefined>(execa('test', {ipcInput: undefined}).sendMessage);34expectType<undefined>(execa('test', {gracefulCancel: undefined}).sendMessage);35expectType<undefined>(execa('test', {gracefulCancel: false}).sendMessage);36expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).sendMessage);37expectType<undefined>(execa('test', {ipc: false, gracefulCancel: true, cancelSignal: AbortSignal.abort()}).sendMessage);3839await subprocess.sendMessage('', {} as const);40await sendMessage('', {} as const);41await subprocess.sendMessage('', {strict: true} as const);
9 unmodified lines
modified:test-d/return/result-ipc.ts+15 added
26 unmodified lines
2728const genericInputResult = await execa('unicorns', {ipcInput: '' as Message});29expectType<Array<Message<'advanced'>>>(genericInputResult.ipcOutput);3031const gracefulResult = await execa('unicorns', {gracefulCancel: true, cancelSignal: AbortSignal.abort()});32expectType<Array<Message<'advanced'>>>(gracefulResult.ipcOutput);3334const genericResult = await execa('unicorns', {} as Options);35expectType<Message[] | []>(genericResult.ipcOutput);3637const genericIpc = await execa('unicorns', {ipc: true as boolean});
1 unmodified line
3940const maybeInputResult = await execa('unicorns', {ipcInput: '' as '' | undefined});41expectType<Array<Message<'advanced'>> | []>(maybeInputResult.ipcOutput);4243const maybeGracefulResult = await execa('unicorns', {gracefulCancel: true as boolean | undefined, cancelSignal: AbortSignal.abort()});44expectType<Array<Message<'advanced'>> | []>(maybeGracefulResult.ipcOutput);4546const falseIpcResult = await execa('unicorns', {ipc: false});47expectType<[]>(falseIpcResult.ipcOutput);4849const noIpcResult = await execa('unicorns');
7 unmodified lines
5758const inputNoIpcResult = await execa('unicorns', {ipc: false, ipcInput: ''});59expectType<[]>(inputNoIpcResult.ipcOutput);6061const undefinedGracefulResult = await execa('unicorns', {gracefulCancel: undefined});62expectType<[]>(undefinedGracefulResult.ipcOutput);6364const falseGracefulResult = await execa('unicorns', {gracefulCancel: false});65expectType<[]>(falseGracefulResult.ipcOutput);6667const gracefulNoIpcResult = await execa('unicorns', {ipc: false, gracefulCancel: true, cancelSignal: AbortSignal.abort()});68expectType<[]>(gracefulNoIpcResult.ipcOutput);6970const noBufferResult = await execa('unicorns', {ipc: true, buffer: false});71expectType<[]>(noBufferResult.ipcOutput);7273const noBufferFdResult = await execa('unicorns', {ipc: true, buffer: {ipc: false}});
21 unmodified lines
modified:test-d/return/result-main.test-d.ts+4 added
25 unmodified lines
26expectType<number | undefined>(unicornsResult.exitCode);27expectType<boolean>(unicornsResult.failed);28expectType<boolean>(unicornsResult.timedOut);29expectType<boolean>(unicornsResult.isCanceled);30expectType<boolean>(unicornsResult.isGracefullyCanceled);31expectType<boolean>(unicornsResult.isTerminated);32expectType<boolean>(unicornsResult.isMaxBuffer);33expectType<boolean>(unicornsResult.isForcefullyTerminated);34expectType<keyof SignalConstants | undefined>(unicornsResult.signal);
9 unmodified lines
44expectType<number | undefined>(unicornsResultSync.exitCode);45expectType<boolean>(unicornsResultSync.failed);46expectType<boolean>(unicornsResultSync.timedOut);47expectType<boolean>(unicornsResultSync.isCanceled);48expectType<boolean>(unicornsResultSync.isGracefullyCanceled);49expectType<boolean>(unicornsResultSync.isTerminated);50expectType<boolean>(unicornsResultSync.isMaxBuffer);51expectType<boolean>(unicornsResultSync.isForcefullyTerminated);52expectType<keyof SignalConstants | undefined>(unicornsResultSync.signal);
10 unmodified lines
63 expectType<number | undefined>(error.exitCode);64 expectType<boolean>(error.failed);65 expectType<boolean>(error.timedOut);66 expectType<boolean>(error.isCanceled);67 expectType<boolean>(error.isGracefullyCanceled);68 expectType<boolean>(error.isTerminated);69 expectType<boolean>(error.isMaxBuffer);70 expectType<boolean>(error.isForcefullyTerminated);71 expectType<keyof SignalConstants | undefined>(error.signal);
15 unmodified lines
87 expectType<number | undefined>(errorSync.exitCode);88 expectType<boolean>(errorSync.failed);89 expectType<boolean>(errorSync.timedOut);90 expectType<boolean>(errorSync.isCanceled);91 expectType<boolean>(errorSync.isGracefullyCanceled);92 expectType<boolean>(errorSync.isTerminated);93 expectType<boolean>(errorSync.isMaxBuffer);94 expectType<boolean>(errorSync.isForcefullyTerminated);95 expectType<keyof SignalConstants | undefined>(errorSync.signal);
9 unmodified lines
modified:types/arguments/options.d.ts+23 added-9 removed
183 unmodified lines
184 Largest amount of data allowed on `stdout`, `stderr` and `stdio`.185186 By default, this applies to both `stdout` and `stderr`, but different values can also be passed.187188 When reached, `error.isMaxBuffer` becomes `true`.189190 @default 100_000_000191 */192 readonly maxBuffer?: FdGenericOption<number>;193
10 unmodified lines
204 Enables exchanging messages with the subprocess using `subprocess.sendMessage(message)`, `subprocess.getOneMessage()` and `subprocess.getEachMessage()`.205206 The subprocess must be a Node.js file.207206 @default `true` if either the `node` option or the `ipcInput` option is set, `false` otherwise208 @default `true` if the `node`, `ipcInput` or `gracefulCancel` option is set, `false` otherwise209 */210 readonly ipc?: Unless<IsSync, boolean>;211212 /**
30 unmodified lines
243244 /**245 If `timeout` is greater than `0`, the subprocess will be terminated if it runs for longer than that amount of milliseconds.246245 On timeout, `result.timedOut` becomes `true`.247 On timeout, `error.timedOut` becomes `true`.248249 @default 0250 */251 readonly timeout?: number;252253 /**252 You can abort the subprocess using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).254 When the `cancelSignal` is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), terminate the subprocess using a `SIGTERM` signal.255254 When `AbortController.abort()` is called, `result.isCanceled` becomes `true`.256 When aborted, `error.isCanceled` becomes `true`.257258 @example259 ```258 import {execa} from 'execa';260 import {execaNode} from 'execa';261260 const abortController = new AbortController();262 const controller = new AbortController();263 const cancelSignal = controller.signal;264265 setTimeout(() => {263 abortController.abort();266 controller.abort();267 }, 5000);268269 try {267 await execa({cancelSignal: abortController.signal})`npm run build`;270 await execaNode({cancelSignal})`build.js`;271 } catch (error) {272 if (error.isCanceled) {270 console.error('Aborted by cancelSignal.');273 console.error('Canceled by cancelSignal.');274 }275276 throw error;277 }
1 unmodified line
279 */280 readonly cancelSignal?: Unless<IsSync, AbortSignal>;281282 /**283 When the `cancelSignal` option is [aborted](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort), do not send any `SIGTERM`. Instead, abort the [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) returned by `getCancelSignal()`. The subprocess should use it to terminate gracefully.284285 The subprocess must be a Node.js file.286287 When aborted, `error.isGracefullyCanceled` becomes `true`.288289 @default false290 */291 readonly gracefulCancel?: Unless<IsSync, boolean>;292293 /**294 If the subprocess is terminated but does not exit, forcefully exit it by sending [`SIGKILL`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGKILL).295296 When this happens, `error.isForcefullyTerminated` becomes `true`.297
101 unmodified lines
modified:types/methods/main-async.d.ts+29 added
106 unmodified lines
107108@example <caption>Simple input</caption>109110```111const getInputString = () => { /* ... *\/ };112const {stdout} = await execa({input: getInputString()})`sort`;113console.log(stdout);114```115
120 unmodified lines
236```237// build.js238import {sendMessage} from 'execa';239240const runBuild = () => { /* ... *\/ };241242await sendMessage({kind: 'start', timestamp: new Date()});243await runBuild();244await sendMessage({kind: 'stop', timestamp: new Date()});245```246247@example <caption>Graceful termination</caption>248249```250// main.js251import {execaNode} from 'execa';252253const controller = new AbortController();254setTimeout(() => {255 controller.abort();256}, 5000);257258await execaNode({259 cancelSignal: controller.signal,260 gracefulCancel: true,261})`build.js`;262```263264```265// build.js266import {getCancelSignal} from 'execa';267268const cancelSignal = await getCancelSignal();269const url = 'https://example.com/build/info';270const response = await fetch(url, {signal: cancelSignal});271```272273@example <caption>Detailed error</caption>274275```276import {execa, ExecaError} from 'execa';
63 unmodified lines
modified:types/return/result.d.ts+5 added
99 unmodified lines
100 */101 isCanceled: boolean;102103 /**104 Whether the subprocess was canceled using both the `cancelSignal` and the `gracefulCancel` options.105 */106 isGracefullyCanceled: boolean;107108 /**109 Whether the subprocess failed because its output was larger than the `maxBuffer` option.110 */111 isMaxBuffer: boolean;112
91 unmodified lines
modified:types/ipc.d.ts+15 added-4 removed
89 unmodified lines
90This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.91*/92export function getEachMessage(getEachMessageOptions?: GetEachMessageOptions): AsyncIterableIterator<Message>;9394/**95Retrieves the [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) shared by the `cancelSignal` option.9697This can only be called inside a subprocess. This requires the `gracefulCancel` option to be `true`.98*/99export function getCancelSignal(): Promise<AbortSignal>;10094// IPC methods in the current process101// IPC methods in the subprocess102export type IpcMethods<103 IpcEnabled extends boolean,104 Serialization extends Options['serialization'],105> = IpcEnabled extends true
27 unmodified lines
133 getOneMessage: undefined;134 getEachMessage: undefined;135 };136130// Whether IPC is enabled, based on the `ipc` and `ipcInput` options137// Whether IPC is enabled, based on the `ipc`, `ipcInput` and `gracefulCancel` options138export type HasIpc<OptionsType extends Options> = HasIpcOption<139OptionsType['ipc'],133'ipcInput' extends keyof OptionsType ? OptionsType['ipcInput'] : undefined140'ipcInput' extends keyof OptionsType ? OptionsType['ipcInput'] : undefined,141'gracefulCancel' extends keyof OptionsType ? OptionsType['gracefulCancel'] : undefined142>;143144type HasIpcOption<145 IpcOption extends Options['ipc'],146 IpcInputOption extends Options['ipcInput'],147 GracefulCancelOption extends Options['gracefulCancel'],148> = IpcOption extends true149 ? true150 : IpcOption extends false151 ? false152 : IpcInputOption extends undefined153 ? GracefulCancelOption extends true154 ? true144 ? false155 : false156 : true;
modified:index.d.ts+1 added
19 unmodified lines
20export {21 sendMessage,22 getOneMessage,23 getEachMessage,24 getCancelSignal,25 type Message,26} from './types/ipc.js';
modified:index.js+2 added
16 unmodified lines
17const {18 sendMessage,19 getOneMessage,20 getEachMessage,21 getCancelSignal,22} = getIpcExport();23export {24 sendMessage,25 getOneMessage,26 getEachMessage,27 getCancelSignal,28};
modified:readme.md+30 added-1 removed
55 unmodified lines
56- [Simple syntax](#simple-syntax): promises and [template strings](docs/execution.md#template-string-syntax), like [`zx`](docs/bash.md).57- [Script](#script) interface.58- [No escaping](docs/escaping.md) nor quoting needed. No risk of shell injection.59- Execute [locally installed binaries](#local-binaries) without `npx`.60- Improved [Windows support](docs/windows.md): [shebangs](docs/windows.md#shebang), [`PATHEXT`](https://ss64.com/nt/path.html#pathext), [and more](https://github.com/moxystudio/node-cross-spawn?tab=readme-ov-file#why).60- Improved [Windows support](docs/windows.md): [shebangs](docs/windows.md#shebang), [`PATHEXT`](https://ss64.com/nt/path.html#pathext), [graceful termination](#graceful-termination), [and more](https://github.com/moxystudio/node-cross-spawn?tab=readme-ov-file#why).61- [Detailed errors](#detailed-error) and [verbose mode](#verbose-mode), for [debugging](docs/debugging.md).62- [Pipe multiple subprocesses](#pipe-multiple-subprocesses) better than in shells: retrieve [intermediate results](docs/pipe.md#result), use multiple [sources](docs/pipe.md#multiple-sources-1-destination)/[destinations](docs/pipe.md#1-source-multiple-destinations), [unpipe](docs/pipe.md#unpipe).63- [Split](#split-into-text-lines) the output into text lines, or [iterate](#iterate-over-text-lines) progressively over them.64- Strip [unnecessary newlines](docs/lines.md#newlines).
121 unmodified lines
186187#### Simple input188189```js190const getInputString = () => { /* ... */ };191const {stdout} = await execa({input: getInputString()})`sort`;192console.log(stdout);193```194
124 unmodified lines
319```js320// build.js321import {sendMessage} from 'execa';322323const runBuild = () => { /* ... */ };324325await sendMessage({kind: 'start', timestamp: new Date()});326await runBuild();327await sendMessage({kind: 'stop', timestamp: new Date()});328```329330#### Graceful termination331332```js333// main.js334import {execaNode} from 'execa';335336const controller = new AbortController();337setTimeout(() => {338 controller.abort();339}, 5000);340341await execaNode({342 cancelSignal: controller.signal,343 gracefulCancel: true,344})`build.js`;345```346347```js348// build.js349import {getCancelSignal} from 'execa';350351const cancelSignal = await getCancelSignal();352const url = 'https://example.com/build/info';353const response = await fetch(url, {signal: cancelSignal});354```355356### Debugging357358#### Detailed error359
62 unmodified lines