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
Provenance
- Commit
c31c94c- Tree
01ca615- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
4cafc3f
11 files changed+829 added−59 removed
modified:docs/api.md+2 added
251 unmodified lines252 [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.253 254 This 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.255 256+Like 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.257+258 [More info.](pipe.md#array-syntax)259 260 ### subprocess.pipe\`command\`261 ### subprocess.pipe(options)\`command\`1048 unmodified linesmodified:docs/pipe.md+10 added
64 unmodified lines65666768697071727374757677787980818295 unmodified lines64 unmodified linesconst sourceResult = destinationResult.pipedFrom[0];console.log(sourceResult.stdout); // Full output of `npm run build````
## Iterate, stream and IPC
Just like a regular subprocess, the value returned by `subprocess.pipe()` can be [iterated](lines.md#progressive-splitting) over its output lines, [converted to a readable stream](streams.md#converting-a-subprocess-to-a-stream), or used to exchange [IPC messages](ipc.md) with the destination subprocess.
```jsfor await (const line of execa`npm run build`.pipe`sort`) { console.log(line);}```
## Errors
When either subprocess fails, `subprocess.pipe()` is rejected with that subprocess' error. If the destination subprocess fails, [`error.pipedFrom`](api.md#resultpipedfrom) includes the source subprocess' result, which is useful for debugging.
95 unmodified linesmodified:lib/ipc/get-each.js+32 added-9 removed
1 unmodified line2 import {validateIpcMethod, disconnect, getStrictResponseError} from './validation.js';3 import {getIpcEmitter, isConnected} from './forward.js';4 import {addReference, removeReference} from './reference.js';5 6+export const internalGetEachMessageOptions = Symbol('internalGetEachMessageOptions');7+8 // Like `[sub]process.on('message')` but promise-based7-export const getEachMessage = ({anyProcess, channel, isSubprocess, ipc}, {reference = true} = {}) => loopOnMessages({8- anyProcess,9- channel,10- isSubprocess,11- ipc,12- shouldAwait: !isSubprocess,13- reference,14-});9+export 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] ?? {};13 14+ return loopOnMessages({15+ ...subprocessInfo,16+ shouldAwait,17+ reference,18+ signal,19+ });20+};21+22 // Same but used internally17-export const loopOnMessages = ({anyProcess, channel, isSubprocess, ipc, shouldAwait, reference}) => {23+export const loopOnMessages = ({anyProcess, channel, isSubprocess, ipc, shouldAwait, reference, signal}) => {24 validateIpcMethod({25 methodName: 'getEachMessage',26 isSubprocess,27 ipc,3 unmodified lines31 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 lines51 reference,52 });53 };54 55+const stopOnAbort = (signal, controller) => {56+ if (signal === undefined) {57+ return;58+ }59+60+ if (signal.aborted) {61+ controller.abort();62+ return;63+ }64+65+ // 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+};70+71 const stopOnDisconnect = async (anyProcess, ipcEmitter, controller) => {72 try {73 await once(ipcEmitter, 'disconnect', {signal: controller.signal});74 controller.abort();38 unmodified linesmodified:lib/ipc/get-one.js+25 added-2 removed
6 unmodified lines7 } from './validation.js';8 import {getIpcEmitter, isConnected} from './forward.js';9 import {addReference, removeReference} from './reference.js';10 11+export const internalGetOneMessageOptions = Symbol('internalGetOneMessageOptions');12+13 // Like `[sub]process.once('message')` but promise-based12-export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, {reference = true, filter} = {}) => {14+export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, options = {}) => {15+ const {reference = true, filter} = options;16+ const {signal} = options[internalGetOneMessageOptions] ?? {};17+18 validateIpcMethod({19 methodName: 'getOneMessage',20 isSubprocess,21 ipc,5 unmodified lines27 channel,28 isSubprocess,29 filter,30 reference,31+ signal,32 });33 };34 29-const getOneMessageAsync = async ({anyProcess, channel, isSubprocess, filter, reference}) => {35+const 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);40+41 try {42 return await Promise.race([43 getMessage(ipcEmitter, filter, controller),44 throwOnDisconnect(ipcEmitter, isSubprocess, controller),7 unmodified lines52 removeReference(channel, reference);53 }54 };55 56+const stopOnAbort = (signal, controller) => {57+ if (signal === undefined) {58+ return;59+ }60+61+ if (signal.aborted) {62+ controller.abort();63+ return;64+ }65+66+ signal.addEventListener('abort', () => {67+ controller.abort();68+ }, {once: true, signal: controller.signal});69+};70+71 const getMessage = async (ipcEmitter, filter, {signal}) => {72 if (filter === undefined) {73 const [message] = await once(ipcEmitter, 'message', {signal});74 return message;18 unmodified linesmodified:lib/pipe/setup.js+167 added-11 removed
1 import isPlainObject from 'is-plain-obj';2+import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';3+import {initializeConcurrentStreams} from '../convert/concurrent.js';4+import {createIterable} from '../convert/iterable.js';5+import {createReadable} from '../convert/readable.js';6+import {internalGetOneMessageOptions} from '../ipc/get-one.js';7+import {internalGetEachMessageOptions} from '../ipc/get-each.js';8 import {normalizePipeArguments} from './pipe-arguments.js';9 import {handlePipeArgumentsError} from './throw.js';10 import {waitForBothSubprocesses} from './sequence.js';11 import {pipeSubprocessStream} from './streaming.js';8 unmodified lines20 });21 }22 23 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 };35 36+/*37+The 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+*/39+const forwardDestinationMethods = (promise, destination, pipeFailureSignal) => {40+ if (destination === undefined) {41+ return;42+ }43+44+ forwardReadableMethods(promise, destination);45+ forwardIpcMethods(promise, destination, pipeFailureSignal);46+};47+48+const 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;53+54+ 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+};65+66+const forwardAll = (promise, destination) => {67+ if (destination.all === undefined) {68+ promise.all = undefined;69+ return;70+ }71+72+ 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+};83+84+const setAllProperty = (promise, value) => {85+ Object.defineProperty(promise, 'all', {86+ value,87+ writable: true,88+ enumerable: true,89+ configurable: true,90+ });91+};92+93+const createPipeReadable = (promise, readableOptions, ...arguments_) => {94+ const readable = createReadable(readableOptions, ...arguments_);95+ destroyOnPipeFailure(promise, readable);96+ return readable;97+};98+99+const destroyOnPipeFailure = async (promise, readable) => {100+ try {101+ await promise;102+ } catch (error) {103+ readable.destroy(error);104+ }105+};106+107+const 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+};112+113+const 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+};118+119+const waitForOnePipeMessage = async (pipeFailureSignal, messagePromise, controller) => {120+ try {121+ return await Promise.race([messagePromise, getSignalRejection(pipeFailureSignal, controller.signal)]);122+ } finally {123+ controller.abort();124+ }125+};126+127+const getSignalRejection = (signal, listenerSignal) => new Promise((_, reject) => {128+ if (signal.aborted) {129+ reject(signal.reason);130+ return;131+ }132+133+ signal.addEventListener('abort', () => {134+ reject(signal.reason);135+ }, {once: true, signal: listenerSignal});136+});137+138+const 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+};145+146+const iterateOnPipeMessages = async function * (promise, iterator, controller) {147+ try {148+ yield * iterator;149+ } finally {150+ controller.abort();151+ await promise;152+ }153+};154+155+const 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+ }160+161+ 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+};165+166+const abortOnSignal = (signal, controller) => {167+ if (signal.aborted) {168+ controller.abort();169+ return;170+ }171+172+ // 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+};177+178+// `writable()` and `duplex()` are intentionally not forwarded: they write to the destination's `stdin`, which is already being piped from the source.179+180 // Asynchronous logic when piping subprocesses181 const handlePipePromise = async ({182 sourcePromise,183 sourceStream,4 unmodified lines188 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 lines213 fileDescriptors,214 startTime,215 }),216 ]);217+ } catch (error) {218+ pipeFailureController.abort(error);219+ throw error;220 } finally {221 maxListenersController.abort();222 }223 };5 unmodified linesadded:test/fixtures/stdin-distinct-both.js+7 added
1234567#!/usr/bin/env nodeimport process from 'node:process';import {text} from 'node:stream/consumers';
const input = await text(process.stdin);process.stdout.write(`${input}:stdout`);process.stderr.write(`${input}:stderr`);added:test/pipe/methods.js+435 added
1+import {setTimeout} from 'node:timers/promises';2+import {Readable} from 'node:stream';3+import {text} from 'node:stream/consumers';4+import test from 'ava';5+import {execa} from '../../index.js';6+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7+import {simpleFull, noNewlinesFull, noNewlinesChunks} from '../helpers/lines.js';8+import {foobarString, foobarArray} from '../helpers/input.js';9+10+setFixtureDirectory();11+12+const timeoutSymbol = Symbol('timeout');13+14+// `stdin.js` pipes its stdin to its stdout, so the piped output equals the source output15+const pipeSimple = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js');16+const pipeAll = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js', {all: true});17+const pipeDistinctBoth = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin-distinct-both.js');18+19+const 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+ ]);25+26+ t.not(result, timeoutSymbol);27+ return result;28+};29+30+const cleanupSubprocesses = async (...subprocesses) => {31+ for (const subprocess of subprocesses) {32+ subprocess.kill();33+ }34+35+ await Promise.allSettled(subprocesses);36+};37+38+const getPipeMessages = async piped => {39+ const messages = [];40+ for await (const message of piped.getEachMessage()) {41+ messages.push(message);42+ }43+44+ return messages;45+};46+47+test('The .pipe() return value can be iterated', async t => {48+ const lines = [];49+ for await (const line of pipeSimple()) {50+ lines.push(line);51+ }52+53+ t.deepEqual(lines, noNewlinesChunks);54+});55+56+test('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+ }61+62+ t.deepEqual(lines, noNewlinesChunks);63+});64+65+test('The .pipe() return value has a .readable() method', async t => {66+ t.is(await text(pipeSimple().readable()), simpleFull);67+});68+69+test('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+ ]);75+76+ t.is(output, simpleFull);77+ t.is(secondOutput, simpleFull);78+});79+80+test('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+ }85+86+ t.deepEqual(chunks, noNewlinesChunks);87+ t.is(chunks.join(''), noNewlinesFull);88+});89+90+test('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+});96+97+test('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');100+101+ t.is(piped.all, undefined);102+ t.is(descriptor.value, undefined);103+ t.is(descriptor.get, undefined);104+ await piped;105+});106+107+test('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+});113+114+test('The .pipe() return value .all is created lazily and cached', async t => {115+ const piped = pipeAll();116+ const descriptor = Object.getOwnPropertyDescriptor(piped, 'all');117+118+ 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+});126+127+test('The .pipe() return value .readable() can read destination stderr', async t => {128+ const piped = pipeDistinctBoth();129+130+ t.is(await text(piped.readable({from: 'stderr'})), `${simpleFull}:stderr`);131+ await piped;132+});133+134+test('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+ }140+141+ t.deepEqual(lines, ['aaa', 'bbb', 'ccc:stderr']);142+ await piped;143+});144+145+test('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+});151+152+test('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});154+155+ t.deepEqual(156+ await Promise.all([getPipeMessages(piped), getPipeMessages(piped)]),157+ [foobarArray, foobarArray],158+ );159+160+ const {ipcOutput} = await piped;161+ t.deepEqual(ipcOutput, foobarArray);162+});163+164+test('The .pipe() return value .getEachMessage() preserves setup errors', async t => {165+ const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});166+167+ t.throws(() => {168+ piped.getEachMessage(null);169+ }, {instanceOf: TypeError});170+171+ await piped;172+});173+174+test('The .pipe() return value .getEachMessage() waits for source failure', async t => {175+ const piped = execa('fail.js').pipe('ipc-send-twice.js', {ipc: true});176+177+ 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+});183+184+test('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+ });191+192+ const piped = source.pipe(destination, {unpipeSignal: abortController.signal});193+ const iterator = piped.getEachMessage();194+ t.deepEqual(await iterator.next(), {done: false, value: foobarString});195+196+ const readerPromise = t.throwsAsync(iterator.next(), {message: /Pipe canceled/});197+ abortController.abort();198+ await assertSettles(t, readerPromise);199+});200+201+test('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+ });208+209+ const piped = source.pipe(destination, {unpipeSignal: abortController.signal});210+ const iterators = [211+ piped.getEachMessage(),212+ piped.getEachMessage(),213+ ];214+215+ 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+ );222+223+ 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+});227+228+const assertCanceledPipeMessageReader = async (t, getReader, abortBeforePipe = false) => {229+ const abortController = new AbortController();230+ if (abortBeforePipe) {231+ abortController.abort();232+ }233+234+ 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+ });239+240+ const piped = source.pipe(destination, {unpipeSignal: abortController.signal});241+ const readerPromise = t.throwsAsync(getReader(piped), {message: /Pipe canceled/});242+243+ if (!abortBeforePipe) {244+ abortController.abort();245+ }246+247+ await assertSettles(t, readerPromise);248+ await t.throwsAsync(piped, {message: /Pipe canceled/});249+};250+251+test('The .pipe() return value .getEachMessage() waits for pipe cancellation before IPC messages', async t => {252+ await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next());253+});254+255+test('The .pipe() return value .getEachMessage() waits for already canceled pipes', async t => {256+ await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next(), true);257+});258+259+test('The .pipe() return value .getOneMessage() waits for pipe cancellation before IPC messages', async t => {260+ await assertCanceledPipeMessageReader(t, piped => piped.getOneMessage());261+});262+263+test('The .pipe() return value .getOneMessage() waits for already canceled pipes', async t => {264+ await assertCanceledPipeMessageReader(t, piped => piped.getOneMessage(), true);265+});266+267+test('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+ });273+274+ const piped = source.pipe(destination);275+ const iterator = piped.getEachMessage();276+277+ 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+});284+285+test('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();289+290+ 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+});295+296+test('The .pipe() return value .getEachMessage() propagates destination failure', async t => {297+ const piped = execa('empty.js').pipe('ipc-send-fail.js', {ipc: true});298+299+ 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/});304+305+ const {ipcOutput} = await t.throwsAsync(piped);306+ t.deepEqual(ipcOutput, [foobarString]);307+});308+309+test('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);312+313+ 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);320+321+ const {ipcOutput, stdout} = await piped;322+ t.deepEqual(ipcOutput, [foobarString]);323+ t.is(stdout, '.');324+});325+326+test('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+ });332+333+ const piped = source.pipe(destination);334+ const {message} = t.throws(() => piped.getEachMessage());335+336+ t.true(message.includes('subprocess.getEachMessage() can only be used'));337+ source.kill();338+ destination.kill();339+ await Promise.allSettled([source, destination, piped]);340+});341+342+test('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+});348+349+test('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+ }354+355+ t.deepEqual(lines, noNewlinesChunks);356+});357+358+test('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+});361+362+test('The .pipe() return value iteration waits for source failure', async t => {363+ const piped = execa('fail.js').pipe('stdin.js');364+365+ 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+});371+372+test('The .pipe() return value .readable() waits for source failure', async t => {373+ const piped = execa('fail.js').pipe('stdin.js');374+375+ await t.throwsAsync(text(piped.readable()), {message: /Command failed with exit code 2/});376+});377+378+test('The .pipe() return value .all waits for source failure', async t => {379+ const piped = execa('fail.js').pipe('stdin.js', {all: true});380+381+ await t.throwsAsync(text(piped.all), {message: /Command failed with exit code 2/});382+});383+384+const assertCanceledPipeReader = async (t, getReader, abortBeforePipe = false) => {385+ const abortController = new AbortController();386+ if (abortBeforePipe) {387+ abortController.abort();388+ }389+390+ const source = execa('stdin.js');391+ const destination = execa('stdin.js', {all: true});392+ t.teardown(async () => {393+ await cleanupSubprocesses(source, destination);394+ });395+396+ const piped = source.pipe(destination, {unpipeSignal: abortController.signal});397+ const readerPromise = t.throwsAsync(getReader(piped), {message: /Pipe canceled/});398+399+ if (!abortBeforePipe) {400+ abortController.abort();401+ }402+403+ await assertSettles(t, readerPromise, 200);404+};405+406+test('The .pipe() return value .readable() waits for pipe cancellation', async t => {407+ await assertCanceledPipeReader(t, piped => text(piped.readable()));408+});409+410+test('The .pipe() return value .all waits for pipe cancellation', async t => {411+ await assertCanceledPipeReader(t, piped => text(piped.all));412+});413+414+test('The .pipe() return value .readable() waits for already canceled pipes', async t => {415+ await assertCanceledPipeReader(t, piped => text(piped.readable()), true);416+});417+418+test('The .pipe() return value .all waits for already canceled pipes', async t => {419+ await assertCanceledPipeReader(t, piped => text(piped.all), true);420+});421+422+test('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+ ];428+429+ for (const pipePromise of piped) {430+ t.is(typeof pipePromise.iterable, 'function');431+ t.is(typeof pipePromise[Symbol.asyncIterator], 'function');432+ }433+434+ await Promise.all(piped);435+});modified:test/pipe/sequence.js+73 added-7 removed
1 import {once} from 'node:events';2 import process from 'node:process';3 import {PassThrough} from 'node:stream';4+import {setTimeout} from 'node:timers/promises';5 import test from 'ava';6 import {execa} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {foobarString} from '../helpers/input.js';2 unmodified lines11 12 setFixtureDirectory();13 14 const isLinux = process.platform === 'linux';15+const timeoutSymbol = Symbol('timeout');16 17+const assertUnhandledRejection = async (t, pipePromise, unhandledRejectionPromise) => {18+ const result = await Promise.race([19+ unhandledRejectionPromise,20+ setTimeout(500, timeoutSymbol),21+ ]);22+23+ t.not(result, timeoutSymbol);24+25+ if (result === timeoutSymbol) {26+ return;27+ }28+29+ const [reason, unhandledPromise] = result;30+ t.is(unhandledPromise, pipePromise);31+ t.regex(reason.message, /Command failed with exit code 2/);32+};33+34+const 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+};47+48 test('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 lines299 const destination = execa('fail.js');300 await t.throwsAsync(source.pipe(destination));301 });302 270-test('Need to await .pipe() return value', async t => {303+test.serial('Need to await .pipe() return value', async t => {304+ await assertUnhandledPipePromise(t);305+});306+307+test.serial('Need to await .pipe() return value, "all" option', async t => {308+ await assertUnhandledPipePromise(t, {destinationOptions: {all: true}});309+});310+311+test.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+});320+321+test.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');326+327+ 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 });333 334+test.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();340+341+ 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+});347+348 if (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 linesmodified:test-d/pipe.test-d.ts+30 added
1 import {createWriteStream} from 'node:fs';2+import type {Readable} from 'node:stream';3 import {expectType, expectNotType, expectError} from 'tsd';4 import {5 execa,6 execaSync,7 $,8 type Result,9+ type Message,10 } from '../index.js';11 12 const fileUrl = new URL('file:///test');13 const stringArray = ['foo', 'bar'] as const;239 unmodified lines253 expectType<undefined>(ignoreShortcutScriptPipeResult.stdout);254 255 const unicornsResult = execaSync('unicorns');256 expectError(unicornsResult.pipe);257+258+// The `.pipe()` return value forwards the destination subprocess' iteration, stream conversion and IPC methods.259+for await (const pipeLine of subprocess.pipe`stdin`) {260+ expectType<string>(pipeLine);261+}262+263+for await (const pipeLine of subprocess.pipe`stdin`.iterable()) {264+ expectType<string>(pipeLine);265+}266+267+for await (const pipeLine of subprocess.pipe(bufferSubprocess)) {268+ expectType<Uint8Array>(pipeLine);269+}270+271+expectType<Readable>(subprocess.pipe`stdin`.readable());272+273+expectType<Readable>(subprocess.pipe({all: true})`stdin`.all);274+expectType<undefined>(subprocess.pipe`stdin`.all);275+276+expectType<undefined>(subprocess.pipe`stdin`.sendMessage);277+const ipcPipeResult = subprocess.pipe({ipc: true})`stdin`;278+expectType<Promise<void>>(ipcPipeResult.sendMessage('message'));279+expectType<Promise<Message<'advanced'>>>(ipcPipeResult.getOneMessage());280+expectType<AsyncIterableIterator<Message<'advanced'>>>(ipcPipeResult.getEachMessage());281+282+// `writable()` and `duplex()` write to the destination's `stdin`, which is already piped from the source, so they are not forwarded.283+expectError(subprocess.pipe`stdin`.writable());284+expectError(subprocess.pipe`stdin`.duplex());modified:types/subprocess/subprocess.d.ts+30 added-24 removed
13 unmodified lines14 import type {SubprocessStdioStream} from './stdout.js';15 import type {SubprocessStdioArray} from './stdio.js';16 import type {SubprocessAll} from './all.js';17 18+// 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.21+export type SubprocessResultMethods<OptionsType extends Options = Options> = {22+ /**23+ Stream combining/interleaving `subprocess.stdout` and `subprocess.stderr`.24+25+ This requires the `all` option to be `true`.26+27+ 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>;30+31+ /**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']>;35+36+ /**37+ Same as `subprocess[Symbol.asyncIterator]` except options can be provided.38+ */39+ iterable<IterableOptions extends ReadableOptions = {}>(readableOptions?: IterableOptions): SubprocessAsyncIterable<IterableOptions['binary'], OptionsType['encoding']>;40+41+ /**42+ Converts the subprocess to a readable stream.43+ */44+ readable(readableOptions?: ReadableOptions): Readable;45+};46+47 type 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 lines77 */78 stderr: SubprocessStdioStream<'2', OptionsType>;79 80 /**51- Stream combining/interleaving `subprocess.stdout` and `subprocess.stderr`.52-53- This requires the `all` option to be `true`.54-55- 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>;58-59- /**81 The subprocess `stdin`, `stdout`, `stderr` and other files descriptors as an array of streams.82 83 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 lines96 kill(signal?: keyof SignalConstants | number, error?: Error): boolean;97 kill(error?: Error): boolean;98 99 /**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']>;82-83- /**84- Same as `subprocess[Symbol.asyncIterator]` except options can be provided.85- */86- iterable<IterableOptions extends ReadableOptions = {}>(readableOptions?: IterableOptions): SubprocessAsyncIterable<IterableOptions['binary'], OptionsType['encoding']>;87-88- /**89- Converts the subprocess to a readable stream.90- */91- readable(readableOptions?: ReadableOptions): Readable;92-93- /**100 Converts the subprocess to a writable stream.101 */102 writable(writableOptions?: WritableOptions): Writable;103 23 unmodified linesmodified:types/pipe.d.ts+18 added-6 removed
1 import type {Options} from './arguments/options.js';2 import type {Result} from './return/result.js';3 import type {FromOption, ToOption} from './arguments/fd-options.js';4-import type {ResultPromise} from './subprocess/subprocess.js';4+import type {ResultPromise, SubprocessResultMethods} from './subprocess/subprocess.js';5+import type {IpcMethods, HasIpc} from './ipc.js';6 import type {TemplateExpression} from './methods/template.js';7 8 // `subprocess.pipe()` options9 type PipeOptions = {14 unmodified lines24 */25 readonly unpipeSignal?: AbortSignal;26 };27 28+// 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.29+type PipeResultMethods<OptionsType extends Options> =30+ & SubprocessResultMethods<OptionsType>31+ & IpcMethods<HasIpc<OptionsType>, OptionsType['serialization']>;32+33+// 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.35+type PipeResultMethodsFrom<Destination extends ResultPromise> = Pick<Destination, keyof PipeResultMethods<Options>>;36+37 // `subprocess.pipe()`38 export 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.41 42 This follows the same syntax as `execa(file, arguments?, options?)` except both regular options and pipe-specific options can be specified.43+44+ 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>;55 56 /**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>;64 65 /**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 };71 72 export {};