Skip to content
Myr

Expose the destination subprocess methods on `.pipe()` (#1252)

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

authored by Sindre Sorhus · committed by GitHub · parent 4cafc3f · Browse files · 11 files+829 added−59 removed
This commit

State

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

Diff stats

11 files+829 added−59 removed

  • tests:+515 added−7 removed
  • other:+314 added−52 removed

11 files+829 added−59 removed

modified:docs/api.md+2 added
251 unmodified lines
252[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the subprocess' [`stdout`](#subprocessstdout) to a second Execa subprocess' [`stdin`](#subprocessstdin). This resolves with that second subprocess' [result](#result). If either subprocess is rejected, this is rejected with that subprocess' [error](#execaerror) instead.253254This follows the same syntax as [`execa(file, arguments?, options?)`](#execafile-arguments-options) except both [regular options](#options-1) and [pipe-specific options](#pipeoptions) can be specified.255256Like a subprocess, the return value can be [iterated](lines.md#progressive-splitting), [converted to a stream](streams.md#converting-a-subprocess-to-a-stream), or used for [IPC](ipc.md) with the destination subprocess.257258[More info.](pipe.md#array-syntax)259260### subprocess.pipe\`command\`261### subprocess.pipe(options)\`command\`
1048 unmodified lines
modified:docs/pipe.md+10 added
modified:lib/ipc/get-each.js+32 added-9 removed
1 unmodified line
2import {validateIpcMethod, disconnect, getStrictResponseError} from './validation.js';3import {getIpcEmitter, isConnected} from './forward.js';4import {addReference, removeReference} from './reference.js';56export const internalGetEachMessageOptions = Symbol('internalGetEachMessageOptions');78// Like `[sub]process.on('message')` but promise-based7export const getEachMessage = ({anyProcess, channel, isSubprocess, ipc}, {reference = true} = {}) => loopOnMessages({8 anyProcess,9 channel,10 isSubprocess,11 ipc,12 shouldAwait: !isSubprocess,13 reference,14});9export const getEachMessage = (subprocessInfo, options = {}) => {10 const {reference = true} = options;11 // Internal callers can stop the IPC listener without exposing cancellation or pipe-awaiting options as public API.12 const {signal, shouldAwait = !subprocessInfo.isSubprocess} = options[internalGetEachMessageOptions] ?? {};1314 return loopOnMessages({15 ...subprocessInfo,16 shouldAwait,17 reference,18 signal,19 });20};2122// Same but used internally17export const loopOnMessages = ({anyProcess, channel, isSubprocess, ipc, shouldAwait, reference}) => {23export const loopOnMessages = ({anyProcess, channel, isSubprocess, ipc, shouldAwait, reference, signal}) => {24 validateIpcMethod({25 methodName: 'getEachMessage',26 isSubprocess,27 ipc,
3 unmodified lines
31 addReference(channel, reference);32 const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);33 const controller = new AbortController();34 const state = {};35 stopOnAbort(signal, controller);36 stopOnDisconnect(anyProcess, ipcEmitter, controller);37 abortOnStrictError({38 ipcEmitter,39 isSubprocess,
11 unmodified lines
51 reference,52 });53};5455const stopOnAbort = (signal, controller) => {56 if (signal === undefined) {57 return;58 }5960 if (signal.aborted) {61 controller.abort();62 return;63 }6465 // Reuse the iterator controller for listener cleanup when iteration ends before the internal signal aborts.66 signal.addEventListener('abort', () => {67 controller.abort();68 }, {once: true, signal: controller.signal});69};7071const stopOnDisconnect = async (anyProcess, ipcEmitter, controller) => {72 try {73 await once(ipcEmitter, 'disconnect', {signal: controller.signal});74 controller.abort();
38 unmodified lines
modified:lib/ipc/get-one.js+25 added-2 removed
6 unmodified lines
7} from './validation.js';8import {getIpcEmitter, isConnected} from './forward.js';9import {addReference, removeReference} from './reference.js';1011export const internalGetOneMessageOptions = Symbol('internalGetOneMessageOptions');1213// Like `[sub]process.once('message')` but promise-based12export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, {reference = true, filter} = {}) => {14export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, options = {}) => {15 const {reference = true, filter} = options;16 const {signal} = options[internalGetOneMessageOptions] ?? {};1718 validateIpcMethod({19 methodName: 'getOneMessage',20 isSubprocess,21 ipc,
5 unmodified lines
27 channel,28 isSubprocess,29 filter,30 reference,31 signal,32 });33};3429const getOneMessageAsync = async ({anyProcess, channel, isSubprocess, filter, reference}) => {35const getOneMessageAsync = async ({anyProcess, channel, isSubprocess, filter, reference, signal}) => {36 addReference(channel, reference);37 const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);38 const controller = new AbortController();39 stopOnAbort(signal, controller);4041 try {42 return await Promise.race([43 getMessage(ipcEmitter, filter, controller),44 throwOnDisconnect(ipcEmitter, isSubprocess, controller),
7 unmodified lines
52 removeReference(channel, reference);53 }54};5556const stopOnAbort = (signal, controller) => {57 if (signal === undefined) {58 return;59 }6061 if (signal.aborted) {62 controller.abort();63 return;64 }6566 signal.addEventListener('abort', () => {67 controller.abort();68 }, {once: true, signal: controller.signal});69};7071const getMessage = async (ipcEmitter, filter, {signal}) => {72 if (filter === undefined) {73 const [message] = await once(ipcEmitter, 'message', {signal});74 return message;
18 unmodified lines
modified:lib/pipe/setup.js+167 added-11 removed
1import isPlainObject from 'is-plain-obj';2import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';3import {initializeConcurrentStreams} from '../convert/concurrent.js';4import {createIterable} from '../convert/iterable.js';5import {createReadable} from '../convert/readable.js';6import {internalGetOneMessageOptions} from '../ipc/get-one.js';7import {internalGetEachMessageOptions} from '../ipc/get-each.js';8import {normalizePipeArguments} from './pipe-arguments.js';9import {handlePipeArgumentsError} from './throw.js';10import {waitForBothSubprocesses} from './sequence.js';11import {pipeSubprocessStream} from './streaming.js';
8 unmodified lines
20 });21 }2223 const {destination, ...normalizedInfo} = normalizePipeArguments(sourceInfo, ...pipeArguments);24 const pipeFailureController = new AbortController();18 const promise = handlePipePromise({...normalizedInfo, destination});25 const promise = handlePipePromise({...normalizedInfo, destination, pipeFailureController});26 promise.pipe = pipeToSubprocess.bind(undefined, {27 ...sourceInfo,28 source: destination,29 sourcePromise: promise,30 boundOptions: {},31 });32 forwardDestinationMethods(promise, destination, pipeFailureController.signal);33 return promise;34};3536/*37The return value of `.pipe()` exposes the destination subprocess' output, but its iteration and stream conversion methods must await the whole pipe so source failures are propagated too. The destination is `undefined` when `.pipe()` was passed invalid arguments, in which case the promise rejects and there is nothing to forward.38*/39const forwardDestinationMethods = (promise, destination, pipeFailureSignal) => {40 if (destination === undefined) {41 return;42 }4344 forwardReadableMethods(promise, destination);45 forwardIpcMethods(promise, destination, pipeFailureSignal);46};4748const forwardReadableMethods = (promise, destination) => {49 const subprocessOptions = SUBPROCESS_OPTIONS.get(destination);50 SUBPROCESS_OPTIONS.set(promise, subprocessOptions);51 promise.stdio = destination.stdio;52 promise.all = destination.all;5354 const {options: {encoding}} = subprocessOptions;55 const concurrentStreams = initializeConcurrentStreams();56 promise[Symbol.asyncIterator] = createIterable.bind(undefined, promise, encoding, {});57 promise.iterable = createIterable.bind(undefined, promise, encoding);58 promise.readable = createPipeReadable.bind(undefined, promise, {59 subprocess: promise,60 concurrentStreams,61 encoding,62 });63 forwardAll(promise, destination);64};6566const forwardAll = (promise, destination) => {67 if (destination.all === undefined) {68 promise.all = undefined;69 return;70 }7172 Object.defineProperty(promise, 'all', {73 get() {74 setAllProperty(promise, destination.all);75 const all = promise.readable({from: 'all'});76 setAllProperty(promise, all);77 return all;78 },79 enumerable: true,80 configurable: true,81 });82};8384const setAllProperty = (promise, value) => {85 Object.defineProperty(promise, 'all', {86 value,87 writable: true,88 enumerable: true,89 configurable: true,90 });91};9293const createPipeReadable = (promise, readableOptions, ...arguments_) => {94 const readable = createReadable(readableOptions, ...arguments_);95 destroyOnPipeFailure(promise, readable);96 return readable;97};9899const destroyOnPipeFailure = async (promise, readable) => {100 try {101 await promise;102 } catch (error) {103 readable.destroy(error);104 }105};106107const forwardIpcMethods = (promise, destination, pipeFailureSignal) => {108 promise.sendMessage = destination.sendMessage;109 promise.getOneMessage = getOnePipeMessage.bind(undefined, destination, pipeFailureSignal);110 promise.getEachMessage = getEachPipeMessage.bind(undefined, promise, destination, pipeFailureSignal);111};112113const getOnePipeMessage = (destination, pipeFailureSignal, ...arguments_) => {114 const controller = new AbortController();115 const messagePromise = destination.getOneMessage(...addPipeOptions(arguments_, controller.signal, internalGetOneMessageOptions));116 return waitForOnePipeMessage(pipeFailureSignal, messagePromise, controller);117};118119const waitForOnePipeMessage = async (pipeFailureSignal, messagePromise, controller) => {120 try {121 return await Promise.race([messagePromise, getSignalRejection(pipeFailureSignal, controller.signal)]);122 } finally {123 controller.abort();124 }125};126127const getSignalRejection = (signal, listenerSignal) => new Promise((_, reject) => {128 if (signal.aborted) {129 reject(signal.reason);130 return;131 }132133 signal.addEventListener('abort', () => {134 reject(signal.reason);135 }, {once: true, signal: listenerSignal});136});137138const getEachPipeMessage = (promise, destination, pipeFailureSignal, ...arguments_) => {139 const controller = new AbortController();140 // Create the destination iterator before awaiting the pipe so option validation stays synchronous.141 const iterator = destination.getEachMessage(...addPipeOptions(arguments_, controller.signal, internalGetEachMessageOptions));142 abortOnSignal(pipeFailureSignal, controller);143 return iterateOnPipeMessages(promise, iterator, controller);144};145146const iterateOnPipeMessages = async function * (promise, iterator, controller) {147 try {148 yield * iterator;149 } finally {150 controller.abort();151 await promise;152 }153};154155const addPipeOptions = (arguments_, signal, internalOptionsSymbol) => {156 if (arguments_[0] === null) {157 // Preserve the public validation error from `getEachMessage(null)` instead of masking it with a pipe failure.158 return arguments_;159 }160161 const [options] = arguments_;162 // The returned pipe promise is awaited by the forwarded IPC iterator, so the destination IPC iterator must not also await the destination subprocess on close.163 return [{...options, [internalOptionsSymbol]: {signal, shouldAwait: false}}];164};165166const abortOnSignal = (signal, controller) => {167 if (signal.aborted) {168 controller.abort();169 return;170 }171172 // Interrupt pending IPC reads when the pipe rejects, including `unpipeSignal` cancellation while the destination keeps running.173 signal.addEventListener('abort', () => {174 controller.abort();175 }, {once: true, signal: controller.signal});176};177178// `writable()` and `duplex()` are intentionally not forwarded: they write to the destination's `stdin`, which is already being piped from the source.179180// Asynchronous logic when piping subprocesses181const handlePipePromise = async ({182 sourcePromise,183 sourceStream,
4 unmodified lines
188 destinationError,189 unpipeSignal,190 fileDescriptors,191 startTime,192 pipeFailureController,193}) => {41 const subprocessPromises = getSubprocessPromises(sourcePromise, destination);42 handlePipeArgumentsError({43 sourceStream,44 sourceError,45 destinationStream,46 destinationError,47 fileDescriptors,48 sourceOptions,49 startTime,50 });194 const maxListenersController = new AbortController();195 try {196 const subprocessPromises = getSubprocessPromises(sourcePromise, destination);197 handlePipeArgumentsError({198 sourceStream,199 sourceError,200 destinationStream,201 destinationError,202 fileDescriptors,203 sourceOptions,204 startTime,205 });206 const mergedStream = pipeSubprocessStream(sourceStream, destinationStream, maxListenersController);207 return await Promise.race([208 waitForBothSubprocesses(subprocessPromises),209 ...unpipeOnAbort(unpipeSignal, {
3 unmodified lines
213 fileDescriptors,214 startTime,215 }),216 ]);217 } catch (error) {218 pipeFailureController.abort(error);219 throw error;220 } finally {221 maxListenersController.abort();222 }223};
5 unmodified lines
added:test/fixtures/stdin-distinct-both.js+7 added
added:test/pipe/methods.js+435 added
1import {setTimeout} from 'node:timers/promises';2import {Readable} from 'node:stream';3import {text} from 'node:stream/consumers';4import test from 'ava';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {simpleFull, noNewlinesFull, noNewlinesChunks} from '../helpers/lines.js';8import {foobarString, foobarArray} from '../helpers/input.js';910setFixtureDirectory();1112const timeoutSymbol = Symbol('timeout');1314// `stdin.js` pipes its stdin to its stdout, so the piped output equals the source output15const pipeSimple = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js');16const pipeAll = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js', {all: true});17const pipeDistinctBoth = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin-distinct-both.js');1819const assertSettles = async (t, promise, timeout = 1000) => {20 const result = await Promise.race([21 promise,22 // Several pipe cancellation tests are specifically checking that a pending reader does not hang.23 setTimeout(timeout, timeoutSymbol, {ref: false}),24 ]);2526 t.not(result, timeoutSymbol);27 return result;28};2930const cleanupSubprocesses = async (...subprocesses) => {31 for (const subprocess of subprocesses) {32 subprocess.kill();33 }3435 await Promise.allSettled(subprocesses);36};3738const getPipeMessages = async piped => {39 const messages = [];40 for await (const message of piped.getEachMessage()) {41 messages.push(message);42 }4344 return messages;45};4647test('The .pipe() return value can be iterated', async t => {48 const lines = [];49 for await (const line of pipeSimple()) {50 lines.push(line);51 }5253 t.deepEqual(lines, noNewlinesChunks);54});5556test('The .pipe() return value has an .iterable() method', async t => {57 const lines = [];58 for await (const line of pipeSimple().iterable()) {59 lines.push(line);60 }6162 t.deepEqual(lines, noNewlinesChunks);63});6465test('The .pipe() return value has a .readable() method', async t => {66 t.is(await text(pipeSimple().readable()), simpleFull);67});6869test('The .pipe() return value .readable() can be called multiple times', async t => {70 const piped = pipeSimple();71 const [output, secondOutput] = await Promise.all([72 text(piped.readable()),73 text(piped.readable()),74 ]);7576 t.is(output, simpleFull);77 t.is(secondOutput, simpleFull);78});7980test('The .pipe() return value .readable() keeps conversion options', async t => {81 const chunks = [];82 for await (const chunk of pipeSimple().readable({binary: false, preserveNewlines: false})) {83 chunks.push(chunk);84 }8586 t.deepEqual(chunks, noNewlinesChunks);87 t.is(chunks.join(''), noNewlinesFull);88});8990test('The .pipe() return value does not have a .writable() method', async t => {91 const piped = pipeSimple();92 t.is(piped.writable, undefined);93 t.is(piped.duplex, undefined);94 await piped;95});9697test('The .pipe() return value does not have .all unless destination uses the "all" option', async t => {98 const piped = pipeSimple();99 const descriptor = Object.getOwnPropertyDescriptor(piped, 'all');100101 t.is(piped.all, undefined);102 t.is(descriptor.value, undefined);103 t.is(descriptor.get, undefined);104 await piped;105});106107test('The .pipe() return value has an .all property', async t => {108 const piped = pipeAll();109 t.true(piped.all instanceof Readable);110 t.is(await text(piped.all), simpleFull);111 await piped;112});113114test('The .pipe() return value .all is created lazily and cached', async t => {115 const piped = pipeAll();116 const descriptor = Object.getOwnPropertyDescriptor(piped, 'all');117118 t.is(typeof descriptor.get, 'function');119 const {all} = piped;120 t.true(all instanceof Readable);121 t.is(piped.all, all);122 t.is(Object.getOwnPropertyDescriptor(piped, 'all').get, undefined);123 t.is(await text(all), simpleFull);124 await piped;125});126127test('The .pipe() return value .readable() can read destination stderr', async t => {128 const piped = pipeDistinctBoth();129130 t.is(await text(piped.readable({from: 'stderr'})), `${simpleFull}:stderr`);131 await piped;132});133134test('The .pipe() return value .iterable() can read destination stderr', async t => {135 const piped = pipeDistinctBoth();136 const lines = [];137 for await (const line of piped.iterable({from: 'stderr'})) {138 lines.push(line);139 }140141 t.deepEqual(lines, ['aaa', 'bbb', 'ccc:stderr']);142 await piped;143});144145test('The .pipe() return value has IPC methods', async t => {146 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});147 t.deepEqual(await getPipeMessages(piped), foobarArray);148 const {ipcOutput} = await piped;149 t.deepEqual(ipcOutput, foobarArray);150});151152test('The .pipe() return value .getEachMessage() can be called twice at the same time', async t => {153 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});154155 t.deepEqual(156 await Promise.all([getPipeMessages(piped), getPipeMessages(piped)]),157 [foobarArray, foobarArray],158 );159160 const {ipcOutput} = await piped;161 t.deepEqual(ipcOutput, foobarArray);162});163164test('The .pipe() return value .getEachMessage() preserves setup errors', async t => {165 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});166167 t.throws(() => {168 piped.getEachMessage(null);169 }, {instanceOf: TypeError});170171 await piped;172});173174test('The .pipe() return value .getEachMessage() waits for source failure', async t => {175 const piped = execa('fail.js').pipe('ipc-send-twice.js', {ipc: true});176177 await t.throwsAsync(async () => {178 for await (const message of piped.getEachMessage()) {179 t.true(foobarArray.includes(message));180 }181 }, {message: /Command failed with exit code 2/});182});183184test('The .pipe() return value .getEachMessage() waits for pipe cancellation', async t => {185 const abortController = new AbortController();186 const source = execa('noop-repeat.js');187 const destination = execa('ipc-send-forever.js', {ipc: true});188 t.teardown(async () => {189 await cleanupSubprocesses(source, destination);190 });191192 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});193 const iterator = piped.getEachMessage();194 t.deepEqual(await iterator.next(), {done: false, value: foobarString});195196 const readerPromise = t.throwsAsync(iterator.next(), {message: /Pipe canceled/});197 abortController.abort();198 await assertSettles(t, readerPromise);199});200201test('The .pipe() return value .getEachMessage() cancels every pending reader', async t => {202 const abortController = new AbortController();203 const source = execa('noop-repeat.js');204 const destination = execa('ipc-send-forever.js', {ipc: true});205 t.teardown(async () => {206 await cleanupSubprocesses(source, destination);207 });208209 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});210 const iterators = [211 piped.getEachMessage(),212 piped.getEachMessage(),213 ];214215 t.deepEqual(216 await Promise.all(iterators.map(async iterator => iterator.next())),217 [218 {done: false, value: foobarString},219 {done: false, value: foobarString},220 ],221 );222223 const readerPromises = iterators.map(iterator => t.throwsAsync(iterator.next(), {message: /Pipe canceled/}));224 abortController.abort();225 await Promise.all(readerPromises.map(async readerPromise => assertSettles(t, readerPromise)));226});227228const assertCanceledPipeMessageReader = async (t, getReader, abortBeforePipe = false) => {229 const abortController = new AbortController();230 if (abortBeforePipe) {231 abortController.abort();232 }233234 const source = execa('noop-repeat.js');235 const destination = execa('ipc-get.js', {ipc: true});236 t.teardown(async () => {237 await cleanupSubprocesses(source, destination);238 });239240 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});241 const readerPromise = t.throwsAsync(getReader(piped), {message: /Pipe canceled/});242243 if (!abortBeforePipe) {244 abortController.abort();245 }246247 await assertSettles(t, readerPromise);248 await t.throwsAsync(piped, {message: /Pipe canceled/});249};250251test('The .pipe() return value .getEachMessage() waits for pipe cancellation before IPC messages', async t => {252 await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next());253});254255test('The .pipe() return value .getEachMessage() waits for already canceled pipes', async t => {256 await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next(), true);257});258259test('The .pipe() return value .getOneMessage() waits for pipe cancellation before IPC messages', async t => {260 await assertCanceledPipeMessageReader(t, piped => piped.getOneMessage());261});262263test('The .pipe() return value .getOneMessage() waits for already canceled pipes', async t => {264 await assertCanceledPipeMessageReader(t, piped => piped.getOneMessage(), true);265});266267test('The .pipe() return value .getEachMessage() waits for the pipe when the iterator is returned', async t => {268 const source = execa('empty.js');269 const destination = execa('ipc-send-forever.js', {ipc: true});270 t.teardown(async () => {271 await cleanupSubprocesses(source, destination);272 });273274 const piped = source.pipe(destination);275 const iterator = piped.getEachMessage();276277 t.deepEqual(await iterator.next(), {done: false, value: foobarString});278 const returnPromise = t.throwsAsync(iterator.return());279 destination.kill();280 const error = await returnPromise;281 t.true(error.isTerminated);282 await Promise.allSettled([source, destination, piped]);283});284285test('The .pipe() return value .getEachMessage() propagates source failure when the iterator is returned', async t => {286 const source = execa('ipc-echo-fail.js', {ipc: true});287 const piped = source.pipe('ipc-send-wait-print.js', {ipc: true});288 const iterator = piped.getEachMessage();289290 t.deepEqual(await iterator.next(), {done: false, value: foobarString});291 const returnPromise = t.throwsAsync(iterator.return(), {message: /Command failed with exit code 1/});292 await source.sendMessage(foobarString);293 await returnPromise;294});295296test('The .pipe() return value .getEachMessage() propagates destination failure', async t => {297 const piped = execa('empty.js').pipe('ipc-send-fail.js', {ipc: true});298299 await t.throwsAsync(async () => {300 for await (const message of piped.getEachMessage()) {301 t.is(message, foobarString);302 }303 }, {message: /Command failed with exit code 1/});304305 const {ipcOutput} = await t.throwsAsync(piped);306 t.deepEqual(ipcOutput, [foobarString]);307});308309test('The .pipe() return value .getEachMessage() waits for the pipe when the consumer throws', async t => {310 const piped = execa('empty.js').pipe('ipc-send-wait-print.js', {ipc: true});311 const cause = new Error(foobarString);312313 t.is(await t.throwsAsync(async () => {314 // eslint-disable-next-line no-unreachable-loop315 for await (const message of piped.getEachMessage()) {316 t.is(message, foobarString);317 throw cause;318 }319 }), cause);320321 const {ipcOutput, stdout} = await piped;322 t.deepEqual(ipcOutput, [foobarString]);323 t.is(stdout, '.');324});325326test('The .pipe() return value .getEachMessage() validates IPC immediately', async t => {327 const source = execa('stdin.js');328 const destination = execa('stdin.js');329 t.teardown(async () => {330 await cleanupSubprocesses(source, destination);331 });332333 const piped = source.pipe(destination);334 const {message} = t.throws(() => piped.getEachMessage());335336 t.true(message.includes('subprocess.getEachMessage() can only be used'));337 source.kill();338 destination.kill();339 await Promise.allSettled([source, destination, piped]);340});341342test('The .pipe() return value can exchange IPC messages', async t => {343 const piped = execa('empty.js').pipe('ipc-echo.js', {ipc: true});344 await piped.sendMessage(foobarString);345 t.is(await piped.getOneMessage(), foobarString);346 await piped;347});348349test('A chained .pipe() return value can be iterated', async t => {350 const lines = [];351 for await (const line of execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js').pipe('stdin.js')) {352 lines.push(line);353 }354355 t.deepEqual(lines, noNewlinesChunks);356});357358test('The .pipe() return value still awaits both subprocesses', async t => {359 await t.throwsAsync(execa('fail.js').pipe('stdin.js'), {message: /Command failed with exit code 2/});360});361362test('The .pipe() return value iteration waits for source failure', async t => {363 const piped = execa('fail.js').pipe('stdin.js');364365 await t.throwsAsync(async () => {366 for await (const line of piped) {367 t.fail(`Unexpected line: ${line}`);368 }369 }, {message: /Command failed with exit code 2/});370});371372test('The .pipe() return value .readable() waits for source failure', async t => {373 const piped = execa('fail.js').pipe('stdin.js');374375 await t.throwsAsync(text(piped.readable()), {message: /Command failed with exit code 2/});376});377378test('The .pipe() return value .all waits for source failure', async t => {379 const piped = execa('fail.js').pipe('stdin.js', {all: true});380381 await t.throwsAsync(text(piped.all), {message: /Command failed with exit code 2/});382});383384const assertCanceledPipeReader = async (t, getReader, abortBeforePipe = false) => {385 const abortController = new AbortController();386 if (abortBeforePipe) {387 abortController.abort();388 }389390 const source = execa('stdin.js');391 const destination = execa('stdin.js', {all: true});392 t.teardown(async () => {393 await cleanupSubprocesses(source, destination);394 });395396 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});397 const readerPromise = t.throwsAsync(getReader(piped), {message: /Pipe canceled/});398399 if (!abortBeforePipe) {400 abortController.abort();401 }402403 await assertSettles(t, readerPromise, 200);404};405406test('The .pipe() return value .readable() waits for pipe cancellation', async t => {407 await assertCanceledPipeReader(t, piped => text(piped.readable()));408});409410test('The .pipe() return value .all waits for pipe cancellation', async t => {411 await assertCanceledPipeReader(t, piped => text(piped.all));412});413414test('The .pipe() return value .readable() waits for already canceled pipes', async t => {415 await assertCanceledPipeReader(t, piped => text(piped.readable()), true);416});417418test('The .pipe() return value .all waits for already canceled pipes', async t => {419 await assertCanceledPipeReader(t, piped => text(piped.all), true);420});421422test('Multiple sources piped to one destination each expose the destination methods', async t => {423 const destination = execa('stdin.js');424 const piped = [425 execa('noop-fd.js', ['1', foobarString]).pipe(destination),426 execa('noop-fd.js', ['1', foobarString]).pipe(destination),427 ];428429 for (const pipePromise of piped) {430 t.is(typeof pipePromise.iterable, 'function');431 t.is(typeof pipePromise[Symbol.asyncIterator], 'function');432 }433434 await Promise.all(piped);435});
modified:test/pipe/sequence.js+73 added-7 removed
1import {once} from 'node:events';2import process from 'node:process';3import {PassThrough} from 'node:stream';4import {setTimeout} from 'node:timers/promises';5import test from 'ava';6import {execa} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {foobarString} from '../helpers/input.js';
2 unmodified lines
1112setFixtureDirectory();1314const isLinux = process.platform === 'linux';15const timeoutSymbol = Symbol('timeout');1617const assertUnhandledRejection = async (t, pipePromise, unhandledRejectionPromise) => {18 const result = await Promise.race([19 unhandledRejectionPromise,20 setTimeout(500, timeoutSymbol),21 ]);2223 t.not(result, timeoutSymbol);2425 if (result === timeoutSymbol) {26 return;27 }2829 const [reason, unhandledPromise] = result;30 t.is(unhandledPromise, pipePromise);31 t.regex(reason.message, /Command failed with exit code 2/);32};3334const assertUnhandledPipePromise = async (t, {destinationOptions = {}, inspectPipePromise} = {}) => {35 const source = execa('fail.js');36 const destination = execa('fail.js', destinationOptions);37 const pipePromise = source.pipe(destination);38 const unhandledRejectionPromise = once(process, 'unhandledRejection');39 await inspectPipePromise?.(pipePromise);40 await assertUnhandledRejection(t, pipePromise, unhandledRejectionPromise);41 await Promise.all([42 t.throwsAsync(source),43 t.throwsAsync(destination),44 ]);45 await t.throwsAsync(pipePromise);46};4748test('Source stream abort -> destination success', async t => {49 const source = execa('noop-repeat.js');50 const destination = execa('stdin.js');51 const pipePromise = source.pipe(destination);
247 unmodified lines
299 const destination = execa('fail.js');300 await t.throwsAsync(source.pipe(destination));301});302270test('Need to await .pipe() return value', async t => {303test.serial('Need to await .pipe() return value', async t => {304 await assertUnhandledPipePromise(t);305});306307test.serial('Need to await .pipe() return value, "all" option', async t => {308 await assertUnhandledPipePromise(t, {destinationOptions: {all: true}});309});310311test.serial('Need to await .pipe() return value after inspecting lazy .all', async t => {312 await assertUnhandledPipePromise(t, {313 destinationOptions: {all: true},314 inspectPipePromise(pipePromise) {315 const descriptor = Object.getOwnPropertyDescriptor(pipePromise, 'all');316 t.is(typeof descriptor.get, 'function');317 },318 });319});320321test.serial('Need to await .pipe() return value after getOneMessage()', async t => {322 const source = execa('fail.js');272 const destination = execa('fail.js');323 const destination = execa('ipc-send-twice.js', {ipc: true});324 const pipePromise = source.pipe(destination);274 await Promise.all([275 once(process, 'unhandledRejection'),276 t.throwsAsync(source),277 t.throwsAsync(destination),278 ]);325 const unhandledRejectionPromise = once(process, 'unhandledRejection');326327 t.is(await pipePromise.getOneMessage(), 'foo');328 await assertUnhandledRejection(t, pipePromise, unhandledRejectionPromise);329 await t.throwsAsync(source);330 await destination;331 await t.throwsAsync(pipePromise);332});333334test.serial('Need to await .pipe() return value after paused getEachMessage()', async t => {335 const source = execa('fail.js');336 const destination = execa('ipc-send-twice.js', {ipc: true});337 const pipePromise = source.pipe(destination);338 const unhandledRejectionPromise = once(process, 'unhandledRejection');339 const iterator = pipePromise.getEachMessage();340341 t.deepEqual(await iterator.next(), {done: false, value: 'foo'});342 await assertUnhandledRejection(t, pipePromise, unhandledRejectionPromise);343 await t.throwsAsync(source);344 await destination;345 await t.throwsAsync(pipePromise);346});347348if (isLinux) {349 const testYesHead = async (t, useStdoutTransform, useStdinTransform, all) => {350 const source = execa('yes', {stdout: useStdoutTransform ? noopGenerator(false) : 'pipe', all});351 const destination = execa('head', ['-n', '1'], {stdin: useStdinTransform ? noopGenerator(false) : 'pipe'});
28 unmodified lines
modified:test-d/pipe.test-d.ts+30 added
1import {createWriteStream} from 'node:fs';2import type {Readable} from 'node:stream';3import {expectType, expectNotType, expectError} from 'tsd';4import {5 execa,6 execaSync,7 $,8 type Result,9 type Message,10} from '../index.js';1112const fileUrl = new URL('file:///test');13const stringArray = ['foo', 'bar'] as const;
239 unmodified lines
253expectType<undefined>(ignoreShortcutScriptPipeResult.stdout);254255const unicornsResult = execaSync('unicorns');256expectError(unicornsResult.pipe);257258// The `.pipe()` return value forwards the destination subprocess' iteration, stream conversion and IPC methods.259for await (const pipeLine of subprocess.pipe`stdin`) {260 expectType<string>(pipeLine);261}262263for await (const pipeLine of subprocess.pipe`stdin`.iterable()) {264 expectType<string>(pipeLine);265}266267for await (const pipeLine of subprocess.pipe(bufferSubprocess)) {268 expectType<Uint8Array>(pipeLine);269}270271expectType<Readable>(subprocess.pipe`stdin`.readable());272273expectType<Readable>(subprocess.pipe({all: true})`stdin`.all);274expectType<undefined>(subprocess.pipe`stdin`.all);275276expectType<undefined>(subprocess.pipe`stdin`.sendMessage);277const ipcPipeResult = subprocess.pipe({ipc: true})`stdin`;278expectType<Promise<void>>(ipcPipeResult.sendMessage('message'));279expectType<Promise<Message<'advanced'>>>(ipcPipeResult.getOneMessage());280expectType<AsyncIterableIterator<Message<'advanced'>>>(ipcPipeResult.getEachMessage());281282// `writable()` and `duplex()` write to the destination's `stdin`, which is already piped from the source, so they are not forwarded.283expectError(subprocess.pipe`stdin`.writable());284expectError(subprocess.pipe`stdin`.duplex());
modified:types/subprocess/subprocess.d.ts+30 added-24 removed
13 unmodified lines
14import type {SubprocessStdioStream} from './stdout.js';15import type {SubprocessStdioArray} from './stdio.js';16import type {SubprocessAll} from './all.js';1718// Read-side iteration, stream conversion and `all` methods.19// These are shared between a subprocess and the return value of `subprocess.pipe()`, which forwards them from its destination subprocess.20// `writable()` and `duplex()` are not included: they write to `stdin`, which the pipe already feeds from its source.21export type SubprocessResultMethods<OptionsType extends Options = Options> = {22 /**23 Stream combining/interleaving `subprocess.stdout` and `subprocess.stderr`.2425 This requires the `all` option to be `true`.2627 This is `undefined` if `stdout` and `stderr` options are set to `'inherit'`, `'ignore'`, `Writable` or `integer`, or if the `buffer` option is `false`.28 */29 all: SubprocessAll<OptionsType>;3031 /**32 Subprocesses are [async iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator). They iterate over each output line.33 */34 [Symbol.asyncIterator](): SubprocessAsyncIterable<undefined, OptionsType['encoding']>;3536 /**37 Same as `subprocess[Symbol.asyncIterator]` except options can be provided.38 */39 iterable<IterableOptions extends ReadableOptions = {}>(readableOptions?: IterableOptions): SubprocessAsyncIterable<IterableOptions['binary'], OptionsType['encoding']>;4041 /**42 Converts the subprocess to a readable stream.43 */44 readable(readableOptions?: ReadableOptions): Readable;45};4647type ExecaCustomSubprocess<OptionsType extends Options> =48 & IpcMethods<HasIpc<OptionsType>, OptionsType['serialization']>49 & PipableSubprocess50 & SubprocessResultMethods<OptionsType>51 & {52 /**53 Process identifier ([PID](https://en.wikipedia.org/wiki/Process_identifier)).54
22 unmodified lines
77 */78 stderr: SubprocessStdioStream<'2', OptionsType>;7980 /**51 Stream combining/interleaving `subprocess.stdout` and `subprocess.stderr`.5253 This requires the `all` option to be `true`.5455 This is `undefined` if `stdout` and `stderr` options are set to `'inherit'`, `'ignore'`, `Writable` or `integer`, or if the `buffer` option is `false`.56 */57 all: SubprocessAll<OptionsType>;5859 /**81 The subprocess `stdin`, `stdout`, `stderr` and other files descriptors as an array of streams.8283 Each array item is `null` if the corresponding `stdin`, `stdout`, `stderr` or `stdio` option is set to `'inherit'`, `'ignore'`, `Stream` or `integer`, or if the `buffer` option is `false`.84 */
11 unmodified lines
96 kill(signal?: keyof SignalConstants | number, error?: Error): boolean;97 kill(error?: Error): boolean;9899 /**79 Subprocesses are [async iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator). They iterate over each output line.80 */81 [Symbol.asyncIterator](): SubprocessAsyncIterable<undefined, OptionsType['encoding']>;8283 /**84 Same as `subprocess[Symbol.asyncIterator]` except options can be provided.85 */86 iterable<IterableOptions extends ReadableOptions = {}>(readableOptions?: IterableOptions): SubprocessAsyncIterable<IterableOptions['binary'], OptionsType['encoding']>;8788 /**89 Converts the subprocess to a readable stream.90 */91 readable(readableOptions?: ReadableOptions): Readable;9293 /**100 Converts the subprocess to a writable stream.101 */102 writable(writableOptions?: WritableOptions): Writable;103
23 unmodified lines
modified:types/pipe.d.ts+18 added-6 removed
1import type {Options} from './arguments/options.js';2import type {Result} from './return/result.js';3import type {FromOption, ToOption} from './arguments/fd-options.js';4import type {ResultPromise} from './subprocess/subprocess.js';4import type {ResultPromise, SubprocessResultMethods} from './subprocess/subprocess.js';5import type {IpcMethods, HasIpc} from './ipc.js';6import type {TemplateExpression} from './methods/template.js';78// `subprocess.pipe()` options9type PipeOptions = {
14 unmodified lines
24 */25 readonly unpipeSignal?: AbortSignal;26};2728// Methods forwarded from the destination subprocess to the return value of `subprocess.pipe()`, so its output can be iterated, converted to a stream, or used for IPC.29type PipeResultMethods<OptionsType extends Options> =30 & SubprocessResultMethods<OptionsType>31 & IpcMethods<HasIpc<OptionsType>, OptionsType['serialization']>;3233// Same as `PipeResultMethods`, but when the destination is another `execa()` call, so its own option types are kept.34// The base `Options` is only used to compute the property names, which do not depend on the specific options.35type PipeResultMethodsFrom<Destination extends ResultPromise> = Pick<Destination, keyof PipeResultMethods<Options>>;3637// `subprocess.pipe()`38export type PipableSubprocess = {39 /**40 [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the subprocess' `stdout` to a second Execa subprocess' `stdin`. This resolves with that second subprocess' result. If either subprocess is rejected, this is rejected with that subprocess' error instead.4142 This follows the same syntax as `execa(file, arguments?, options?)` except both regular options and pipe-specific options can be specified.4344 Like a subprocess, the return value can be [iterated](https://github.com/sindresorhus/execa/blob/main/docs/lines.md#progressive-splitting), [converted to a stream](https://github.com/sindresorhus/execa/blob/main/docs/streams.md#converting-a-subprocess-to-a-stream), or used for [IPC](https://github.com/sindresorhus/execa/blob/main/docs/ipc.md) with the destination subprocess.45 */46 pipe<OptionsType extends Options & PipeOptions = {}>(47 file: string | URL,48 arguments?: readonly string[],49 options?: OptionsType,38 ): Promise<Result<OptionsType>> & PipableSubprocess;50 ): Promise<Result<OptionsType>> & PipableSubprocess & PipeResultMethods<OptionsType>;51 pipe<OptionsType extends Options & PipeOptions = {}>(52 file: string | URL,53 options?: OptionsType,42 ): Promise<Result<OptionsType>> & PipableSubprocess;54 ): Promise<Result<OptionsType>> & PipableSubprocess & PipeResultMethods<OptionsType>;5556 /**57 Like `subprocess.pipe(file, arguments?, options?)` but using a `command` template string instead. This follows the same syntax as `$`.58 */59 pipe(templates: TemplateStringsArray, ...expressions: readonly TemplateExpression[]):48 Promise<Result<{}>> & PipableSubprocess;60 Promise<Result<{}>> & PipableSubprocess & PipeResultMethods<{}>;61 pipe<OptionsType extends Options & PipeOptions = {}>(options: OptionsType):62 (templates: TemplateStringsArray, ...expressions: readonly TemplateExpression[])51 => Promise<Result<OptionsType>> & PipableSubprocess;63 => Promise<Result<OptionsType>> & PipableSubprocess & PipeResultMethods<OptionsType>;6465 /**66 Like `subprocess.pipe(file, arguments?, options?)` but using the return value of another `execa()` call instead.67 */68 pipe<Destination extends ResultPromise>(destination: Destination, options?: PipeOptions):57 Promise<Awaited<Destination>> & PipableSubprocess;69 Promise<Awaited<Destination>> & PipableSubprocess & PipeResultMethodsFrom<Destination>;70};7172export {};