Add `exchangeMessage()` method (#1077)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 571e052 · Browse files · 39 files·+649 added−229 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
39 files+649 added−229 removed
- tests:+332 added−182 removed
- other:+317 added−47 removed
Provenance
- Commit
7a0a1c6- Tree
c6fd71a- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
571e052
39 files changed+649 added−229 removed
modified:docs/api.md+25 added-1 removed
134 unmodified lines135 This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.136 137 [More info.](ipc.md#listening-to-messages)138 139+### exchangeMessage(message, getOneMessageOptions?)140+141+`message`: [`Message`](ipc.md#message-type)\142+_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\143+_Returns_: [`Promise<Message>`](ipc.md#message-type)144+145+Send a `message` to the parent process, then receive a response from it.146+147+This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.148+149+[More info.](ipc.md#exchanging-messages)150+151 ## Return value152 153 _TypeScript:_ [`ResultPromise`](typescript.md)\154 _Type:_ `Promise<object> | Subprocess`149 unmodified lines304 This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.305 306 [More info.](ipc.md#listening-to-messages)307 308+### subprocess.exchangeMessage(message, getOneMessageOptions?)309+310+`message`: [`Message`](ipc.md#message-type)\311+_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\312+_Returns_: [`Promise<Message>`](ipc.md#message-type)313+314+Send a `message` to the subprocess, then receive a response from it.315+316+This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.317+318+[More info.](ipc.md#exchanging-messages)319+320 ### subprocess.stdin321 322 _Type:_ [`Writable | null`](https://nodejs.org/api/stream.html#class-streamwritable)323 613 unmodified lines937 938 _Type:_ `boolean`\939 _Default:_ `true` if either the [`node`](#optionsnode) option or the [`ipcInput`](#optionsipcinput) is set, `false` otherwise940 917-Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).941+Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions), [`subprocess.exchangeMessage(message)`](#subprocessexchangemessagemessage-getonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).942 943 The subprocess must be a Node.js file.944 945 [More info.](ipc.md)199 unmodified linesmodified:docs/execution.md+1 added-1 removed
124 unmodified linesExpand all1251261271281291291301311321334 unmodified lines124 unmodified linesExpand all- The [`stdin`](api.md#optionsstdin), [`stdout`](api.md#optionsstdout), [`stderr`](api.md#optionsstderr) and [`stdio`](api.md#optionsstdio) options cannot be [`'overlapped'`](api.md#optionsstdout), an [async iterable](lines.md#progressive-splitting), an async [transform](transform.md), a [`Duplex`](transform.md#duplextransform-streams), nor a [web stream](streams.md#web-streams). Node.js streams can be passed but only if either they [have a file descriptor](streams.md#file-descriptors), or the [`input`](api.md#optionsinput) option is used.- Signal termination: [`subprocess.kill()`](api.md#subprocesskillerror), [`subprocess.pid`](api.md#subprocesspid), [`cleanup`](api.md#optionscleanup) option, [`cancelSignal`](api.md#optionscancelsignal) option, [`forceKillAfterDelay`](api.md#optionsforcekillafterdelay) option.- Piping multiple subprocesses: [`subprocess.pipe()`](api.md#subprocesspipefile-arguments-options).- [`subprocess.iterable()`](lines.md#progressive-splitting).- [IPC](ipc.md): [`sendMessage()`](api.md#sendmessagemessage), [`getOneMessage()`](api.md#getonemessagegetonemessageoptions), [`getEachMessage()`](api.md#geteachmessage), [`result.ipcOutput`](output.md#any-output-type), [`ipc`](api.md#optionsipc) option, [`serialization`](api.md#optionsserialization) option, [`ipcInput`](input.md#any-input-type) option.- [IPC](ipc.md): [`sendMessage()`](api.md#sendmessagemessage), [`getOneMessage()`](api.md#getonemessagegetonemessageoptions), [`exchangeMessage()`](api.md#exchangemessagemessage-getonemessageoptions), [`getEachMessage()`](api.md#geteachmessage), [`result.ipcOutput`](output.md#any-output-type), [`ipc`](api.md#optionsipc) option, [`serialization`](api.md#optionsserialization) option, [`ipcInput`](input.md#any-input-type) option.- [`result.all`](api.md#resultall) is not interleaved.- [`detached`](api.md#optionsdetached) option.- The [`maxBuffer`](api.md#optionsmaxbuffer) option is always measured in bytes, not in characters, [lines](api.md#optionslines) nor [objects](transform.md#object-mode). Also, it ignores transforms and the [`encoding`](api.md#optionsencoding) option.
4 unmodified linesmodified:docs/ipc.md+61 added-7 removed
10 unmodified lines11 When the [`ipc`](api.md#optionsipc) option is `true`, the current process and subprocess can exchange messages. This only works if the subprocess is a [Node.js file](node.md).12 13 The `ipc` option defaults to `true` when using [`execaNode()`](node.md#run-nodejs-files) or the [`node`](node.md#run-nodejs-files) option.14 15-The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions). The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage) and [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) instead.15+The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions). [`subprocess.exchangeMessage(message)`](api.md#subprocessexchangemessagemessage-getonemessageoptions) combines both: first it sends a message, then it returns the response.16 17+The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage), [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) and [`exchangeMessage(message)`](api.md#exchangemessagemessage-getonemessageoptions) instead. Those are the same methods, but imported directly from the `'execa'` module.18+19 ```js20 // parent.js21 import {execaNode} from 'execa';22 23 const subprocess = execaNode`child.js`;22-console.log(await subprocess.getOneMessage()); // 'Hello from child'23-await subprocess.sendMessage('Hello from parent');24+const message = await subprocess.exchangeMessage('Hello from parent');25+console.log(message); // 'Hello from child'26 ```27 28 ```js29 // child.js28-import {sendMessage, getOneMessage} from 'execa';30+import {getOneMessage, sendMessage} from 'execa';31 30-await sendMessage('Hello from child');31-console.log(await getOneMessage()); // 'Hello from parent'32+const message = await getOneMessage(); // 'Hello from parent'33+const newMessage = message.replace('parent', 'child'); // 'Hello from child'34+await sendMessage(newMessage);35 ```36 37 ## Listening to messages38 36-[`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions) and [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) read a single message. To listen to multiple messages in a row, [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage) and [`getEachMessage()`](api.md#geteachmessage) should be used instead.39+The methods described above read a single message. On the other hand, [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage) and [`getEachMessage()`](api.md#geteachmessage) return an [async iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). This should be preferred when listening to multiple messages.40 41 [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage) waits for the subprocess to end (even when using [`break`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break) or [`return`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return)). It throws if the subprocess [fails](api.md#result). This means you do not need to `await` the subprocess' [promise](execution.md#result).42 43 ```js101 unmodified lines145 146 const subprocess = execaNode({serialization: 'json'})`child.js`;147 ```148 149+## Messages order150+151+The messages are always received in the same order they were sent.152+153 ## Debugging154 155 When the [`verbose`](api.md#optionsverbose) option is `'full'`, the IPC messages sent by the subprocess to the current process are [printed on the console](debugging.md#full-mode).156 157 Also, when the subprocess [failed](errors.md#subprocess-failure), [`error.ipcOutput`](api.md) contains all the messages sent by the subprocess. Those are also shown at the end of the [error message](errors.md#error-message).158 159+## Best practices160+161+### Call `getOneMessage()`/`getEachMessage()` early162+163+If a process sends a message but the other process is not listening/receiving it, that message is silently ignored.164+165+This means if [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) or [`getEachMessage()`](api.md#geteachmessage) is called too late (i.e. after the other process called [`sendMessage()`](api.md#sendmessagemessage)), it will miss the message. Also, it will keep waiting for the missed message, which might either make it hang forever, or throw when the other process exits.166+167+Therefore, listening to messages should always be done early, before the other process sends any message.168+169+### Prefer `exchangeMessage()` over `sendMessage()` + `getOneMessage()`170+171+When _first_ sending a message, _then_ receiving a response, the following code should be avoided.172+173+```js174+import {sendMessage, getOneMessage} from 'execa';175+176+await sendMessage(message);177+178+// The other process might respond between those two calls179+180+const response = await getOneMessage();181+```182+183+Indeed, when [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) is called, the other process might have already sent a response. This only happens when the other process is very fast. However, when it does happen, `getOneMessage()` will miss that response.184+185+Using [`exchangeMessage()`](api.md#exchangemessagemessage-getonemessageoptions) prevents this race condition.186+187+```js188+import {exchangeMessage} from 'execa';189+190+const response = await exchangeMessage(message);191+```192+193+However please note that, when doing the reverse (_first_ receiving a message, _then_ sending a response), the following code is correct.194+195+```js196+import {sendMessage, getOneMessage} from 'execa';197+198+const message = await getOneMessage();199+200+// The other process is just waiting for a response between those two calls.201+// So there is no race condition here.202+203+await sendMessage('response');204+```205+206 <hr>207 208 [**Next**: 🐛 Debugging](debugging.md)\209 [**Previous**: ⏳️ Streams](streams.md)\1 unmodified lineadded:lib/ipc/exchange.js+43 added
12345678910111213141516171819202122232425262728293031323334353637383940414243import {validateIpcMethod} from './validation.js';import {sendOneMessage} from './send.js';import {onceMessage} from './get-one.js';
// Like `[sub]process.send()` followed by `[sub]process.getOneMessage()`.// Avoids the following race condition: listening to `message` after the other process already responded.export const exchangeMessage = ({anyProcess, anyProcessSend, isSubprocess, ipc}, message, {filter} = {}) => { const methodName = 'exchangeMessage'; validateIpcMethod({ methodName, isSubprocess, ipc, isConnected: anyProcess.connected, });
return exchangeOneMessage({ anyProcess, anyProcessSend, isSubprocess, methodName, message, filter, });};
const exchangeOneMessage = async ({anyProcess, anyProcessSend, isSubprocess, methodName, message, filter}) => { const [response] = await Promise.all([ onceMessage({ anyProcess, isSubprocess, methodName, filter, }), sendOneMessage({ anyProcess, anyProcessSend, isSubprocess, methodName, message, }), ]); return response;};modified:lib/ipc/get-each.js+7 added-4 removed
1 import {once, on} from 'node:events';2-import {validateIpcOption, validateConnection, disconnect} from './validation.js';2+import {validateIpcMethod, disconnect} from './validation.js';3 4 // Like `[sub]process.on('message')` but promise-based5 export const getEachMessage = ({anyProcess, isSubprocess, ipc}) => loopOnMessages({6 anyProcess,3 unmodified lines10 });11 12 // Same but used internally13 export const loopOnMessages = ({anyProcess, isSubprocess, ipc, shouldAwait}) => {14- const methodName = 'getEachMessage';15- validateIpcOption(methodName, isSubprocess, ipc);16- validateConnection(methodName, isSubprocess, anyProcess.channel !== null);14+ validateIpcMethod({15+ methodName: 'getEachMessage',16+ isSubprocess,17+ ipc,18+ isConnected: anyProcess.channel !== null,19+ });20 21 const controller = new AbortController();22 stopOnExit(anyProcess, controller);23 return iterateOnMessages(anyProcess, shouldAwait, controller);37 unmodified linesmodified:lib/ipc/get-one.js+9 added-5 removed
1 import {once, on} from 'node:events';2 import {3- validateIpcOption,4- validateConnection,3+ validateIpcMethod,4 disconnect,5 throwOnEarlyDisconnect,6 } from './validation.js';7 8 // Like `[sub]process.once('message')` but promise-based9 export const getOneMessage = ({anyProcess, isSubprocess, ipc}, {filter} = {}) => {10 const methodName = 'getOneMessage';12- validateIpcOption(methodName, isSubprocess, ipc);13- validateConnection(methodName, isSubprocess, anyProcess.channel !== null);11+ validateIpcMethod({12+ methodName,13+ isSubprocess,14+ ipc,15+ isConnected: anyProcess.channel !== null,16+ });17 18 return onceMessage({19 anyProcess,20 isSubprocess,1 unmodified line22 filter,23 });24 };25 26+// Same but used internally23-const onceMessage = async ({anyProcess, isSubprocess, methodName, filter}) => {27+export const onceMessage = async ({anyProcess, isSubprocess, methodName, filter}) => {28 const controller = new AbortController();29 try {30 return await Promise.race([31 getMessage(anyProcess, filter, controller),32 unmodified linesmodified:lib/ipc/methods.js+7 added
1234567891015 unmodified lines262728293031323334353637import process from 'node:process';import {promisify} from 'node:util';import {sendMessage} from './send.js';import {getOneMessage} from './get-one.js';import {getEachMessage} from './get-each.js';import {exchangeMessage} from './exchange.js';
// Add promise-based IPC methods in current processexport const addIpcMethods = (subprocess, {ipc}) => { Object.assign(subprocess, getIpcMethods(subprocess, false, ipc));15 unmodified lines ipc, }), getOneMessage: getOneMessage.bind(undefined, {anyProcess, isSubprocess, ipc}), getEachMessage: getEachMessage.bind(undefined, {anyProcess, isSubprocess, ipc}), exchangeMessage: exchangeMessage.bind(undefined, { anyProcess, anyProcessSend, isSubprocess, ipc, }), };};modified:lib/ipc/send.js+17 added-7 removed
1 import {2- validateIpcOption,3- validateConnection,2+ validateIpcMethod,3 handleSerializationError,4 disconnect,5 } from './validation.js';6 7 // Like `[sub]process.send()` but promise-based.9-// We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.8+// We do not `await subprocess` during `.sendMessage()`, `.getOneMessage()` nor `.exchangeMessage()` since those methods are transient.9 // Users would still need to `await subprocess` after the method is done.10 // Also, this would prevent `unhandledRejection` event from being emitted, making it silent.11 export const sendMessage = ({anyProcess, anyProcessSend, isSubprocess, ipc}, message) => {12 const methodName = 'sendMessage';14- validateIpcOption(methodName, isSubprocess, ipc);15- validateConnection(methodName, isSubprocess, anyProcess.connected);13+ validateIpcMethod({14+ methodName,15+ isSubprocess,16+ ipc,17+ isConnected: anyProcess.connected,18+ });19 20 return sendOneMessage({21 anyProcess,22 anyProcessSend,23 isSubprocess,24+ methodName,25 message,26 });27 };28 25-const sendOneMessage = async ({anyProcess, anyProcessSend, isSubprocess, message}) => {29+// Same but used internally30+export const sendOneMessage = async ({anyProcess, anyProcessSend, isSubprocess, methodName, message}) => {31 try {32 await anyProcessSend(message);33 } catch (error) {34 disconnect(anyProcess);30- handleSerializationError(error, isSubprocess, message);35+ handleSerializationError({36+ error,37+ isSubprocess,38+ methodName,39+ message,40+ });41 throw error;42 }43 };modified:lib/ipc/validation.js+10 added-4 removed
1+// Validate the IPC channel is connected before receiving/sending messages2+export const validateIpcMethod = ({methodName, isSubprocess, ipc, isConnected}) => {3+ validateIpcOption(methodName, isSubprocess, ipc);4+ validateConnection(methodName, isSubprocess, isConnected);5+};6+7 // Better error message when forgetting to set `ipc: true` and using the IPC methods2-export const validateIpcOption = (methodName, isSubprocess, ipc) => {8+const validateIpcOption = (methodName, isSubprocess, ipc) => {9 if (!ipc) {10 throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() can only be used if the \`ipc\` option is \`true\`.`);11 }12 };13 14 // 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.10-export const validateConnection = (methodName, isSubprocess, isConnected) => {16+const validateConnection = (methodName, isSubprocess, isConnected) => {17 if (!isConnected) {18 throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);19 }20 };8 unmodified lines29 const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';30 31 // Better error message when sending messages which cannot be serialized.32 // Works with both `serialization: 'advanced'` and `serialization: 'json'`.27-export const handleSerializationError = (error, isSubprocess, message) => {33+export const handleSerializationError = ({error, isSubprocess, methodName, message}) => {34 if (isSerializationError(error)) {29- error.message = `${getNamespaceName(isSubprocess)}sendMessage()'s argument type is invalid: the message cannot be serialized: ${String(message)}.\n${error.message}`;35+ error.message = `${getNamespaceName(isSubprocess)}${methodName}()'s argument type is invalid: the message cannot be serialized: ${String(message)}.\n${error.message}`;36 }37 };38 39 const isSerializationError = ({code, message}) => SERIALIZATION_ERROR_CODES.has(code)28 unmodified linesmodified:test/convert/readable.js+2 added-4 removed
116 unmodified lines117 const subprocess = execa('ipc-echo.js', {ipc: true});118 const stream = subprocess[methodName]();119 120 subprocess.stdout.destroy();121- await subprocess.sendMessage(foobarString);121 122 const [error, message] = await Promise.all([123 t.throwsAsync(finishedStream(stream)),125- subprocess.getOneMessage(),124+ subprocess.exchangeMessage(foobarString),125 ]);126 t.like(error, prematureClose);127 t.is(message, foobarString);128 assertWritableAborted(t, subprocess.stdin);10 unmodified lines139 const stream = subprocess[methodName]();140 141 const cause = new Error(foobarString);142 subprocess.stdout.destroy(cause);144- await subprocess.sendMessage(foobarString);143 144 const [error, message] = await Promise.all([145 t.throwsAsync(finishedStream(stream)),148- subprocess.getOneMessage(),146+ subprocess.exchangeMessage(foobarString),147 ]);148 t.is(message, foobarString);149 t.is(error.cause, cause);150 assertProcessNormalExit(t, error);307 unmodified linesadded:test/fixtures/ipc-echo-filter-exchange.js+5 added
1+#!/usr/bin/env node2+import {sendMessage, exchangeMessage} from '../../index.js';3+import {foobarArray} from '../helpers/input.js';4+5+await sendMessage(await exchangeMessage('.', ({filter: message => message === foobarArray[1]})));added:test/fixtures/ipc-echo-item-exchange.js+5 added
1+#!/usr/bin/env node2+import {exchangeMessage, getOneMessage} from '../../index.js';3+4+const [message] = await getOneMessage();5+await exchangeMessage(message);added:test/fixtures/ipc-echo-twice-filter-get.js+10 added
1+#!/usr/bin/env node2+import {sendMessage, getOneMessage} from '../../index.js';3+import {alwaysPass} from '../helpers/ipc.js';4+5+const message = await getOneMessage({filter: alwaysPass});6+const [secondMessage] = await Promise.all([7+ getOneMessage({filter: alwaysPass}),8+ sendMessage(message),9+]);10+await sendMessage(secondMessage);modified:test/fixtures/ipc-echo-twice-filter.js+3 added-4 removed
1 #!/usr/bin/env node2-import {sendMessage, getOneMessage} from '../../index.js';2+import {sendMessage, getOneMessage, exchangeMessage} from '../../index.js';3 import {alwaysPass} from '../helpers/ipc.js';4 5 const message = await getOneMessage({filter: alwaysPass});6-const secondMessagePromise = getOneMessage({filter: alwaysPass});7-await sendMessage(message);8-await sendMessage(await secondMessagePromise);6+const secondMessage = await exchangeMessage(message, {filter: alwaysPass});7+await sendMessage(secondMessage);added:test/fixtures/ipc-echo-twice-get.js+9 added
1+#!/usr/bin/env node2+import {sendMessage, getOneMessage} from '../../index.js';3+4+const message = await getOneMessage();5+const [secondMessage] = await Promise.all([6+ getOneMessage(),7+ sendMessage(message),8+]);9+await sendMessage(await secondMessage);modified:test/fixtures/ipc-echo-twice.js+3 added-4 removed
1 #!/usr/bin/env node2-import {sendMessage, getOneMessage} from '../../index.js';2+import {sendMessage, getOneMessage, exchangeMessage} from '../../index.js';3 4 const message = await getOneMessage();5-const secondMessagePromise = getOneMessage();6-await sendMessage(message);7-await sendMessage(await secondMessagePromise);5+const secondMessage = await exchangeMessage(message);6+await sendMessage(await secondMessage);added:test/fixtures/ipc-exchange-error.js+4 added
1+#!/usr/bin/env node2+import {exchangeMessage} from '../../index.js';3+4+await exchangeMessage(0n);modified:test/fixtures/ipc-iterate-error.js+1 added-11 removed
1 #!/usr/bin/env node2 import process from 'node:process';3-import {getEachMessage} from '../../index.js';3 import {foobarString} from '../helpers/input.js';4+import {iterateAllMessages} from '../helpers/ipc.js';5 6-// @todo: replace with Array.fromAsync(subprocess.getEachMessage()) after dropping support for Node <22.0.07-const iterateAllMessages = async () => {8- const messages = [];9- for await (const message of getEachMessage()) {10- messages.push(message);11- }12-13- return messages;14-};15-6 const cause = new Error(foobarString);7 await Promise.all([8 iterateAllMessages(),9 process.emit('error', cause),1 unmodified lineadded:test/fixtures/ipc-process-error-exchange.js+10 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {exchangeMessage} from '../../index.js';4+import {foobarString} from '../helpers/input.js';5+6+const cause = new Error(foobarString);7+await Promise.all([8+ exchangeMessage('.'),9+ process.emit('error', cause),10+]);added:test/fixtures/ipc-process-error-filter-exchange.js+11 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {exchangeMessage} from '../../index.js';4+import {foobarString} from '../helpers/input.js';5+import {alwaysPass} from '../helpers/ipc.js';6+7+const cause = new Error(foobarString);8+await Promise.all([9+ exchangeMessage('.', {filter: alwaysPass}),10+ process.emit('error', cause),11+]);modified:test/fixtures/ipc-send-print.js+2 added-1 removed
1 unmodified line2 import process from 'node:process';3 import {sendMessage, getOneMessage} from '../../index.js';4 import {foobarString} from '../helpers/input.js';5 6+const promise = getOneMessage();7 await sendMessage(foobarString);8 9 process.stdout.write('.');10 10-await getOneMessage();11+await promise;modified:test/fixtures/ipc-send-twice-wait.js+2 added-3 removed
1 #!/usr/bin/env node2-import {sendMessage, getOneMessage} from '../../index.js';2+import {sendMessage, exchangeMessage} from '../../index.js';3 import {foobarString} from '../helpers/input.js';4 5 await sendMessage(foobarString);6-await sendMessage(foobarString);7-await getOneMessage();6+await exchangeMessage(foobarString);modified:test/helpers/ipc.js+16 added
1+import isPlainObj from 'is-plain-obj';2+3+export const subprocessGetOne = (subprocess, options) => subprocess.getOneMessage(options);4+5+export const subprocessSendGetOne = async (subprocess, message) => {6+ const [response] = await Promise.all([7+ subprocess.getOneMessage(),8+ subprocess.sendMessage(message),9+ ]);10+ return response;11+};12+13+export const subprocessExchange = (subprocess, messageOrOptions) => isPlainObj(messageOrOptions)14+ ? subprocess.exchangeMessage('.', messageOrOptions)15+ : subprocess.exchangeMessage(messageOrOptions);16+17 // @todo: replace with Array.fromAsync(subprocess.getEachMessage()) after dropping support for Node <22.0.018 export const iterateAllMessages = async subprocess => {19 const messages = [];20 for await (const message of subprocess.getEachMessage()) {7 unmodified linesmodified:test/io/max-buffer.js+1 added-1 removed
276 unmodified lines277 } = await t.throwsAsync(execa('ipc-send-twice-wait.js', {ipc: true, maxBuffer: {ipc: 1}}));278 t.true(isMaxBuffer);279 t.is(shortMessage, 'Command\'s IPC output was larger than 1 messages: ipc-send-twice-wait.js\nmaxBuffer exceeded');280 t.true(message.endsWith(`\n\n${foobarString}`));281- t.true(stderr.includes('Error: getOneMessage() could not complete'));281+ t.true(stderr.includes('Error: exchangeMessage() could not complete'));282 t.deepEqual(ipcOutput, [foobarString]);283 });284 285 test('maxBuffer is ignored with result.ipcOutput if buffer is false', async t => {8 unmodified linesmodified:test/ipc/buffer-messages.js+11 added
55 unmodified lines56 const {ipcOutput} = t.throws(() => execaSync('fail.js'));57 t.deepEqual(ipcOutput, []);58 });59 60+const HIGH_CONCURRENCY_COUNT = 10;61+62+test.serial('Can retrieve initial IPC messages under heavy load', async t => {63+ await Promise.all(64+ Array.from({length: HIGH_CONCURRENCY_COUNT}, async (_, index) => {65+ const {ipcOutput} = await execa('ipc-send-argv.js', [`${index}`], {ipc: true});66+ t.deepEqual(ipcOutput, [`${index}`]);67+ }),68+ );69+});70+71 test('"error" event interrupts result.ipcOutput', async t => {72 const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});73 t.is(await subprocess.getOneMessage(), foobarString);74 6 unmodified linesmodified:test/ipc/get-each.js+28 added-10 removed
29 unmodified lines30 31 test('Can iterate multiple times over IPC messages in subprocess', async t => {32 const subprocess = execa('ipc-iterate-twice.js', {ipc: true});33 34- await subprocess.sendMessage('.');35- t.is(await subprocess.getOneMessage(), '.');36- await subprocess.sendMessage(foobarString);37- t.is(await subprocess.getOneMessage(), foobarString);38- await subprocess.sendMessage('.');39- t.is(await subprocess.getOneMessage(), '.');40- await subprocess.sendMessage(foobarString);41- t.is(await subprocess.getOneMessage(), foobarString);34+ t.is(await subprocess.exchangeMessage('.'), '.');35+ t.is(await subprocess.exchangeMessage(foobarString), foobarString);36+ t.is(await subprocess.exchangeMessage('.'), '.');37+ t.is(await subprocess.exchangeMessage(foobarString), foobarString);38 39 const {ipcOutput} = await subprocess;40 t.deepEqual(ipcOutput, ['.', foobarString, '.', foobarString]);41 });8 unmodified lines50 const {ipcOutput} = await subprocess;51 t.deepEqual(ipcOutput, foobarArray);52 });53 58-const HIGH_CONCURRENCY_COUNT = 100;54+const HIGH_CONCURRENCY_COUNT = 10;55 60-test('Can send many messages at once with exports.getEachMessage()', async t => {56+test.serial('Can send many messages at once with exports.getEachMessage()', async t => {57 const subprocess = execa('ipc-iterate.js', {ipc: true});58 await Promise.all(Array.from({length: HIGH_CONCURRENCY_COUNT}, (_, index) => subprocess.sendMessage(index)));59 await subprocess.sendMessage(foobarString);60 30 unmodified lines91 const {ipcOutput} = await subprocess;92 t.deepEqual(ipcOutput, [foobarString]);93 });94 95+const testParentError = async (t, buffer) => {96+ const subprocess = execa('ipc-send-twice.js', {ipc: true, buffer});97+ const promise = iterateAllMessages(subprocess);98+99+ const cause = new Error(foobarString);100+ subprocess.emit('error', cause);101+102+ const ipcError = await t.throwsAsync(promise);103+ t.is(ipcError.cause, cause);104+105+ const error = await t.throwsAsync(subprocess);106+ t.is(error.exitCode, undefined);107+ t.false(error.isTerminated);108+ t.is(error.cause, cause);109+ if (buffer) {110+ t.true(error.message.includes('Error: sendMessage() cannot be used'));111+ }112+};113+114+test('"error" event interrupts subprocess.getEachMessage(), buffer false', testParentError, false);115+test('error" event interrupts subprocess.getEachMessage(), buffer true', testParentError, true);116+117 const loopAndBreak = async (t, subprocess) => {118 // eslint-disable-next-line no-unreachable-loop119 for await (const message of subprocess.getEachMessage()) {120 t.is(message, foobarString);29 unmodified linesmodified:test/ipc/get-one.js+105 added-80 removed
2 unmodified lines3 import test from 'ava';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString, foobarArray} from '../helpers/input.js';7-import {iterateAllMessages, alwaysPass} from '../helpers/ipc.js';7+import {8+ subprocessGetOne,9+ subprocessSendGetOne,10+ subprocessExchange,11+ alwaysPass,12+} from '../helpers/ipc.js';13 14 setFixtureDirectory();15 11-const getOneSubprocessMessage = subprocess => subprocess.getOneMessage();12-const getOneFilteredMessage = subprocess => subprocess.getOneMessage({filter: alwaysPass});13-14-const testKeepAlive = async (t, buffer) => {16+const testKeepAlive = async (t, buffer, exchangeMethod) => {17 const subprocess = execa('ipc-echo-twice.js', {ipc: true, buffer});16- await subprocess.sendMessage(foobarString);17- t.is(await subprocess.getOneMessage(), foobarString);18- await subprocess.sendMessage(foobarString);19- t.is(await subprocess.getOneMessage(), foobarString);18+ t.is(await exchangeMethod(subprocess, foobarString), foobarString);19+ t.is(await exchangeMethod(subprocess, foobarString), foobarString);20 await subprocess;21 };22 23-test('subprocess.getOneMessage() keeps the subprocess alive, buffer false', testKeepAlive, false);24-test('subprocess.getOneMessage() keeps the subprocess alive, buffer true', testKeepAlive, true);23+test('subprocess.getOneMessage() keeps the subprocess alive, buffer false', testKeepAlive, false, subprocessSendGetOne);24+test('subprocess.getOneMessage() keeps the subprocess alive, buffer true', testKeepAlive, true, subprocessSendGetOne);25+test('subprocess.getOneMessage() keeps the subprocess alive, buffer false, exchangeMessage()', testKeepAlive, false, subprocessExchange);26+test('subprocess.getOneMessage() keeps the subprocess alive, buffer true, exchangeMessage()', testKeepAlive, true, subprocessExchange);27 26-const testBufferInitial = async (t, buffer) => {28+const testBufferInitial = async (t, buffer, exchangeMethod) => {29 const subprocess = execa('ipc-echo-wait.js', {ipc: true, buffer});28- await subprocess.sendMessage(foobarString);29- t.is(await subprocess.getOneMessage(), foobarString);30+ t.is(await exchangeMethod(subprocess, foobarString), foobarString);31 await subprocess;32 };33 33-test('Buffers initial message to subprocess, buffer false', testBufferInitial, false);34-test('Buffers initial message to subprocess, buffer true', testBufferInitial, true);34+test('Buffers initial message to subprocess, buffer false', testBufferInitial, false, subprocessSendGetOne);35+test('Buffers initial message to subprocess, buffer true', testBufferInitial, true, subprocessSendGetOne);36+test('Buffers initial message to subprocess, buffer false, exchangeMessage()', testBufferInitial, false, subprocessExchange);37+test('Buffers initial message to subprocess, buffer true, exchangeMessage()', testBufferInitial, true, subprocessExchange);38 39 test('Buffers initial message to current process, buffer false', async t => {40 const subprocess = execa('ipc-send-print.js', {ipc: true, buffer: false});41 const [chunk] = await once(subprocess.stdout, 'data');13 unmodified lines55 const {ipcOutput} = await subprocess;56 t.deepEqual(ipcOutput, [foobarString]);57 });58 56-const HIGH_CONCURRENCY_COUNT = 100;57-58-test('subprocess.getOneMessage() can filter messages', async t => {59+const testFilterParent = async (t, exchangeMethod) => {60 const subprocess = execa('ipc-send-twice.js', {ipc: true});60- const message = await subprocess.getOneMessage({filter: message => message === foobarArray[1]});61+ const message = await exchangeMethod(subprocess, {filter: message => message === foobarArray[1]});62 t.is(message, foobarArray[1]);63 64 const {ipcOutput} = await subprocess;65 t.deepEqual(ipcOutput, foobarArray);65-});66+};67 67-test('exports.getOneMessage() can filter messages', async t => {68- const subprocess = execa('ipc-echo-filter.js', {ipc: true});68+test('subprocess.getOneMessage() can filter messages', testFilterParent, subprocessGetOne);69+test('subprocess.exchangeMessage() can filter messages', testFilterParent, subprocessExchange);70+71+const testFilterSubprocess = async (t, fixtureName, expectedOutput) => {72+ const subprocess = execa(fixtureName, {ipc: true});73 await subprocess.sendMessage(foobarArray[0]);74 await subprocess.sendMessage(foobarArray[1]);75 76 const {ipcOutput} = await subprocess;73- t.deepEqual(ipcOutput, [foobarArray[1]]);74-});77+ t.deepEqual(ipcOutput, expectedOutput);78+};79 76-test.serial('Can retrieve initial IPC messages under heavy load, buffer false', async t => {80+test('exports.getOneMessage() can filter messages', testFilterSubprocess, 'ipc-echo-filter.js', [foobarArray[1]]);81+test('exports.exchangeMessage() can filter messages', testFilterSubprocess, 'ipc-echo-filter-exchange.js', ['.', foobarArray[1]]);82+83+const HIGH_CONCURRENCY_COUNT = 10;84+85+const testHeavyLoad = async (t, exchangeMethod) => {86 await Promise.all(87 Array.from({length: HIGH_CONCURRENCY_COUNT}, async (_, index) => {88 const subprocess = execa('ipc-send-argv.js', [`${index}`], {ipc: true, buffer: false});80- t.is(await subprocess.getOneMessage(), `${index}`);89+ t.is(await exchangeMethod(subprocess, {}), `${index}`);90 await subprocess;91 }),92 );84-});93+};94 86-test.serial('Can retrieve initial IPC messages under heavy load, buffer true', async t => {87- await Promise.all(88- Array.from({length: HIGH_CONCURRENCY_COUNT}, async (_, index) => {89- const {ipcOutput} = await execa('ipc-send-argv.js', [`${index}`], {ipc: true});90- t.deepEqual(ipcOutput, [`${index}`]);91- }),92- );93-});95+test.serial('Can retrieve initial IPC messages under heavy load', testHeavyLoad, subprocessGetOne);96+test.serial('Can retrieve initial IPC messages under heavy load, exchangeMessage()', testHeavyLoad, subprocessExchange);97 95-const testTwice = async (t, buffer, filter) => {98+const testTwice = async (t, exchangeMethod, buffer, filter) => {99 const subprocess = execa('ipc-send.js', {ipc: true, buffer});100 t.deepEqual(98- await Promise.all([subprocess.getOneMessage({filter}), subprocess.getOneMessage({filter})]),101+ await Promise.all([exchangeMethod(subprocess, {filter}), exchangeMethod(subprocess, {filter})]),102 [foobarString, foobarString],103 );104 await subprocess;105 };106 104-test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, false, undefined);105-test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, true, undefined);106-test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', testTwice, false, alwaysPass);107-test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', testTwice, true, alwaysPass);107+test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, subprocessGetOne, false, undefined);108+test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, subprocessGetOne, true, undefined);109+test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', testTwice, subprocessGetOne, false, alwaysPass);110+test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', testTwice, subprocessGetOne, true, alwaysPass);111+test('subprocess.exchangeMessage() can be called twice at the same time, buffer false', testTwice, subprocessExchange, false, undefined);112+test('subprocess.exchangeMessage() can be called twice at the same time, buffer true', testTwice, subprocessExchange, true, undefined);113+test('subprocess.exchangeMessage() can be called twice at the same time, buffer false, filter', testTwice, subprocessExchange, false, alwaysPass);114+test('subprocess.exchangeMessage() can be called twice at the same time, buffer true, filter', testTwice, subprocessExchange, true, alwaysPass);115 109-const testCleanupListeners = async (t, buffer, filter) => {116+const testCleanupListeners = async (t, exchangeMethod, buffer, filter) => {117 const subprocess = execa('ipc-send.js', {ipc: true, buffer});118 const bufferCount = buffer ? 1 : 0;119 120 t.is(subprocess.listenerCount('message'), bufferCount);121 t.is(subprocess.listenerCount('disconnect'), bufferCount);122 116- const promise = subprocess.getOneMessage({filter});123+ const promise = exchangeMethod(subprocess, {filter});124 t.is(subprocess.listenerCount('message'), bufferCount + 1);125 t.is(subprocess.listenerCount('disconnect'), bufferCount + 1);126 t.is(await promise, foobarString);127 5 unmodified lines133 t.is(subprocess.listenerCount('message'), 0);134 t.is(subprocess.listenerCount('disconnect'), 0);135 };136 130-test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false, undefined);131-test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true, undefined);132-test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', testCleanupListeners, false, alwaysPass);133-test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', testCleanupListeners, true, alwaysPass);137+test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, subprocessGetOne, false, undefined);138+test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, subprocessGetOne, true, undefined);139+test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', testCleanupListeners, subprocessGetOne, false, alwaysPass);140+test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', testCleanupListeners, subprocessGetOne, true, alwaysPass);141+test('Cleans up subprocess.exchangeMessage() listeners, buffer false', testCleanupListeners, subprocessExchange, false, undefined);142+test('Cleans up subprocess.exchangeMessage() listeners, buffer true', testCleanupListeners, subprocessExchange, true, undefined);143+test('Cleans up subprocess.exchangeMessage() listeners, buffer false, filter', testCleanupListeners, subprocessExchange, false, alwaysPass);144+test('Cleans up subprocess.exchangeMessage() listeners, buffer true, filter', testCleanupListeners, subprocessExchange, true, alwaysPass);145 135-const testParentDisconnect = async (t, buffer, filter) => {136- const fixtureName = filter ? 'ipc-echo-twice-filter.js' : 'ipc-echo-twice.js';146+const testParentDisconnect = async (t, buffer, filter, exchange) => {147+ const fixtureStart = filter ? 'ipc-echo-twice-filter' : 'ipc-echo-twice';148+ const fixtureName = exchange ? `${fixtureStart}.js` : `${fixtureStart}-get.js`;149 const subprocess = execa(fixtureName, {ipc: true, buffer});150 await subprocess.sendMessage(foobarString);151 t.is(await subprocess.getOneMessage(), foobarString);152 2 unmodified lines155 const {exitCode, isTerminated, message} = await t.throwsAsync(subprocess);156 t.is(exitCode, 1);157 t.false(isTerminated);158 if (buffer) {147- t.true(message.includes('Error: getOneMessage() could not complete'));159+ const methodName = exchange ? 'exchangeMessage()' : 'getOneMessage()';160+ t.true(message.includes(`Error: ${methodName} could not complete`));161 }162 };163 151-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false, false);152-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true, false);153-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', testParentDisconnect, false, true);154-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true, filter', testParentDisconnect, true, true);164+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false, false, false);165+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true, false, false);166+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', testParentDisconnect, false, true, false);167+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true, filter', testParentDisconnect, true, false);168+test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer false', testParentDisconnect, false, false, true);169+test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer true', testParentDisconnect, true, false, true);170+test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer false, filter', testParentDisconnect, false, true, true);171+test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer true, filter', testParentDisconnect, true, true, true);172 173+// eslint-disable-next-line max-params156-const testSubprocessDisconnect = async (t, buffer, filter) => {174+const testSubprocessDisconnect = async (t, exchangeMethod, methodName, buffer, filter) => {175 const subprocess = execa('empty.js', {ipc: true, buffer});158- await t.throwsAsync(subprocess.getOneMessage({filter}), {159- message: /subprocess\.getOneMessage\(\) could not complete/,160- });176+ const {message} = await t.throwsAsync(exchangeMethod(subprocess, {filter}));177+ t.true(message.includes(`subprocess.${methodName}() could not complete`));178 await subprocess;179 };180 164-test('Subprocess exit interrupts disconnect.getOneMessage(), buffer false', testSubprocessDisconnect, false, undefined);165-test('Subprocess exit interrupts disconnect.getOneMessage(), buffer true', testSubprocessDisconnect, true, undefined);166-test('Subprocess exit interrupts disconnect.getOneMessage(), buffer false, filter', testSubprocessDisconnect, false, alwaysPass);167-test('Subprocess exit interrupts disconnect.getOneMessage(), buffer true, filter', testSubprocessDisconnect, true, alwaysPass);181+test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', false, undefined);182+test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', true, undefined);183+test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false, filter', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', false, alwaysPass);184+test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true, filter', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', true, alwaysPass);185+test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer false', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', false, undefined);186+test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer true', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', true, undefined);187+test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer false, filter', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', false, alwaysPass);188+test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer true, filter', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', true, alwaysPass);189 169-const testParentError = async (t, getMessages, useCause, buffer) => {170- const subprocess = execa('ipc-echo.js', {ipc: true, buffer});171- await subprocess.sendMessage(foobarString);172- const promise = getMessages(subprocess);190+const testParentError = async (t, exchangeMethod, filter, buffer) => {191+ const subprocess = execa('forever.js', {ipc: true, buffer});192+ const promise = exchangeMethod(subprocess, {filter});193 194 const cause = new Error(foobarString);195 subprocess.emit('error', cause);196+ t.is(await t.throwsAsync(promise), cause);197 177- const ipcError = await t.throwsAsync(promise);178- t.is(useCause ? ipcError.cause : ipcError, cause);179-198+ subprocess.kill();199 const error = await t.throwsAsync(subprocess);181- t.is(error.exitCode, 1);200+ t.is(error.exitCode, undefined);201 t.false(error.isTerminated);202 t.is(error.cause, cause);184- if (buffer) {185- t.true(error.message.includes('Error: getOneMessage() cannot be used'));186- }203 };204 189-test('"error" event interrupts subprocess.getOneMessage(), buffer false', testParentError, getOneSubprocessMessage, false, false);190-test('"error" event interrupts subprocess.getOneMessage(), buffer true', testParentError, getOneSubprocessMessage, false, true);191-test('"error" event interrupts subprocess.getOneMessage(), buffer false, filter', testParentError, getOneFilteredMessage, false, false);192-test('"error" event interrupts subprocess.getOneMessage(), buffer true, filter', testParentError, getOneFilteredMessage, false, true);193-test('"error" event interrupts subprocess.getEachMessage(), buffer false', testParentError, iterateAllMessages, true, false);194-test('"error" event interrupts subprocess.getEachMessage(), buffer true', testParentError, iterateAllMessages, true, true);205+test('"error" event interrupts subprocess.getOneMessage(), buffer false', testParentError, subprocessGetOne, undefined, false);206+test('"error" event interrupts subprocess.getOneMessage(), buffer true', testParentError, subprocessGetOne, undefined, true);207+test('"error" event interrupts subprocess.getOneMessage(), buffer false, filter', testParentError, subprocessGetOne, alwaysPass, false);208+test('"error" event interrupts subprocess.getOneMessage(), buffer true, filter', testParentError, subprocessGetOne, alwaysPass, true);209+test('"error" event interrupts subprocess.exchangeMessage(), buffer false', testParentError, subprocessExchange, undefined, false);210+test('"error" event interrupts subprocess.exchangeMessage(), buffer true', testParentError, subprocessExchange, undefined, true);211+test('"error" event interrupts subprocess.exchangeMessage(), buffer false, filter', testParentError, subprocessExchange, alwaysPass, false);212+test('"error" event interrupts subprocess.exchangeMessage(), buffer true, filter', testParentError, subprocessExchange, alwaysPass, true);213 214 const testSubprocessError = async (t, fixtureName, buffer) => {215 const subprocess = execa(fixtureName, {ipc: true, buffer});216+ if (fixtureName.includes('exchange')) {217+ await subprocess.getOneMessage();218+ }219 220 const ipcError = await t.throwsAsync(subprocess.getOneMessage());221 t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));222 8 unmodified lines231 test('"error" event interrupts exports.getOneMessage(), buffer false', testSubprocessError, 'ipc-process-error.js', false);232 test('"error" event interrupts exports.getOneMessage(), buffer true', testSubprocessError, 'ipc-process-error.js', true);233 test('"error" event interrupts exports.getOneMessage(), buffer false, filter', testSubprocessError, 'ipc-process-error-filter.js', false);234 test('"error" event interrupts exports.getOneMessage(), buffer true, filter', testSubprocessError, 'ipc-process-error-filter.js', true);235+test('"error" event interrupts exports.exchangeMessage(), buffer false', testSubprocessError, 'ipc-process-error-exchange.js', false);236+test('"error" event interrupts exports.exchangeMessage(), buffer true', testSubprocessError, 'ipc-process-error-exchange.js', true);237+test('"error" event interrupts exports.exchangeMessage(), buffer false, filter', testSubprocessError, 'ipc-process-error-filter-exchange.js', false);238+test('"error" event interrupts exports.exchangeMessage(), buffer true, filter', testSubprocessError, 'ipc-process-error-filter-exchange.js', true);239 test('"error" event interrupts exports.getEachMessage(), buffer false', testSubprocessError, 'ipc-iterate-error.js', false);240 test('"error" event interrupts exports.getEachMessage(), buffer true', testSubprocessError, 'ipc-iterate-error.js', true);modified:test/ipc/send.js+60 added-41 removed
1 import test from 'ava';2 import {execa} from '../../index.js';3 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4 import {foobarString} from '../helpers/input.js';5+import {subprocessSendGetOne, subprocessExchange} from '../helpers/ipc.js';6 7 setFixtureDirectory();8 8-test('Can exchange IPC messages', async t => {9+const testExchange = async (t, exchangeMethod) => {10 const subprocess = execa('ipc-echo.js', {ipc: true});10- await subprocess.sendMessage(foobarString);11- t.is(await subprocess.getOneMessage(), foobarString);11+ t.is(await exchangeMethod(subprocess, foobarString), foobarString);12 await subprocess;13-});13+};14 15-const HIGH_CONCURRENCY_COUNT = 100;15+test('Can exchange IPC messages', testExchange, subprocessSendGetOne);16+test('Can exchange IPC messages, exchangeMessage()', testExchange, subprocessExchange);17 17-test.serial('Can exchange IPC messages under heavy load', async t => {18+const HIGH_CONCURRENCY_COUNT = 10;19+20+const testHeavyLoad = async (t, exchangeMethod) => {21 await Promise.all(22 Array.from({length: HIGH_CONCURRENCY_COUNT}, async (_, index) => {23 const subprocess = execa('ipc-echo.js', {ipc: true});21- await subprocess.sendMessage(index);22- t.is(await subprocess.getOneMessage(), index);24+ t.is(await exchangeMethod(subprocess, index), index);25 await subprocess;26 }),27 );26-});28+};29 28-test('Can use "serialization: json" option', async t => {30+test.serial('Can exchange IPC messages under heavy load', testHeavyLoad, subprocessSendGetOne);31+test.serial('Can exchange IPC messages under heavy load, exchangeMessage()', testHeavyLoad, subprocessExchange);32+33+const testDefaultSerialization = async (t, exchangeMethod) => {34+ const subprocess = execa('ipc-echo.js', {ipc: true});35+ const message = await exchangeMethod(subprocess, [0n]);36+ t.is(message[0], 0n);37+ await subprocess;38+};39+40+test('The "serialization" option defaults to "advanced"', testDefaultSerialization, subprocessSendGetOne);41+test('The "serialization" option defaults to "advanced", exchangeMessage()', testDefaultSerialization, subprocessExchange);42+43+const testJsonSerialization = async (t, exchangeMethod) => {44 const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json'});45 const date = new Date();31- await subprocess.sendMessage(date);32- t.is(await subprocess.getOneMessage(), date.toJSON());46+ t.is(await exchangeMethod(subprocess, date), date.toJSON());47 await subprocess;34-});48+};49 50+test('Can use "serialization: json" option', testJsonSerialization, subprocessSendGetOne);51+test('Can use "serialization: json" option, exchangeMessage()', testJsonSerialization, subprocessExchange);52+53+const testJsonError = async (t, exchangeMethod) => {54+ const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json'});55+ await t.throwsAsync(exchangeMethod(subprocess, [0n]), {message: /serialize a BigInt/});56+ await t.throwsAsync(subprocess);57+};58+59+test('Validates JSON payload with serialization: "json"', testJsonError, subprocessSendGetOne);60+test('Validates JSON payload with serialization: "json", exchangeMessage()', testJsonError, subprocessExchange);61+62 const BIG_PAYLOAD_SIZE = '.'.repeat(1e6);63 38-test('Handles backpressure', async t => {64+const testBackpressure = async (t, exchangeMethod) => {65 const subprocess = execa('ipc-iterate.js', {ipc: true});40- await subprocess.sendMessage(BIG_PAYLOAD_SIZE);66+ await exchangeMethod(subprocess, BIG_PAYLOAD_SIZE);67 t.true(subprocess.send(foobarString));68 const {ipcOutput} = await subprocess;69 t.deepEqual(ipcOutput, [BIG_PAYLOAD_SIZE]);44-});70+};71 46-test('Disconnects IPC on exports.sendMessage() error', async t => {72+test('Handles backpressure', testBackpressure, subprocessSendGetOne);73+test('Handles backpressure, exchangeMessage()', testBackpressure, subprocessExchange);74+75+const testParentDisconnect = async (t, methodName) => {76 const subprocess = execa('ipc-echo-twice.js', {ipc: true});48- await subprocess.sendMessage(foobarString);49- t.is(await subprocess.getOneMessage(), foobarString);77+ t.is(await subprocess.exchangeMessage(foobarString), foobarString);78 51- await t.throwsAsync(subprocess.sendMessage(0n), {52- message: /subprocess.sendMessage\(\)'s argument type is invalid/,53- });79+ const {message} = await t.throwsAsync(subprocess[methodName](0n));80+ t.true(message.includes(`subprocess.${methodName}()'s argument type is invalid`));81 82 const {exitCode, isTerminated, stderr} = await t.throwsAsync(subprocess);83 t.is(exitCode, 1);84 t.false(isTerminated);58- t.true(stderr.includes('Error: getOneMessage() could not complete'));59-});85+ t.true(stderr.includes('Error: exchangeMessage() could not complete'));86+};87 61-test('Disconnects IPC on subprocess.sendMessage() error', async t => {62- const subprocess = execa('ipc-send-error.js', {ipc: true});88+test('Disconnects IPC on exports.sendMessage() error', testParentDisconnect, 'sendMessage');89+test('Disconnects IPC on exports.exchangeMessage() error', testParentDisconnect, 'exchangeMessage');90+91+const testSubprocessDisconnect = async (t, methodName, fixtureName) => {92+ const subprocess = execa(fixtureName, {ipc: true});93 const ipcError = await t.throwsAsync(subprocess.getOneMessage());94 t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));95 96 const {exitCode, isTerminated, stderr} = await t.throwsAsync(subprocess);97 t.is(exitCode, 1);98 t.false(isTerminated);69- t.true(stderr.includes('sendMessage()\'s argument type is invalid'));70-});99+ t.true(stderr.includes(`${methodName}()'s argument type is invalid`));100+};101 72-test('The "serialization" option defaults to "advanced"', async t => {73- const subprocess = execa('ipc-echo.js', {ipc: true});74- await subprocess.sendMessage([0n]);75- const message = await subprocess.getOneMessage();76- t.is(message[0], 0n);77- await subprocess;78-});79-80-test('The "serialization" option can be set to "json"', async t => {81- const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json'});82- await t.throwsAsync(subprocess.sendMessage([0n]), {message: /serialize a BigInt/});83- await t.throwsAsync(subprocess);84-});102+test('Disconnects IPC on subprocess.sendMessage() error', testSubprocessDisconnect, 'sendMessage', 'ipc-send-error.js');103+test('Disconnects IPC on subprocess.exchangeMessage() error', testSubprocessDisconnect, 'exchangeMessage', 'ipc-exchange-error.js');modified:test/ipc/validation.js+43 added-21 removed
19 unmodified lines20 test('Cannot use subprocess.sendMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'sendMessage', stdioIpc);21 test('Cannot use subprocess.getOneMessage() without ipc option', testRequiredIpcSubprocess, 'getOneMessage', {});22 test('Cannot use subprocess.getOneMessage() with ipc: false', testRequiredIpcSubprocess, 'getOneMessage', {ipc: false});23 test('Cannot use subprocess.getOneMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'getOneMessage', stdioIpc);24+test('Cannot use subprocess.exchangeMessage() without ipc option', testRequiredIpcSubprocess, 'exchangeMessage', {});25+test('Cannot use subprocess.exchangeMessage() with ipc: false', testRequiredIpcSubprocess, 'exchangeMessage', {ipc: false});26+test('Cannot use subprocess.exchangeMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'exchangeMessage', stdioIpc);27 test('Cannot use subprocess.getEachMessage() without ipc option', testRequiredIpcSubprocess, 'getEachMessage', {});28 test('Cannot use subprocess.getEachMessage() with ipc: false', testRequiredIpcSubprocess, 'getEachMessage', {ipc: false});29 test('Cannot use subprocess.getEachMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'getEachMessage', stdioIpc);30 5 unmodified lines36 test('Cannot use exports.sendMessage() without ipc option', testRequiredIpcExports, 'sendMessage', {});37 test('Cannot use exports.sendMessage() with ipc: false', testRequiredIpcExports, 'sendMessage', {ipc: false});38 test('Cannot use exports.getOneMessage() without ipc option', testRequiredIpcExports, 'getOneMessage', {});39 test('Cannot use exports.getOneMessage() with ipc: false', testRequiredIpcExports, 'getOneMessage', {ipc: false});40+test('Cannot use exports.exchangeMessage() without ipc option', testRequiredIpcExports, 'exchangeMessage', {});41+test('Cannot use exports.exchangeMessage() with ipc: false', testRequiredIpcExports, 'exchangeMessage', {ipc: false});42 test('Cannot use exports.getEachMessage() without ipc option', testRequiredIpcExports, 'getEachMessage', {});43 test('Cannot use exports.getEachMessage() with ipc: false', testRequiredIpcExports, 'getEachMessage', {ipc: false});44 45 const testPostDisconnection = async (t, methodName) => {4 unmodified lines50 };51 52 test('subprocess.sendMessage() after disconnection', testPostDisconnection, 'sendMessage');53 test('subprocess.getOneMessage() after disconnection', testPostDisconnection, 'getOneMessage');54+test('subprocess.exchangeMessage() after disconnection', testPostDisconnection, 'exchangeMessage');55 test('subprocess.getEachMessage() after disconnection', testPostDisconnection, 'getEachMessage');56 57 const testPostDisconnectionSubprocess = async (t, methodName) => {58 const subprocess = execa('ipc-disconnect.js', [methodName], {ipc: true});3 unmodified lines62 };63 64 test('exports.sendMessage() after disconnection', testPostDisconnectionSubprocess, 'sendMessage');65 test('exports.getOneMessage() after disconnection', testPostDisconnectionSubprocess, 'getOneMessage');66+test('exports.exchangeMessage() after disconnection', testPostDisconnectionSubprocess, 'exchangeMessage');67 test('exports.getEachMessage() after disconnection', testPostDisconnectionSubprocess, 'getEachMessage');68 62-const testInvalidPayload = async (t, serialization, message) => {69+const testInvalidPayload = async (t, methodName, serialization, message) => {70 const subprocess = execa('empty.js', {ipc: true, serialization});64- await t.throwsAsync(subprocess.sendMessage(message), {message: /type is invalid/});71+ await t.throwsAsync(subprocess[methodName](message), {message: /type is invalid/});72 await subprocess;73 };74 75 const cycleObject = {};76 cycleObject.self = cycleObject;77 const toJsonCycle = {toJSON: () => ({test: true, toJsonCycle})};78 72-test('subprocess.sendMessage() cannot send undefined', testInvalidPayload, 'advanced', undefined);73-test('subprocess.sendMessage() cannot send bigints', testInvalidPayload, 'advanced', 0n);74-test('subprocess.sendMessage() cannot send symbols', testInvalidPayload, 'advanced', Symbol('test'));75-test('subprocess.sendMessage() cannot send functions', testInvalidPayload, 'advanced', () => {});76-test('subprocess.sendMessage() cannot send promises', testInvalidPayload, 'advanced', Promise.resolve());77-test('subprocess.sendMessage() cannot send proxies', testInvalidPayload, 'advanced', new Proxy({}, {}));78-test('subprocess.sendMessage() cannot send Intl', testInvalidPayload, 'advanced', new Intl.Collator());79-test('subprocess.sendMessage() cannot send undefined, JSON', testInvalidPayload, 'json', undefined);80-test('subprocess.sendMessage() cannot send bigints, JSON', testInvalidPayload, 'json', 0n);81-test('subprocess.sendMessage() cannot send symbols, JSON', testInvalidPayload, 'json', Symbol('test'));82-test('subprocess.sendMessage() cannot send functions, JSON', testInvalidPayload, 'json', () => {});83-test('subprocess.sendMessage() cannot send cycles, JSON', testInvalidPayload, 'json', cycleObject);84-test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'json', toJsonCycle);79+test('subprocess.sendMessage() cannot send undefined', testInvalidPayload, 'sendMessage', 'advanced', undefined);80+test('subprocess.sendMessage() cannot send bigints', testInvalidPayload, 'sendMessage', 'advanced', 0n);81+test('subprocess.sendMessage() cannot send symbols', testInvalidPayload, 'sendMessage', 'advanced', Symbol('test'));82+test('subprocess.sendMessage() cannot send functions', testInvalidPayload, 'sendMessage', 'advanced', () => {});83+test('subprocess.sendMessage() cannot send promises', testInvalidPayload, 'sendMessage', 'advanced', Promise.resolve());84+test('subprocess.sendMessage() cannot send proxies', testInvalidPayload, 'sendMessage', 'advanced', new Proxy({}, {}));85+test('subprocess.sendMessage() cannot send Intl', testInvalidPayload, 'sendMessage', 'advanced', new Intl.Collator());86+test('subprocess.sendMessage() cannot send undefined, JSON', testInvalidPayload, 'sendMessage', 'json', undefined);87+test('subprocess.sendMessage() cannot send bigints, JSON', testInvalidPayload, 'sendMessage', 'json', 0n);88+test('subprocess.sendMessage() cannot send symbols, JSON', testInvalidPayload, 'sendMessage', 'json', Symbol('test'));89+test('subprocess.sendMessage() cannot send functions, JSON', testInvalidPayload, 'sendMessage', 'json', () => {});90+test('subprocess.sendMessage() cannot send cycles, JSON', testInvalidPayload, 'sendMessage', 'json', cycleObject);91+test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'sendMessage', 'json', toJsonCycle);92+test('subprocess.exchangeMessage() cannot send undefined', testInvalidPayload, 'exchangeMessage', 'advanced', undefined);93+test('subprocess.exchangeMessage() cannot send bigints', testInvalidPayload, 'exchangeMessage', 'advanced', 0n);94+test('subprocess.exchangeMessage() cannot send symbols', testInvalidPayload, 'exchangeMessage', 'advanced', Symbol('test'));95+test('subprocess.exchangeMessage() cannot send functions', testInvalidPayload, 'exchangeMessage', 'advanced', () => {});96+test('subprocess.exchangeMessage() cannot send promises', testInvalidPayload, 'exchangeMessage', 'advanced', Promise.resolve());97+test('subprocess.exchangeMessage() cannot send proxies', testInvalidPayload, 'exchangeMessage', 'advanced', new Proxy({}, {}));98+test('subprocess.exchangeMessage() cannot send Intl', testInvalidPayload, 'exchangeMessage', 'advanced', new Intl.Collator());99+test('subprocess.exchangeMessage() cannot send undefined, JSON', testInvalidPayload, 'exchangeMessage', 'json', undefined);100+test('subprocess.exchangeMessage() cannot send bigints, JSON', testInvalidPayload, 'exchangeMessage', 'json', 0n);101+test('subprocess.exchangeMessage() cannot send symbols, JSON', testInvalidPayload, 'exchangeMessage', 'json', Symbol('test'));102+test('subprocess.exchangeMessage() cannot send functions, JSON', testInvalidPayload, 'exchangeMessage', 'json', () => {});103+test('subprocess.exchangeMessage() cannot send cycles, JSON', testInvalidPayload, 'exchangeMessage', 'json', cycleObject);104+test('subprocess.exchangeMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'exchangeMessage', 'json', toJsonCycle);105 86-test('exports.sendMessage() validates payload', async t => {87- const subprocess = execa('ipc-echo-item.js', {ipc: true});106+const testSubprocessInvalidPayload = async (t, methodName, fixtureName) => {107+ const subprocess = execa(fixtureName, {ipc: true});108 await subprocess.sendMessage([undefined]);89- await t.throwsAsync(subprocess, {90- message: /sendMessage\(\)'s argument type is invalid/,91- });92-});109+ const {message} = await t.throwsAsync(subprocess);110+ t.true(message.includes(`${methodName}()'s argument type is invalid`));111+};112+113+test('exports.sendMessage() validates payload', testSubprocessInvalidPayload, 'sendMessage', 'ipc-echo-item.js');114+test('exports.exchangeMessage() validates payload', testSubprocessInvalidPayload, 'exchangeMessage', 'ipc-echo-item-exchange.js');modified:test/methods/node.js+1 added-2 removed
223 unmodified lines224 225 const testIpc = async (t, execaMethod, options) => {226 const subprocess = execaMethod('ipc-echo.js', [], options);227 228- await subprocess.sendMessage(foobarString);229- t.is(await subprocess.getOneMessage(), foobarString);228+ t.is(await subprocess.exchangeMessage(foobarString), foobarString);229 230 const {stdio} = await subprocess;231 t.is(stdio.length, 4);232 t.is(stdio[3], undefined);55 unmodified linesadded:test-d/ipc/exchange.test-d.ts+65 added
1+import {expectType, expectError} from 'tsd';2+import {3+ exchangeMessage,4+ execa,5+ type Message,6+ type Options,7+} from '../../index.js';8+9+const subprocess = execa('test', {ipc: true});10+expectType<Promise<Message<'advanced'>>>(subprocess.exchangeMessage(''));11+const jsonSubprocess = execa('test', {ipc: true, serialization: 'json'});12+expectType<Promise<Message<'json'>>>(jsonSubprocess.exchangeMessage(''));13+expectType<Promise<Message>>(exchangeMessage(''));14+15+expectError(await subprocess.exchangeMessage());16+expectError(await exchangeMessage());17+expectError(await subprocess.exchangeMessage(undefined));18+expectError(await exchangeMessage(undefined));19+expectError(await subprocess.exchangeMessage(0n));20+expectError(await exchangeMessage(0n));21+expectError(await subprocess.exchangeMessage(Symbol('test')));22+expectError(await exchangeMessage(Symbol('test')));23+expectError(await subprocess.exchangeMessage('', ''));24+expectError(await exchangeMessage('', ''));25+expectError(await subprocess.exchangeMessage('', {}, ''));26+expectError(await exchangeMessage('', {}, ''));27+28+await execa('test', {ipcInput: ''}).exchangeMessage('');29+await execa('test', {ipcInput: '' as Message}).exchangeMessage('');30+await execa('test', {} as Options).exchangeMessage?.('');31+await execa('test', {ipc: true as boolean}).exchangeMessage?.('');32+await execa('test', {ipcInput: '' as '' | undefined}).exchangeMessage?.('');33+34+expectType<undefined>(execa('test').exchangeMessage);35+expectType<undefined>(execa('test', {}).exchangeMessage);36+expectType<undefined>(execa('test', {ipc: false}).exchangeMessage);37+expectType<undefined>(execa('test', {ipcInput: undefined}).exchangeMessage);38+expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).exchangeMessage);39+40+await subprocess.exchangeMessage('', {filter: undefined} as const);41+await subprocess.exchangeMessage('', {filter: (message: Message<'advanced'>) => true} as const);42+await jsonSubprocess.exchangeMessage('', {filter: (message: Message<'json'>) => true} as const);43+await jsonSubprocess.exchangeMessage('', {filter: (message: Message<'advanced'>) => true} as const);44+await subprocess.exchangeMessage('', {filter: (message: Message<'advanced'> | bigint) => true} as const);45+await subprocess.exchangeMessage('', {filter: () => true} as const);46+expectError(await subprocess.exchangeMessage('', {filter: (message: Message<'advanced'>) => ''} as const));47+// eslint-disable-next-line @typescript-eslint/no-empty-function48+expectError(await subprocess.exchangeMessage('', {filter(message: Message<'advanced'>) {}} as const));49+expectError(await subprocess.exchangeMessage('', {filter: (message: Message<'json'>) => true} as const));50+expectError(await subprocess.exchangeMessage('', {filter: (message: '') => true} as const));51+expectError(await subprocess.exchangeMessage('', {filter: true} as const));52+expectError(await subprocess.exchangeMessage('', {unknownOption: true} as const));53+54+await exchangeMessage('', {filter: undefined} as const);55+await exchangeMessage('', {filter: (message: Message) => true} as const);56+await exchangeMessage('', {filter: (message: Message<'advanced'>) => true} as const);57+await exchangeMessage('', {filter: (message: Message | bigint) => true} as const);58+await exchangeMessage('', {filter: () => true} as const);59+expectError(await exchangeMessage('', {filter: (message: Message) => ''} as const));60+// eslint-disable-next-line @typescript-eslint/no-empty-function61+expectError(await exchangeMessage('', {filter(message: Message) {}} as const));62+expectError(await exchangeMessage('', {filter: (message: Message<'json'>) => true} as const));63+expectError(await exchangeMessage('', {filter: (message: '') => true} as const));64+expectError(await exchangeMessage('', {filter: true} as const));65+expectError(await exchangeMessage('', {unknownOption: true} as const));modified:test-d/ipc/get-one.test-d.ts+2 added
12 unmodified lines13 expectType<Promise<Message>>(getOneMessage());14 15 expectError(await subprocess.getOneMessage(''));16 expectError(await getOneMessage(''));17+expectError(await subprocess.getOneMessage({}, ''));18+expectError(await getOneMessage({}, ''));19 20 await execa('test', {ipcInput: ''}).getOneMessage();21 await execa('test', {ipcInput: '' as Message}).getOneMessage();22 await execa('test', {} as Options).getOneMessage?.();35 unmodified linesmodified:test-d/ipc/message.test-d.ts+27 added-1 removed
1 import {File} from 'node:buffer';2 import {expectAssignable, expectNotAssignable} from 'tsd';3-import {sendMessage, type Message} from '../../index.js';3+import {sendMessage, exchangeMessage, type Message} from '../../index.js';4 5 await sendMessage('');6+await exchangeMessage('');7 expectAssignable<Message>('');8 expectAssignable<Message<'advanced'>>('');9 expectAssignable<Message<'json'>>('');10 11 await sendMessage(0);12+await exchangeMessage(0);13 expectAssignable<Message>(0);14 expectAssignable<Message<'advanced'>>(0);15 expectAssignable<Message<'json'>>(0);16 17 await sendMessage(true);18+await exchangeMessage(true);19 expectAssignable<Message>(true);20 expectAssignable<Message<'advanced'>>(true);21 expectAssignable<Message<'json'>>(true);22 23 await sendMessage([] as const);24+await exchangeMessage([] as const);25 expectAssignable<Message>([] as const);26 expectAssignable<Message<'advanced'>>([] as const);27 expectAssignable<Message<'json'>>([] as const);28 29 await sendMessage([true] as const);30+await exchangeMessage([true] as const);31 expectAssignable<Message>([true] as const);32 expectAssignable<Message<'advanced'>>([true] as const);33 expectAssignable<Message<'json'>>([true] as const);34 35 await sendMessage([undefined] as const);36+await exchangeMessage([undefined] as const);37 expectAssignable<Message>([undefined] as const);38 expectAssignable<Message<'advanced'>>([undefined] as const);39 expectNotAssignable<Message<'json'>>([undefined] as const);40 41 await sendMessage([0n] as const);42+await exchangeMessage([0n] as const);43 expectAssignable<Message>([0n] as const);44 expectAssignable<Message<'advanced'>>([0n] as const);45 expectNotAssignable<Message<'json'>>([0n] as const);46 47 await sendMessage({} as const);48+await exchangeMessage({} as const);49 expectAssignable<Message>({} as const);50 expectAssignable<Message<'advanced'>>({} as const);51 expectAssignable<Message<'json'>>({} as const);52 53 await sendMessage({test: true} as const);54+await exchangeMessage({test: true} as const);55 expectAssignable<Message>({test: true} as const);56 expectAssignable<Message<'advanced'>>({test: true} as const);57 expectAssignable<Message<'json'>>({test: true} as const);58 59 await sendMessage({test: undefined} as const);60+await exchangeMessage({test: undefined} as const);61 expectAssignable<Message>({test: undefined} as const);62 expectAssignable<Message<'advanced'>>({test: undefined} as const);63 expectNotAssignable<Message<'json'>>({test: undefined} as const);64 65 await sendMessage({test: 0n} as const);66+await exchangeMessage({test: 0n} as const);67 expectAssignable<Message>({test: 0n} as const);68 expectAssignable<Message<'advanced'>>({test: 0n} as const);69 expectNotAssignable<Message<'json'>>({test: 0n} as const);70 71 await sendMessage(null);72+await exchangeMessage(null);73 expectAssignable<Message>(null);74 expectAssignable<Message<'advanced'>>(null);75 expectAssignable<Message<'json'>>(null);76 77 await sendMessage(Number.NaN);78+await exchangeMessage(Number.NaN);79 expectAssignable<Message>(Number.NaN);80 expectAssignable<Message<'advanced'>>(Number.NaN);81 expectAssignable<Message<'json'>>(Number.NaN);82 83 await sendMessage(Number.POSITIVE_INFINITY);84+await exchangeMessage(Number.POSITIVE_INFINITY);85 expectAssignable<Message>(Number.POSITIVE_INFINITY);86 expectAssignable<Message<'advanced'>>(Number.POSITIVE_INFINITY);87 expectAssignable<Message<'json'>>(Number.POSITIVE_INFINITY);88 89 await sendMessage(new Map());90+await exchangeMessage(new Map());91 expectAssignable<Message>(new Map());92 expectAssignable<Message<'advanced'>>(new Map());93 expectNotAssignable<Message<'json'>>(new Map());94 95 await sendMessage(new Set());96+await exchangeMessage(new Set());97 expectAssignable<Message>(new Set());98 expectAssignable<Message<'advanced'>>(new Set());99 expectNotAssignable<Message<'json'>>(new Set());100 101 await sendMessage(new Date());102+await exchangeMessage(new Date());103 expectAssignable<Message>(new Date());104 expectAssignable<Message<'advanced'>>(new Date());105 expectNotAssignable<Message<'json'>>(new Date());106 107 await sendMessage(/regexp/);108+await exchangeMessage(/regexp/);109 expectAssignable<Message>(/regexp/);110 expectAssignable<Message<'advanced'>>(/regexp/);111 expectNotAssignable<Message<'json'>>(/regexp/);112 113 await sendMessage(new Blob());114+await exchangeMessage(new Blob());115 expectAssignable<Message>(new Blob());116 expectAssignable<Message<'advanced'>>(new Blob());117 expectNotAssignable<Message<'json'>>(new Blob());118 119 await sendMessage(new File([], ''));120+await exchangeMessage(new File([], ''));121 expectAssignable<Message>(new File([], ''));122 expectAssignable<Message<'advanced'>>(new File([], ''));123 expectNotAssignable<Message<'json'>>(new File([], ''));124 125 await sendMessage(new DataView(new ArrayBuffer(0)));126+await exchangeMessage(new DataView(new ArrayBuffer(0)));127 expectAssignable<Message>(new DataView(new ArrayBuffer(0)));128 expectAssignable<Message<'advanced'>>(new DataView(new ArrayBuffer(0)));129 expectNotAssignable<Message<'json'>>(new DataView(new ArrayBuffer(0)));130 131 await sendMessage(new ArrayBuffer(0));132+await exchangeMessage(new ArrayBuffer(0));133 expectAssignable<Message>(new ArrayBuffer(0));134 expectAssignable<Message<'advanced'>>(new ArrayBuffer(0));135 expectNotAssignable<Message<'json'>>(new ArrayBuffer(0));136 137 await sendMessage(new SharedArrayBuffer(0));138+await exchangeMessage(new SharedArrayBuffer(0));139 expectAssignable<Message>(new SharedArrayBuffer(0));140 expectAssignable<Message<'advanced'>>(new SharedArrayBuffer(0));141 expectNotAssignable<Message<'json'>>(new SharedArrayBuffer(0));142 143 await sendMessage(new Uint8Array());144+await exchangeMessage(new Uint8Array());145 expectAssignable<Message>(new Uint8Array());146 expectAssignable<Message<'advanced'>>(new Uint8Array());147 expectNotAssignable<Message<'json'>>(new Uint8Array());148 149 await sendMessage(AbortSignal.abort());150+await exchangeMessage(AbortSignal.abort());151 expectAssignable<Message>(AbortSignal.abort());152 expectAssignable<Message<'advanced'>>(AbortSignal.abort());153 expectNotAssignable<Message<'json'>>(AbortSignal.abort());154 155 await sendMessage(new Error('test'));156+await exchangeMessage(new Error('test'));157 expectAssignable<Message>(new Error('test'));158 expectAssignable<Message<'advanced'>>(new Error('test'));159 expectNotAssignable<Message<'json'>>(new Error('test'));modified:types/arguments/options.d.ts+1 added-1 removed
197 unmodified lines198 */199 readonly buffer?: FdGenericOption<boolean>;200 201 /**202- Enables exchanging messages with the subprocess using `subprocess.sendMessage(message)`, `subprocess.getOneMessage()` and `subprocess.getEachMessage()`.202+ Enables exchanging messages with the subprocess using `subprocess.sendMessage(message)`, `subprocess.getOneMessage()`, `subprocess.exchangeMessage(message)` and `subprocess.getEachMessage()`.203 204 The subprocess must be a Node.js file.205 206 @default `true` if either the `node` option or the `ipcInput` option is set, `false` otherwise176 unmodified linesmodified:types/methods/main-async.d.ts+6 added-6 removed
185 unmodified lines186 // parent.js187 import {execaNode} from 'execa';188 189 const subprocess = execaNode`child.js`;190-console.log(await subprocess.getOneMessage()); // 'Hello from child'191-await subprocess.sendMessage('Hello from parent');192-const result = await subprocess;190+const message = await subprocess.exchangeMessage('Hello from parent');191+console.log(message); // 'Hello from child'192 ```193 194 ```195 // child.js197-import {sendMessage, getOneMessage} from 'execa';196+import {getOneMessage, sendMessage} from 'execa';197 199-await sendMessage('Hello from child');200-console.log(await getOneMessage()); // 'Hello from parent'198+const message = await getOneMessage(); // 'Hello from parent'199+const newMessage = message.replace('parent', 'child'); // 'Hello from child'200+await sendMessage(newMessage);201 ```202 203 @example <caption>Any input type</caption>204 105 unmodified linesmodified:types/ipc.d.ts+17 added-2 removed
16 unmodified lines17 | readonly JsonMessage[]18 | {readonly [key: string | number]: JsonMessage};19 20 /**21-Type of messages exchanged between a process and its subprocess using `sendMessage()`, `getOneMessage()` and `getEachMessage()`.21+Type of messages exchanged between a process and its subprocess using `sendMessage()`, `getOneMessage()`, `exchangeMessage()` and `getEachMessage()`.22 23 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.24 */25 export type Message<26 Serialization extends Options['serialization'] = Options['serialization'],27 > = Serialization extends 'json' ? JsonMessage : AdvancedMessage;28 29 /**30-Options to `getOneMessage()` and `subprocess.getOneMessage()`30+Options to `getOneMessage()`, `exchangeMessage()`, `subprocess.getOneMessage()` and `subprocess.exchangeMessage()`31 */32 type GetOneMessageOptions<33 Serialization extends Options['serialization'],34 > = {18 unmodified lines53 */54 export function getOneMessage(getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>): Promise<Message>;55 56 /**57+Send a `message` to the parent process, then receive a response from it.58+59+This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.60+*/61+export function exchangeMessage(message: Message, getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>): Promise<Message>;62+63+/**64 Iterate over each `message` from the parent process.65 66 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.67 */19 unmodified lines87 */88 getOneMessage(getOneMessageOptions?: GetOneMessageOptions<Serialization>): Promise<Message<Serialization>>;89 90 /**91+ Send a `message` to the subprocess, then receive a response from it.92+93+ This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.94+ */95+ exchangeMessage(message: Message<Serialization>, getOneMessageOptions?: GetOneMessageOptions<Serialization>): Promise<Message<Serialization>>;96+97+ /**98 Iterate over each `message` from the subprocess.99 100 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.101 */4 unmodified lines106 // At type check time, they are typed as `undefined` to prevent calling them.107 : {108 sendMessage: undefined;109 getOneMessage: undefined;110+ exchangeMessage: undefined;111 getEachMessage: undefined;112 };113 114 // Whether IPC is enabled, based on the `ipc` and `ipcInput` options15 unmodified linesmodified:index.d.ts+1 added
18 unmodified lines19 20 export {21 sendMessage,22 getOneMessage,23+ exchangeMessage,24 getEachMessage,25 type Message,26 } from './types/ipc.js';modified:index.js+12 added-2 removed
12 unmodified lines13 export const execaCommandSync = createExeca(mapCommandSync);14 export const execaNode = createExeca(mapNode);15 export const $ = createExeca(mapScriptAsync, {}, deepScriptOptions, setScriptSync);16 17-const {sendMessage, getOneMessage, getEachMessage} = getIpcExport();18-export {sendMessage, getOneMessage, getEachMessage};17+const {18+ sendMessage,19+ getOneMessage,20+ exchangeMessage,21+ getEachMessage,22+} = getIpcExport();23+export {24+ sendMessage,25+ getOneMessage,26+ exchangeMessage,27+ getEachMessage,28+};modified:readme.md+6 added-6 removed
268 unmodified lines269 // parent.js270 import {execaNode} from 'execa';271 272 const subprocess = execaNode`child.js`;273-console.log(await subprocess.getOneMessage()); // 'Hello from child'274-await subprocess.sendMessage('Hello from parent');275-const result = await subprocess;273+const message = await subprocess.exchangeMessage('Hello from parent');274+console.log(message); // 'Hello from child'275 ```276 277 ```js278 // child.js280-import {sendMessage, getOneMessage} from 'execa';279+import {getOneMessage, sendMessage} from 'execa';280 282-await sendMessage('Hello from child');283-console.log(await getOneMessage()); // 'Hello from parent'281+const message = await getOneMessage(); // 'Hello from parent'282+const newMessage = message.replace('parent', 'child'); // 'Hello from child'283+await sendMessage(newMessage);284 ```285 286 #### Any input type287 104 unmodified lines