Skip to content
Myr

Add `ipcInput` option (#1068)

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

authored by ehmicky · committed by GitHub · parent 69152ec · Browse files · 27 files+542 added−173 removed
This commit

State

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

Diff stats

27 files+542 added−173 removed

  • tests:+123 added−82 removed
  • other:+419 added−91 removed

27 files+542 added−173 removed

modified:docs/api.md+13 added-1 removed
896 unmodified lines
897898### options.ipc899900_Type:_ `boolean`\901_Default:_ `true` if the [`node`](#optionsnode) option is enabled, `false` otherwise901_Default:_ `true` if either the [`node`](#optionsnode) option or the [`ipcInput`](#optionsipcinput) is set, `false` otherwise902903Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessage) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).904905The subprocess must be a Node.js file.906907[More info.](ipc.md)908909### options.serialization910
3 unmodified lines
914Specify the kind of serialization used for sending messages between subprocesses when using the [`ipc`](#optionsipc) option.915916[More info.](ipc.md#message-type)917918### options.ipcInput919920_Type_: [`Message`](ipc.md#message-type)921922Sends an IPC message when the subprocess starts.923924The subprocess must be a [Node.js file](#optionsnode). The value's [type](ipc.md#message-type) depends on the [`serialization`](#optionsserialization) option.925926More info [here](ipc.md#send-an-initial-message) and [there](input.md#any-input-type).927928### options.verbose929930_Type:_ `'none' | 'short' | 'full'`\931_Default:_ `'none'`
175 unmodified lines
modified:docs/input.md+22 added
modified:docs/ipc.md+23 added-1 removed
6 unmodified lines
7# 📞 Inter-process communication89## Exchanging messages1011When 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.11When 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).1213The `ipc` option defaults to `true` when using [`execaNode()`](node.md#run-nodejs-files) or the [`node`](node.md#run-nodejs-files) option.1415The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessage). The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage) and [`getOneMessage()`](api.md#getonemessage) instead.
72 unmodified lines
88await runBuild();89await sendMessage({kind: 'stop', timestamp: new Date()});90```9192## Send an initial message9394The [`ipcInput`](api.md#optionsipcinput) option sends a message to the [Node.js subprocess](node.md) when it starts.9596```js97// main.js98import {execaNode} from 'execa';99100const ipcInput = [101 {task: 'lint', ignore: /test\.js/},102 {task: 'copy', files: new Set(['main.js', 'index.js']),103}];104await execaNode({ipcInput})`build.js`;105```106107```js108// build.js109import {getOneMessage} from 'execa';110111const ipcInput = await getOneMessage();112```113114## Message type115116By default, messages are serialized using [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). This supports most types including objects, arrays, `Error`, `Date`, `RegExp`, `Map`, `Set`, `bigint`, `Uint8Array`, and circular references. This throws when passing functions, symbols or promises (including inside an object or array).117
17 unmodified lines
modified:lib/arguments/options.js+5 added-1 removed
4 unmodified lines
5import {normalizeForceKillAfterDelay} from '../terminate/kill.js';6import {normalizeKillSignal} from '../terminate/signal.js';7import {validateTimeout} from '../terminate/timeout.js';8import {handleNodeOption} from '../methods/node.js';9import {validateIpcInputOption} from '../ipc/ipc-input.js';10import {validateEncoding, BINARY_ENCODINGS} from './encoding-option.js';11import {normalizeCwd} from './cwd.js';12import {normalizeFileUrl} from './file-url.js';13import {normalizeFdSpecificOptions} from './specific.js';
9 unmodified lines
23 const fdOptions = normalizeFdSpecificOptions(initialOptions);24 const options = addDefaultOptions(fdOptions);25 validateTimeout(options);26 validateEncoding(options);27 validateIpcInputOption(options);28 options.shell = normalizeFileUrl(options.shell);29 options.env = getEnv(options);30 options.killSignal = normalizeKillSignal(options.killSignal);31 options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);
18 unmodified lines
50 all = false,51 windowsHide = true,52 killSignal = 'SIGTERM',53 forceKillAfterDelay = true,52 ipc = false,54 ipcInput,55 ipc = ipcInput !== undefined,56 serialization = 'advanced',57 ...options58}) => ({59 ...options,
7 unmodified lines
67 all,68 windowsHide,69 killSignal,70 forceKillAfterDelay,71 ipcInput,72 ipc,73 serialization,74});75
15 unmodified lines
added:lib/ipc/buffer-messages.js+43 added
added:lib/ipc/ipc-input.js+44 added
deleted:lib/ipc/messages.js-43 removed
modified:lib/methods/main-sync.js+5 added-1 removed
55 unmodified lines
56// Options normalization logic specific to sync methods57const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;5859// Options validation logic specific to sync methods60const validateSyncOptions = ({ipc, detached, cancelSignal}) => {60const validateSyncOptions = ({ipc, ipcInput, detached, cancelSignal}) => {61 if (ipcInput) {62 throwInvalidSyncOption('ipcInput');63 }6465 if (ipc) {66 throwInvalidSyncOption('ipc: true');67 }68
99 unmodified lines
modified:lib/resolve/wait-subprocess.js+4 added-1 removed
2 unmodified lines
3import {throwOnTimeout} from '../terminate/timeout.js';4import {isStandardStream} from '../utils/standard-stream.js';5import {TRANSFORM_TYPES} from '../stdio/type.js';6import {getBufferedData} from '../io/contents.js';7import {waitForIpcMessages} from '../ipc/messages.js';7import {waitForIpcMessages} from '../ipc/buffer-messages.js';8import {sendIpcInput} from '../ipc/ipc-input.js';9import {waitForAllStream} from './all-async.js';10import {waitForStdioStreams} from './stdio.js';11import {waitForExit, waitForSuccessfulExit} from './exit-async.js';12import {waitForStream} from './wait-stream.js';
8 unmodified lines
21 lines,22 timeoutDuration: timeout,23 stripFinalNewline,24 ipc,25 ipcInput,26 },27 context,28 verboseInfo,29 fileDescriptors,
48 unmodified lines
78 ipc,79 ipcMessages,80 verboseInfo,81 }),82 sendIpcInput(subprocess, ipcInput),83 ...originalPromises,84 ...customStreamsEndPromises,85 ]),86 onInternalError,
38 unmodified lines
added:test/ipc/buffer-messages.js+58 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {foobarString, foobarArray} from '../helpers/input.js';56setFixtureDirectory();78const testResultIpc = async (t, options) => {9 const {ipc} = await execa('ipc-send-twice.js', {...options, ipc: true});10 t.deepEqual(ipc, foobarArray);11};1213test('Sets result.ipc', testResultIpc, {});14test('Sets result.ipc, fd-specific buffer', testResultIpc, {buffer: {stdout: false}});1516const testResultNoBuffer = async (t, options) => {17 const {ipc} = await execa('ipc-send.js', {...options, ipc: true});18 t.deepEqual(ipc, []);19};2021test('Sets empty result.ipc if buffer is false', testResultNoBuffer, {buffer: false});22test('Sets empty result.ipc if buffer is false, fd-specific buffer', testResultNoBuffer, {buffer: {ipc: false}});2324test('Sets empty result.ipc if ipc is false', async t => {25 const {ipc} = await execa('empty.js');26 t.deepEqual(ipc, []);27});2829test('Sets empty result.ipc, sync', t => {30 const {ipc} = execaSync('empty.js');31 t.deepEqual(ipc, []);32});3334const testErrorIpc = async (t, options) => {35 const {ipc} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));36 t.deepEqual(ipc, [foobarString]);37};3839test('Sets error.ipc', testErrorIpc, {});40test('Sets error.ipc, fd-specific buffer', testErrorIpc, {buffer: {stdout: false}});4142const testErrorNoBuffer = async (t, options) => {43 const {ipc} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));44 t.deepEqual(ipc, []);45};4647test('Sets empty error.ipc if buffer is false', testErrorNoBuffer, {buffer: false});48test('Sets empty error.ipc if buffer is false, fd-specific buffer', testErrorNoBuffer, {buffer: {ipc: false}});4950test('Sets empty error.ipc if ipc is false', async t => {51 const {ipc} = await t.throwsAsync(execa('fail.js'));52 t.deepEqual(ipc, []);53});5455test('Sets empty error.ipc, sync', t => {56 const {ipc} = t.throws(() => execaSync('fail.js'));57 t.deepEqual(ipc, []);58});
modified:test/ipc/get-one.js+1 added-2 removed
107 unmodified lines
108test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false);109test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true);110111test('"error" event interrupts result.ipc', async t => {112 const subprocess = execa('ipc-echo-twice.js', {ipc: true});113 await subprocess.sendMessage(foobarString);112 const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});113 t.is(await subprocess.getOneMessage(), foobarString);114115 const cause = new Error(foobarString);116 subprocess.emit('error', cause);
77 unmodified lines
added:test/ipc/ipc-input.js+46 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {foobarString} from '../helpers/input.js';56setFixtureDirectory();78const testSuccess = async (t, options) => {9 const {ipc} = await execa('ipc-echo.js', {ipcInput: foobarString, ...options});10 t.deepEqual(ipc, [foobarString]);11};1213test('Sends a message with the "ipcInput" option, ipc undefined', testSuccess, {});14test('Sends a message with the "ipcInput" option, ipc true', testSuccess, {ipc: true});1516test('Cannot use the "ipcInput" option with "ipc" false', t => {17 t.throws(() => {18 execa('empty.js', {ipcInput: foobarString, ipc: false});19 }, {message: /unless the `ipc` option is `true`/});20});2122test('Cannot use the "ipcInput" option with execaSync()', t => {23 t.throws(() => {24 execaSync('empty.js', {ipcInput: foobarString});25 }, {message: /The "ipcInput" option cannot be used with synchronous/});26});2728test('Invalid "ipcInput" option v8 format', t => {29 const {message} = t.throws(() => {30 execa('empty.js', {ipcInput() {}});31 });32 t.is(message, 'The `ipcInput` option is not serializable with a structured clone.\nipcInput() {} could not be cloned.');33});3435test('Invalid "ipcInput" option JSON format', t => {36 const {message} = t.throws(() => {37 execa('empty.js', {ipcInput: 0n, serialization: 'json'});38 });39 t.is(message, 'The `ipcInput` option is not serializable with JSON.\nDo not know how to serialize a BigInt');40});4142test('Handles "ipcInput" option during sending', async t => {43 await t.throwsAsync(execa('empty.js', {ipcInput: 0n}), {44 message: /The "message" argument must be one of type string/,45 });46});
deleted:test/ipc/messages.js-58 removed
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {foobarString, foobarArray} from '../helpers/input.js';56setFixtureDirectory();78const testResultIpc = async (t, options) => {9 const {ipc} = await execa('ipc-send-twice.js', {...options, ipc: true});10 t.deepEqual(ipc, foobarArray);11};1213test('Sets result.ipc', testResultIpc, {});14test('Sets result.ipc, fd-specific buffer', testResultIpc, {buffer: {stdout: false}});1516const testResultNoBuffer = async (t, options) => {17 const {ipc} = await execa('ipc-send.js', {...options, ipc: true});18 t.deepEqual(ipc, []);19};2021test('Sets empty result.ipc if buffer is false', testResultNoBuffer, {buffer: false});22test('Sets empty result.ipc if buffer is false, fd-specific buffer', testResultNoBuffer, {buffer: {ipc: false}});2324test('Sets empty result.ipc if ipc is false', async t => {25 const {ipc} = await execa('empty.js');26 t.deepEqual(ipc, []);27});2829test('Sets empty result.ipc, sync', t => {30 const {ipc} = execaSync('empty.js');31 t.deepEqual(ipc, []);32});3334const testErrorIpc = async (t, options) => {35 const {ipc} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));36 t.deepEqual(ipc, [foobarString]);37};3839test('Sets error.ipc', testErrorIpc, {});40test('Sets error.ipc, fd-specific buffer', testErrorIpc, {buffer: {stdout: false}});4142const testErrorNoBuffer = async (t, options) => {43 const {ipc} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));44 t.deepEqual(ipc, []);45};4647test('Sets empty error.ipc if buffer is false', testErrorNoBuffer, {buffer: false});48test('Sets empty error.ipc if buffer is false, fd-specific buffer', testErrorNoBuffer, {buffer: {ipc: false}});4950test('Sets empty error.ipc if ipc is false', async t => {51 const {ipc} = await t.throwsAsync(execa('fail.js'));52 t.deepEqual(ipc, []);53});5455test('Sets empty error.ipc, sync', t => {56 const {ipc} = t.throws(() => execaSync('fail.js'));57 t.deepEqual(ipc, []);58});
modified:test/ipc/send.js+14 added
66 unmodified lines
67 t.is(exitCode, 1);68 t.false(isTerminated);69 t.true(stderr.includes('sendMessage()\'s argument type is invalid'));70});7172test('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});7980test('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});
modified:test/methods/node.js-14 removed
284 unmodified lines
285286test('Cannot use "shell: true" - execaNode()', testNoShell, execaNode);287test('Cannot use "shell: true" - "node" option', testNoShell, runWithNodeOption);288test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);289290test('The "serialization" option defaults to "advanced"', async t => {291 const subprocess = execa('node', ['ipc-echo.js'], {ipc: true});292 await subprocess.sendMessage([0n]);293 const message = await subprocess.getOneMessage();294 t.is(message[0], 0n);295 await subprocess;296});297298test('The "serialization" option can be set to "json"', async t => {299 const subprocess = execa('node', ['ipc-echo.js'], {ipc: true, serialization: 'json'});300 await t.throwsAsync(subprocess.sendMessage([0n]), {message: /serialize a BigInt/});301 await t.throwsAsync(subprocess);302});
modified:test/return/message.js+4 added-8 removed
93 unmodified lines
94 const {originalMessage} = await t.throwsAsync(execa('noop.js', {uid: true}));95 t.is(originalMessage, 'The "options.uid" property must be int32. Received type boolean (true)');96});9798const testIpcMessage = async (t, doubles, input, returnedMessage) => {98const testIpcMessage = async (t, doubles, ipcInput, returnedMessage) => {99 const fixtureName = doubles ? 'ipc-echo-twice-fail.js' : 'ipc-echo-fail.js';100 const subprocess = execa(fixtureName, {ipc: true});101 await subprocess.sendMessage(input);102 const {exitCode, message, ipc} = await t.throwsAsync(subprocess);100 const {exitCode, message, ipc} = await t.throwsAsync(execa(fixtureName, {ipcInput}));101 t.is(exitCode, 1);102 t.true(message.endsWith(`\n\n${doubles ? `${returnedMessage}\n${returnedMessage}` : returnedMessage}`));105 t.deepEqual(ipc, doubles ? [input, input] : [input]);103 t.deepEqual(ipc, doubles ? [ipcInput, ipcInput] : [ipcInput]);104};105106test('error.message contains IPC messages, single string', testIpcMessage, false, foobarString, foobarString);107test('error.message contains IPC messages, two strings', testIpcMessage, true, foobarString, foobarString);
2 unmodified lines
110test('error.message contains IPC messages, multiline string', testIpcMessage, false, `${foobarString}\n${foobarString}`, `${foobarString}\n${foobarString}`);111test('error.message contains IPC messages, control characters', testIpcMessage, false, '\0', '\\u0000');112113test('error.message does not contain IPC messages, buffer false', async t => {116 const subprocess = execa('ipc-echo-fail.js', {ipc: true, buffer: false});117 await subprocess.sendMessage(foobarString);118 const {exitCode, message, ipc} = await t.throwsAsync(subprocess);114 const {exitCode, message, ipc} = await t.throwsAsync(execa('ipc-echo-fail.js', {ipcInput: foobarString, buffer: false}));115 t.is(exitCode, 1);116 t.true(message.endsWith('ipc-echo-fail.js'));117 t.deepEqual(ipc, []);118});
modified:test-d/arguments/options.test-d.ts+9 added
199 unmodified lines
200expectError(execaSync('unicorns', {serialization: 'advanced'}));201expectError(await execa('unicorns', {serialization: 'other'}));202expectError(execaSync('unicorns', {serialization: 'other'}));203204await execa('unicorns', {ipcInput: ''});205expectError(execaSync('unicorns', {ipcInput: ''}));206await execa('unicorns', {ipcInput: {}});207expectError(execaSync('unicorns', {ipcInput: {}}));208await execa('unicorns', {ipcInput: undefined});209execaSync('unicorns', {ipcInput: undefined});210expectError(await execa('unicorns', {ipcInput: 0n}));211expectError(execaSync('unicorns', {ipcInput: 0n}));212213await execa('unicorns', {detached: true});214expectError(execaSync('unicorns', {detached: true}));215expectError(await execa('unicorns', {detached: 'true'}));216expectError(execaSync('unicorns', {detached: 'true'}));
5 unmodified lines
modified:test-d/ipc/get-each.test-d.ts+18 added-3 removed
1import {expectType, expectError} from 'tsd';2import {getEachMessage, execa, type Message} from '../../index.js';2import {3 getEachMessage,4 execa,5 type Message,6 type Options,7} from '../../index.js';89for await (const message of getEachMessage()) {10 expectType<Message>(message);11}
10 unmodified lines
22 expectType<Message<'json'>>(message);23}2425expectError(subprocess.getEachMessage(''));21expectError(await execa('test').getEachMessage());22expectError(await execa('test', {ipc: false}).getEachMessage());2627execa('test', {ipcInput: ''}).getEachMessage();28execa('test', {ipcInput: '' as Message}).getEachMessage();29execa('test', {} as Options).getEachMessage?.();30execa('test', {ipc: true as boolean}).getEachMessage?.();31execa('test', {ipcInput: '' as '' | undefined}).getEachMessage?.();3233expectType<undefined>(execa('test').getEachMessage);34expectType<undefined>(execa('test', {}).getEachMessage);35expectType<undefined>(execa('test', {ipc: false}).getEachMessage);36expectType<undefined>(execa('test', {ipcInput: undefined}).getEachMessage);37expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).getEachMessage);38
modified:test-d/ipc/get-one.test-d.ts+18 added-3 removed
1import {expectType, expectError} from 'tsd';2import {getOneMessage, execa, type Message} from '../../index.js';2import {3 getOneMessage,4 execa,5 type Message,6 type Options,7} from '../../index.js';89expectType<Promise<Message>>(getOneMessage());10expectError(await getOneMessage(''));11
1 unmodified line
13expectType<Message<'advanced'>>(await subprocess.getOneMessage());14expectType<Message<'json'>>(await execa('test', {ipc: true, serialization: 'json'}).getOneMessage());1516expectError(await subprocess.getOneMessage(''));12expectError(await execa('test').getOneMessage());13expectError(await execa('test', {ipc: false}).getOneMessage());1718await execa('test', {ipcInput: ''}).getOneMessage();19await execa('test', {ipcInput: '' as Message}).getOneMessage();20await execa('test', {} as Options).getOneMessage?.();21await execa('test', {ipc: true as boolean}).getOneMessage?.();22await execa('test', {ipcInput: '' as '' | undefined}).getOneMessage?.();2324expectType<undefined>(execa('test').getOneMessage);25expectType<undefined>(execa('test', {}).getOneMessage);26expectType<undefined>(execa('test', {ipc: false}).getOneMessage);27expectType<undefined>(execa('test', {ipcInput: undefined}).getOneMessage);28expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).getOneMessage);
modified:test-d/ipc/send.test-d.ts+18 added-3 removed
1import {expectType, expectError} from 'tsd';2import {sendMessage, execa} from '../../index.js';2import {3 sendMessage,4 execa,5 type Message,6 type Options,7} from '../../index.js';89expectType<Promise<void>>(sendMessage(''));1011expectError(await sendMessage());
4 unmodified lines
16const subprocess = execa('test', {ipc: true});17expectType<void>(await subprocess.sendMessage(''));1819expectError(await subprocess.sendMessage());15expectError(await execa('test').sendMessage(''));16expectError(await execa('test', {ipc: false}).sendMessage(''));2021await execa('test', {ipcInput: ''}).sendMessage('');22await execa('test', {ipcInput: '' as Message}).sendMessage('');23await execa('test', {} as Options).sendMessage?.('');24await execa('test', {ipc: true as boolean}).sendMessage?.('');25await execa('test', {ipcInput: '' as '' | undefined}).sendMessage?.('');2627expectType<undefined>(execa('test').sendMessage);28expectType<undefined>(execa('test', {}).sendMessage);29expectType<undefined>(execa('test', {ipc: false}).sendMessage);30expectType<undefined>(execa('test', {ipcInput: undefined}).sendMessage);31expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).sendMessage);
modified:test-d/return/result-ipc.ts+25 added
5 unmodified lines
6 type SyncResult,7 type ExecaError,8 type ExecaSyncError,9 type Message,10 type Options,11} from '../../index.js';1213const ipcResult = await execa('unicorns', {ipc: true});14expectType<Array<Message<'advanced'>>>(ipcResult.ipc);
6 unmodified lines
2122const jsonResult = await execa('unicorns', {ipc: true, serialization: 'json'});23expectType<Array<Message<'json'>>>(jsonResult.ipc);2425const inputResult = await execa('unicorns', {ipcInput: ''});26expectType<Array<Message<'advanced'>>>(inputResult.ipc);2728const genericInputResult = await execa('unicorns', {ipcInput: '' as Message});29expectType<Array<Message<'advanced'>>>(genericInputResult.ipc);3031const genericResult = await execa('unicorns', {} as Options);32expectType<Message[] | []>(genericResult.ipc);3334const genericIpc = await execa('unicorns', {ipc: true as boolean});35expectType<Array<Message<'advanced'>> | []>(genericIpc.ipc);3637const maybeInputResult = await execa('unicorns', {ipcInput: '' as '' | undefined});38expectType<Array<Message<'advanced'>> | []>(maybeInputResult.ipc);3940const falseIpcResult = await execa('unicorns', {ipc: false});41expectType<[]>(falseIpcResult.ipc);4243const noIpcResult = await execa('unicorns');44expectType<[]>(noIpcResult.ipc);4546const emptyIpcResult = await execa('unicorns', {});47expectType<[]>(emptyIpcResult.ipc);4849const undefinedInputResult = await execa('unicorns', {ipcInput: undefined});50expectType<[]>(undefinedInputResult.ipc);5152const inputNoIpcResult = await execa('unicorns', {ipc: false, ipcInput: ''});53expectType<[]>(inputNoIpcResult.ipc);5455const noBufferResult = await execa('unicorns', {ipc: true, buffer: false});56expectType<[]>(noBufferResult.ipc);5758const noBufferFdResult = await execa('unicorns', {ipc: true, buffer: {ipc: false}});
21 unmodified lines
modified:types/arguments/options.d.ts+11 added-1 removed
1import type {SignalConstants} from 'node:os';2import type {env} from 'node:process';3import type {Readable} from 'node:stream';4import type {Unless} from '../utils.js';5import type {Message} from '../ipc.js';6import type {StdinOptionCommon, StdoutStderrOptionCommon, StdioOptionsProperty} from '../stdio/type.js';7import type {FdGenericOption} from './specific.js';8import type {EncodingOption} from './encoding-option.js';9
190 unmodified lines
200201 /**202 Enables exchanging messages with the subprocess using `subprocess.sendMessage(message)`, `subprocess.getOneMessage()` and `subprocess.getEachMessage()`.203203 @default `true` if the `node` option is enabled, `false` otherwise204 The subprocess must be a Node.js file.205206 @default `true` if either the `node` option or the `ipcInput` option is set, `false` otherwise207 */208 readonly ipc?: Unless<IsSync, boolean>;209210 /**
3 unmodified lines
214 */215 readonly serialization?: Unless<IsSync, 'json' | 'advanced'>;216217 /**218 Sends an IPC message when the subprocess starts.219220 The subprocess must be a Node.js file. The value's type depends on the `serialization` option.221 */222 readonly ipcInput?: Unless<IsSync, Message>;223224 /**225 If `verbose` is `'short'`, prints the command on [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)): its file, arguments, duration and (if it failed) error message.226227 If `verbose` is `'full'`, the command's [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)), `stderr` and IPC messages are also printed.228
154 unmodified lines
modified:types/methods/main-async.d.ts+73 added-6 removed
103 unmodified lines
104// stdout is also printed to the terminal105console.log(stdout);106```107108@example <caption>Files</caption>108@example <caption>Simple input</caption>109110```111// Similar to: npm run build > output.txt112await execa({stdout: {file: './output.txt'}})`npm run build`;111const {stdout} = await execa({input: getInputString()})`sort`;112console.log(stdout);113```114115@example <caption>Simple input</caption>115@example <caption>File input</caption>116117```118const {stdout} = await execa({input: getInputString()})`sort`;119console.log(stdout);118// Similar to: npm run build < input.txt119await execa({stdin: {file: 'input.txt'}})`npm run build`;120```121122@example <caption>File output</caption>123124```125// Similar to: npm run build > output.txt126await execa({stdout: {file: 'output.txt'}})`npm run build`;127```128129@example <caption>Split into text lines</caption>130131```132const {stdout} = await execa({lines: true})`npm run build`;
46 unmodified lines
179 createWriteStream('./output.txt'),180);181```182183@example <caption>Exchange messages</caption>184185```186// parent.js187import {execaNode} from 'execa';188189const subprocess = execaNode`child.js`;190console.log(await subprocess.getOneMessage()); // 'Hello from child'191await subprocess.sendMessage('Hello from parent');192const result = await subprocess;193```194195```196// child.js197import {sendMessage, getOneMessage} from 'execa';198199await sendMessage('Hello from child');200console.log(await getOneMessage()); // 'Hello from parent'201```202203@example <caption>Any input type</caption>204205```206// main.js207import {execaNode} from 'execa';208209const ipcInput = [210 {task: 'lint', ignore: /test\.js/},211 {task: 'copy', files: new Set(['main.js', 'index.js']),212}];213await execaNode({ipcInput})`build.js`;214```215216```217// build.js218import {getOneMessage} from 'execa';219220const ipcInput = await getOneMessage();221```222223@example <caption>Any output type</caption>224225```226// main.js227import {execaNode} from 'execa';228229const {ipc} = await execaNode`build.js`;230console.log(ipc[0]); // {kind: 'start', timestamp: date}231console.log(ipc[1]); // {kind: 'stop', timestamp: date}232```233234```235// build.js236import {sendMessage} from 'execa';237238await sendMessage({kind: 'start', timestamp: new Date()});239await runBuild();240await sendMessage({kind: 'stop', timestamp: new Date()});241```242243@example <caption>Detailed error</caption>244245```246import {execa, ExecaError} from 'execa';
63 unmodified lines
modified:types/return/result-ipc.d.ts+5 added-5 removed
1import type {FdSpecificOption} from '../arguments/specific.js';2import type {CommonOptions} from '../arguments/options.js';3import type {Message} from '../ipc.js';2import type {CommonOptions, Options, StricterOptions} from '../arguments/options.js';3import type {Message, HasIpc} from '../ipc.js';45// `result.ipc`6// This is empty unless the `ipc` option is `true`.7// Also, this is empty if the `buffer` option is `false`.
3 unmodified lines
11> = IsSync extends true12 ? []13 : ResultIpcAsync<14 FdSpecificOption<OptionsType['buffer'], 'ipc'>,15 OptionsType['ipc'],15 HasIpc<StricterOptions<OptionsType, Options>>,16 OptionsType['serialization']17 >;1819type ResultIpcAsync<20 BufferOption extends boolean | undefined,21 IpcOption extends boolean | undefined,21 IpcEnabled extends boolean,22 SerializationOption extends CommonOptions['serialization'],23> = BufferOption extends false24 ? []25 : IpcOption extends true25 : IpcEnabled extends true26 ? Array<Message<SerializationOption>>27 : [];
modified:types/subprocess/subprocess.d.ts+2 added-9 removed
1import type {ChildProcess} from 'node:child_process';2import type {SignalConstants} from 'node:os';3import type {Readable, Writable, Duplex} from 'node:stream';4import type {StdioOptionsArray} from '../stdio/type.js';4import type {Options} from '../arguments/options.js';5import type {Result} from '../return/result.js';6import type {PipableSubprocess} from '../pipe.js';7import type {
1 unmodified line
9 WritableOptions,10 DuplexOptions,11 SubprocessAsyncIterable,12} from '../convert.js';14import type {IpcMethods} from '../ipc.js';13import type {IpcMethods, HasIpc} from '../ipc.js';14import type {SubprocessStdioStream} from './stdout.js';15import type {SubprocessStdioArray} from './stdio.js';16import type {SubprocessAll} from './all.js';1719type HasIpc<OptionsType extends Options> = OptionsType['ipc'] extends true20 ? true21 : OptionsType['stdio'] extends StdioOptionsArray22 ? 'ipc' extends OptionsType['stdio'][number] ? true : false23 : false;2418type ExecaCustomSubprocess<OptionsType extends Options> = {19 /**20 Process identifier ([PID](https://en.wikipedia.org/wiki/Process_identifier)).21
74 unmodified lines
96 Converts the subprocess to a duplex stream.97 */98 duplex(duplexOptions?: DuplexOptions): Duplex;99}107& IpcMethods<OptionsType['ipc'], OptionsType['serialization']>100& IpcMethods<HasIpc<OptionsType>, OptionsType['serialization']>101& PipableSubprocess;102103/**104[`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with additional methods and properties.
13 unmodified lines
modified:types/ipc.d.ts+23 added-6 removed
48 unmodified lines
49export function getEachMessage(): AsyncIterableIterator<Message>;5051// IPC methods in the current process52export type IpcMethods<53 IpcOption extends Options['ipc'],53 IpcEnabled extends boolean,54 Serialization extends Options['serialization'],55> = IpcOption extends true55> = IpcEnabled extends true56 ? {57 /**58 Send a `message` to the subprocess.59
16 unmodified lines
76 getEachMessage(): AsyncIterableIterator<Message<Serialization>>;77 }78 // Those methods only work if the `ipc` option is `true`.79 // At runtime, they are actually defined, in order to provide with a nice error message.80 // At type check time, they are typed as `never` to prevent calling them.80 // At type check time, they are typed as `undefined` to prevent calling them.81 : {82 sendMessage: never;83 getOneMessage: never;84 getEachMessage: never;82 sendMessage: undefined;83 getOneMessage: undefined;84 getEachMessage: undefined;85 };8687// Whether IPC is enabled, based on the `ipc` and `ipcInput` options88export type HasIpc<OptionsType extends Options> = HasIpcOption<89OptionsType['ipc'],90'ipcInput' extends keyof OptionsType ? OptionsType['ipcInput'] : undefined91>;9293type HasIpcOption<94 IpcOption extends Options['ipc'],95 IpcInputOption extends Options['ipcInput'],96> = IpcOption extends true97 ? true98 : IpcOption extends false99 ? false100 : IpcInputOption extends undefined101 ? false102 : true;
modified:readme.md+58 added-7 removed
60 unmodified lines
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).65- Pass any [input](docs/input.md) to the subprocess: [files](#file-input), [strings](#simple-input), [`Uint8Array`s](docs/binary.md#binary-input), [iterables](docs/streams.md#iterables-as-input), [objects](docs/transform.md#object-mode) and almost any [other type](#any-input-type).66- Return [almost any type](#any-output-type) from the subprocess, or redirect it to [files](#file-output).67- Get [interleaved output](#interleaved-output) from `stdout` and `stderr` similar to what is printed on the terminal.68- Retrieve the output [programmatically and print it](#programmatic--terminal-output) on the console at the same time.69- [Transform or filter](#transformfilter-output) the input and output with [simple functions](docs/transform.md).68- Redirect the [input](docs/input.md) and [output](docs/output.md) from/to [files](#files), [strings](#simple-input), [`Uint8Array`s](docs/binary.md#binary-input), [iterables](docs/streams.md#iterables-as-input) or [objects](docs/transform.md#object-mode).70- Pass [Node.js streams](docs/streams.md#nodejs-streams) or [web streams](#web-streams) to subprocesses, or [convert](#convert-to-duplex-stream) subprocesses to [a stream](docs/streams.md#converting-a-subprocess-to-a-stream).71- [Exchange messages](#exchange-messages) with the subprocess.72- Ensure subprocesses exit even when they [intercept termination signals](docs/termination.md#forceful-termination), or when the current process [ends abruptly](docs/termination.md#current-process-exit).73
109 unmodified lines
183// stdout is also printed to the terminal184console.log(stdout);185```186186#### Files187#### Simple input188189```js189// Similar to: npm run build > output.txt190await execa({stdout: {file: './output.txt'}})`npm run build`;190const {stdout} = await execa({input: getInputString()})`sort`;191console.log(stdout);192```193193#### Simple input194#### File input195196```js196const {stdout} = await execa({input: getInputString()})`sort`;197console.log(stdout);197// Similar to: npm run build < input.txt198await execa({stdin: {file: 'input.txt'}})`npm run build`;199```200201#### File output202203```js204// Similar to: npm run build > output.txt205await execa({stdout: {file: 'output.txt'}})`npm run build`;206```207208#### Split into text lines209210```js211const {stdout} = await execa({lines: true})`npm run build`;
48 unmodified lines
260 createWriteStream('./output.txt'),261);262```263264### IPC265266#### Exchange messages267268```js269// parent.js
1 unmodified line
271272const subprocess = execaNode`child.js`;273console.log(await subprocess.getOneMessage()); // 'Hello from child'274await subprocess.sendMessage('Hello from parent');275const result = await subprocess;276```277278```js279// child.js
2 unmodified lines
282await sendMessage('Hello from child');283console.log(await getOneMessage()); // 'Hello from parent'284```285286#### Any input type287288```js289// main.js290import {execaNode} from 'execa';291292const ipcInput = [293 {task: 'lint', ignore: /test\.js/},294 {task: 'copy', files: new Set(['main.js', 'index.js']),295}];296await execaNode({ipcInput})`build.js`;297```298299```js300// build.js301import {getOneMessage} from 'execa';302303const ipcInput = await getOneMessage();304```305306#### Any output type307308```js309// main.js310import {execaNode} from 'execa';311312const {ipc} = await execaNode`build.js`;313console.log(ipc[0]); // {kind: 'start', timestamp: date}314console.log(ipc[1]); // {kind: 'stop', timestamp: date}315```316317```js318// build.js319import {sendMessage} from 'execa';320321await sendMessage({kind: 'start', timestamp: new Date()});322await runBuild();323await sendMessage({kind: 'stop', timestamp: new Date()});324```325326### Debugging327328#### Detailed error329
62 unmodified lines