Improve piping processes (#834)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 30a662d · Browse files · 23 files·+1511 added−256 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
23 files+1511 added−256 removed
- tests:+1114 added−110 removed
- other:+397 added−146 removed
Provenance
- Commit
1a47ea2- Tree
65d3504- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
30a662d
23 files changed+1511 added−256 removed
modified:docs/scripts.md+6 added-4 removed
586 unmodified lines587 ### Piping stdout to another command588 589 ```sh590 # Bash591-echo example | cat591+echo npm run build | sort | head -n2592 ```593 594 ```js595 // zx596-await $`echo example | cat`;596+await $`npm run build | sort | head -n2`;597 ```598 599 ```js600 // Execa601-await $`echo example`.pipe($({stdin: 'pipe'})`cat`);601+await $`npm run build`602+ .pipe($({stdin: 'pipe'})`sort`)603+ .pipe($({stdin: 'pipe'})`head -n2`);604 ```605 606 ### Piping stdout and stderr to another command607 12 unmodified lines620 ```621 622 ```js623 // Execa622-await $({all: true})`echo example`.pipe($({stdin: 'pipe'})`cat`, 'all');624+await $({all: true})`echo example`.pipe($({from: 'all', stdin: 'pipe'})`cat`);625 ```626 627 ### Piping stdout to a file628 50 unmodified linesadded:lib/pipe/abort.js+13 added
12345678910111213import {aborted} from 'node:util';import {createNonCommandError} from './validate.js';
export const unpipeOnAbort = (signal, ...args) => signal === undefined ? [] : [unpipeOnSignalAbort(signal, ...args)];
const unpipeOnSignalAbort = async (signal, sourceStream, mergedStream, {stdioStreamsGroups, options}) => { await aborted(signal, sourceStream); await mergedStream.remove(sourceStream); const error = new Error('Pipe cancelled by `signal` option.'); throw createNonCommandError({error, stdioStreamsGroups, options});};added:lib/pipe/sequence.js+24 added
123456789101112131415161718192021222324// Like Bash, we await both processes. This is unlike some other shells which only await the destination process.// Like Bash with the `pipefail` option, if either process fails, the whole pipe fails.// Like Bash, if both processes fail, we return the failure of the destination.// This ensures both processes' errors are present, using `error.pipedFrom`.export const waitForBothProcesses = async (source, destination) => { const [ {status: sourceStatus, reason: sourceReason, value: sourceResult = sourceReason}, {status: destinationStatus, reason: destinationReason, value: destinationResult = destinationReason}, ] = await Promise.allSettled([source, destination]);
if (!destinationResult.pipedFrom.includes(sourceResult)) { destinationResult.pipedFrom.push(sourceResult); }
if (destinationStatus === 'rejected') { throw destinationResult; }
if (sourceStatus === 'rejected') { throw sourceResult; }
return destinationResult;};added:lib/pipe/setup.js+25 added
12345678910111213141516171819202122232425import {normalizePipeArguments} from './validate.js';import {waitForBothProcesses} from './sequence.js';import {pipeProcessStream} from './streaming.js';import {unpipeOnAbort} from './abort.js';
// Pipe a process' `stdout`/`stderr`/`stdio` into another process' `stdin`export const pipeToProcess = (sourceInfo, destination, pipeOptions) => { const promise = handlePipePromise(sourceInfo, destination, pipeOptions); promise.pipe = pipeToProcess.bind(undefined, {...sourceInfo, spawned: destination}); return promise;};
const handlePipePromise = async (sourceInfo, destination, {from, signal} = {}) => { const {source, sourceStream, destinationStream} = normalizePipeArguments(destination, from, sourceInfo); const maxListenersController = new AbortController(); try { const mergedStream = pipeProcessStream(sourceStream, destinationStream, maxListenersController); return await Promise.race([ waitForBothProcesses(source, destination), ...unpipeOnAbort(signal, sourceStream, mergedStream, sourceInfo), ]); } finally { maxListenersController.abort(); }};added:lib/pipe/streaming.js+69 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import {finished} from 'node:stream/promises';import mergeStreams from '@sindresorhus/merge-streams';import {incrementMaxListeners} from '../stdio/utils.js';
// The piping behavior is like Bash.// In particular, when one process exits, the other is not terminated by a signal.// Instead, its stdout (for the source) or stdin (for the destination) closes.// If the process uses it, it will make it error with SIGPIPE or EPIPE (for the source) or end (for the destination).// If it does not use it, it will continue running.// This allows for processes to gracefully exit and lower the coupling between processes.export const pipeProcessStream = (sourceStream, destinationStream, maxListenersController) => { const mergedStream = MERGED_STREAMS.has(destinationStream) ? pipeMoreProcessStream(sourceStream, destinationStream) : pipeFirstProcessStream(sourceStream, destinationStream); incrementMaxListeners(sourceStream, SOURCE_LISTENERS_PER_PIPE, maxListenersController.signal); return mergedStream;};
// We use `merge-streams` to allow for multiple sources to pipe to the same destination.const pipeFirstProcessStream = (sourceStream, destinationStream) => { const mergedStream = mergeStreams([sourceStream]); mergedStream.pipe(destinationStream, {end: false});
onSourceStreamFinish(mergedStream, destinationStream); onDestinationStreamFinish(mergedStream, destinationStream); MERGED_STREAMS.set(destinationStream, mergedStream); return mergedStream;};
const pipeMoreProcessStream = (sourceStream, destinationStream) => { const mergedStream = MERGED_STREAMS.get(destinationStream); mergedStream.add(sourceStream); return mergedStream;};
const onSourceStreamFinish = async (mergedStream, destinationStream) => { try { await finished(mergedStream, {cleanup: true, readable: true, writable: false}); } catch {}
endDestinationStream(destinationStream);};
export const endDestinationStream = destinationStream => { if (destinationStream.writable) { destinationStream.end(); }};
const onDestinationStreamFinish = async (mergedStream, destinationStream) => { try { await finished(destinationStream, {cleanup: true, readable: false, writable: true}); } catch {}
abortSourceStream(mergedStream); MERGED_STREAMS.delete(destinationStream);};
export const abortSourceStream = mergedStream => { if (mergedStream.readable) { mergedStream.destroy(); }};
const MERGED_STREAMS = new WeakMap();
// Number of listeners set up on `sourceStream` by each `sourceStream.pipe(destinationStream)`// Those are added by `merge-streams`const SOURCE_LISTENERS_PER_PIPE = 2;added:lib/pipe/validate.js+145 added
1+import {ChildProcess} from 'node:child_process';2+import {STANDARD_STREAMS_ALIASES} from '../stdio/utils.js';3+import {makeEarlyError} from '../error.js';4+import {abortSourceStream, endDestinationStream} from './streaming.js';5+6+export const normalizePipeArguments = (destination, from, {spawned: source, stdioStreamsGroups, options}) => {7+ const {destinationStream, destinationError} = getDestinationStream(destination);8+ const {sourceStream, sourceError} = getSourceStream(source, stdioStreamsGroups, from, options);9+ handlePipeArgumentsError({sourceStream, sourceError, destinationStream, destinationError, stdioStreamsGroups, options});10+ return {source, sourceStream, destinationStream};11+};12+13+const getDestinationStream = destination => {14+ try {15+ if (!isExecaChildProcess(destination)) {16+ throw new TypeError('The first argument must be an Execa child process.');17+ }18+19+ const destinationStream = destination.stdin;20+ if (destinationStream === null) {21+ throw new TypeError('The destination child process\'s stdin must be available. Please set its "stdin" option to "pipe".');22+ }23+24+ return {destinationStream};25+ } catch (error) {26+ return {destinationError: error};27+ }28+};29+30+const isExecaChildProcess = destination => destination instanceof ChildProcess31+ && typeof destination.then === 'function'32+ && typeof destination.pipe === 'function';33+34+const getSourceStream = (source, stdioStreamsGroups, from, options) => {35+ try {36+ const streamIndex = getStreamIndex(stdioStreamsGroups, from);37+ const sourceStream = streamIndex === 'all' ? source.all : source.stdio[streamIndex];38+39+ if (sourceStream === null || sourceStream === undefined) {40+ throw new TypeError(getInvalidStdioOptionMessage(streamIndex, from, options));41+ }42+43+ return {sourceStream};44+ } catch (error) {45+ return {sourceError: error};46+ }47+};48+49+const getStreamIndex = (stdioStreamsGroups, from = 'stdout') => {50+ const streamIndex = STANDARD_STREAMS_ALIASES.includes(from)51+ ? STANDARD_STREAMS_ALIASES.indexOf(from)52+ : from;53+54+ if (streamIndex === 'all') {55+ return streamIndex;56+ }57+58+ if (streamIndex === 0) {59+ throw new TypeError('The "from" option must not be "stdin".');60+ }61+62+ if (!Number.isInteger(streamIndex) || streamIndex < 0) {63+ throw new TypeError(`The "from" option must not be "${streamIndex}".64+It must be "stdout", "stderr", "all" or a file descriptor integer.65+It is optional and defaults to "stdout".`);66+ }67+68+ const stdioStreams = stdioStreamsGroups[streamIndex];69+ if (stdioStreams === undefined) {70+ throw new TypeError(`The "from" option must not be ${streamIndex}. That file descriptor does not exist.71+Please set the "stdio" option to ensure that file descriptor exists.`);72+ }73+74+ if (stdioStreams[0].direction === 'input') {75+ throw new TypeError(`The "from" option must not be ${streamIndex}. It must be a readable stream, not writable.`);76+ }77+78+ return streamIndex;79+};80+81+const getInvalidStdioOptionMessage = (streamIndex, from, options) => {82+ if (streamIndex === 'all' && !options.all) {83+ return 'The "all" option must be true to use `childProcess.pipe(destinationProcess, {from: "all"})`.';84+ }85+86+ const {optionName, optionValue} = getInvalidStdioOption(streamIndex, options);87+ const pipeOptions = from === undefined ? '' : `, {from: ${serializeOptionValue(from)}}`;88+ return `The \`${optionName}: ${serializeOptionValue(optionValue)}\` option is incompatible with using \`childProcess.pipe(destinationProcess${pipeOptions})\`.89+Please set this option with "pipe" instead.`;90+};91+92+const getInvalidStdioOption = (streamIndex, {stdout, stderr, stdio}) => {93+ const usedIndex = streamIndex === 'all' ? 1 : streamIndex;94+95+ if (usedIndex === 1 && stdout !== undefined) {96+ return {optionName: 'stdout', optionValue: stdout};97+ }98+99+ if (usedIndex === 2 && stderr !== undefined) {100+ return {optionName: 'stderr', optionValue: stderr};101+ }102+103+ return {optionName: `stdio[${usedIndex}]`, optionValue: stdio[usedIndex]};104+};105+106+const serializeOptionValue = optionValue => {107+ if (typeof optionValue === 'string') {108+ return `"${optionValue}"`;109+ }110+111+ return typeof optionValue === 'number' ? `${optionValue}` : 'Stream';112+};113+114+const handlePipeArgumentsError = ({sourceStream, sourceError, destinationStream, destinationError, stdioStreamsGroups, options}) => {115+ const error = getPipeArgumentsError({sourceStream, sourceError, destinationStream, destinationError});116+ if (error !== undefined) {117+ throw createNonCommandError({error, stdioStreamsGroups, options});118+ }119+};120+121+const getPipeArgumentsError = ({sourceStream, sourceError, destinationStream, destinationError}) => {122+ if (sourceError !== undefined && destinationError !== undefined) {123+ return destinationError;124+ }125+126+ if (destinationError !== undefined) {127+ abortSourceStream(sourceStream);128+ return destinationError;129+ }130+131+ if (sourceError !== undefined) {132+ endDestinationStream(destinationStream);133+ return sourceError;134+ }135+};136+137+export const createNonCommandError = ({error, stdioStreamsGroups, options}) => makeEarlyError({138+ error,139+ command: PIPE_COMMAND_MESSAGE,140+ escapedCommand: PIPE_COMMAND_MESSAGE,141+ stdioStreamsGroups,142+ options,143+});144+145+const PIPE_COMMAND_MESSAGE = 'source.pipe(destination)';modified:lib/error.js+3 added
145 unmodified lines146 if ('bufferedData' in error) {147 delete error.bufferedData;148 }149 150+ error.pipedFrom = [];151+152 return error;153 };154 155 export const makeEarlyError = ({30 unmodified lines186 stdout: stdio[1],187 stderr: stdio[2],188 all,189 stdio,190+ pipedFrom: [],191 });deleted:lib/pipe.js-95 removed
1-import {ChildProcess} from 'node:child_process';2-import {isWritableStream} from 'is-stream';3-import {STANDARD_STREAMS_ALIASES} from './stdio/utils.js';4-5-export const pipeToProcess = ({spawned, stdioStreamsGroups, options}, targetProcess, streamName) => {6- validateTargetProcess(targetProcess);7-8- const streamIndex = getStreamIndex(streamName);9- const inputStream = getInputStream(spawned, streamIndex, stdioStreamsGroups);10- validateStdioOption(inputStream, streamIndex, streamName, options);11-12- inputStream.pipe(targetProcess.stdin);13- return targetProcess;14-};15-16-const validateTargetProcess = targetProcess => {17- if (!isExecaChildProcess(targetProcess)) {18- throw new TypeError('The first argument must be an Execa child process.');19- }20-21- if (!isWritableStream(targetProcess.stdin)) {22- throw new TypeError('The target child process\'s stdin must be available.');23- }24-};25-26-const isExecaChildProcess = target => target instanceof ChildProcess && typeof target.then === 'function';27-28-const getStreamIndex = (streamName = 'stdout') => STANDARD_STREAMS_ALIASES.includes(streamName)29- ? STANDARD_STREAMS_ALIASES.indexOf(streamName)30- : streamName;31-32-const getInputStream = (spawned, streamIndex, stdioStreamsGroups) => {33- if (streamIndex === 'all') {34- return spawned.all;35- }36-37- if (streamIndex === 0) {38- throw new TypeError('The second argument must not be "stdin".');39- }40-41- if (!Number.isInteger(streamIndex) || streamIndex < 0) {42- throw new TypeError(`The second argument must not be "${streamIndex}".43-It must be "stdout", "stderr", "all" or a file descriptor integer.44-It is optional and defaults to "stdout".`);45- }46-47- const stdioStreams = stdioStreamsGroups[streamIndex];48- if (stdioStreams === undefined) {49- throw new TypeError(`The second argument must not be ${streamIndex}: that file descriptor does not exist.50-Please set the "stdio" option to ensure that file descriptor exists.`);51- }52-53- if (stdioStreams[0].direction === 'input') {54- throw new TypeError(`The second argument must not be ${streamIndex}: it must be a readable stream, not writable.`);55- }56-57- return spawned.stdio[streamIndex];58-};59-60-const validateStdioOption = (inputStream, streamIndex, streamName, options) => {61- if (inputStream !== null && inputStream !== undefined) {62- return;63- }64-65- if (streamIndex === 'all' && !options.all) {66- throw new TypeError('The "all" option must be true to use `childProcess.pipe(targetProcess, "all")`.');67- }68-69- const {optionName, optionValue} = getInvalidStdioOption(streamIndex, options);70- const pipeArgument = streamName === undefined ? '' : `, ${streamName}`;71- throw new TypeError(`The \`${optionName}: ${serializeOptionValue(optionValue)}\` option is incompatible with using \`childProcess.pipe(targetProcess${pipeArgument})\`.72-Please set this option with "pipe" instead.`);73-};74-75-const getInvalidStdioOption = (streamIndex, {stdout, stderr, stdio}) => {76- const usedIndex = streamIndex === 'all' ? 1 : streamIndex;77-78- if (usedIndex === 1 && stdout !== undefined) {79- return {optionName: 'stdout', optionValue: stdout};80- }81-82- if (usedIndex === 2 && stderr !== undefined) {83- return {optionName: 'stderr', optionValue: stderr};84- }85-86- return {optionName: `stdio[${usedIndex}]`, optionValue: stdio[usedIndex]};87-};88-89-const serializeOptionValue = optionValue => {90- if (typeof optionValue === 'string') {91- return `"${optionValue}"`;92- }93-94- return typeof optionValue === 'number' ? `${optionValue}` : 'Stream';95-};added:test/fixtures/noop-stdin-double.js+6 added
123456#!/usr/bin/env nodeimport process from 'node:process';import {text} from 'node:stream/consumers';
const stdinString = await text(process.stdin);console.log(`${stdinString} ${process.argv[2]}`);added:test/fixtures/stdin-both.js+5 added
12345#!/usr/bin/env nodeimport process from 'node:process';
process.stdin.pipe(process.stdout);process.stdin.pipe(process.stderr);added:test/fixtures/stdin-fail.js+5 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+process.stdin.pipe(process.stdout);5+process.exitCode = 2;added:test/pipe/abort.js+167 added
1+import {once} from 'node:events';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {foobarString} from '../helpers/input.js';6+7+setFixtureDir();8+9+const assertUnPipeError = async (t, pipePromise) => {10+ const error = await t.throwsAsync(pipePromise);11+12+ t.is(error.command, 'source.pipe(destination)');13+ t.is(error.escapedCommand, error.command);14+15+ t.is(typeof error.cwd, 'string');16+ t.true(error.failed);17+ t.false(error.timedOut);18+ t.false(error.isCanceled);19+ t.false(error.isTerminated);20+ t.is(error.exitCode, undefined);21+ t.is(error.signal, undefined);22+ t.is(error.signalDescription, undefined);23+ t.is(error.stdout, undefined);24+ t.is(error.stderr, undefined);25+ t.is(error.all, undefined);26+ t.deepEqual(error.stdio, Array.from({length: error.stdio.length}));27+ t.deepEqual(error.pipedFrom, []);28+29+ t.true(error.originalMessage.includes('Pipe cancelled'));30+ t.true(error.shortMessage.includes(`Command failed: ${error.command}`));31+ t.true(error.shortMessage.includes(error.originalMessage));32+ t.true(error.message.includes(error.shortMessage));33+};34+35+test('Can unpipe a single process', async t => {36+ const abortController = new AbortController();37+ const source = execa('stdin.js');38+ const destination = execa('stdin.js');39+ const pipePromise = source.pipe(destination, {signal: abortController.signal});40+41+ abortController.abort();42+ await assertUnPipeError(t, pipePromise);43+44+ source.stdin.end(foobarString);45+ destination.stdin.end('.');46+47+ t.like(await destination, {stdout: '.'});48+ t.like(await source, {stdout: foobarString});49+});50+51+test('Can use an already aborted signal', async t => {52+ const abortController = new AbortController();53+ abortController.abort();54+ const source = execa('empty.js');55+ const destination = execa('empty.js');56+ const pipePromise = source.pipe(destination, {signal: abortController.signal});57+58+ await assertUnPipeError(t, pipePromise);59+});60+61+test('Can unpipe a process among other sources', async t => {62+ const abortController = new AbortController();63+ const source = execa('stdin.js');64+ const secondSource = execa('noop.js', [foobarString]);65+ const destination = execa('stdin.js');66+ const pipePromise = source.pipe(destination, {signal: abortController.signal});67+ const secondPipePromise = secondSource.pipe(destination);68+69+ abortController.abort();70+ await assertUnPipeError(t, pipePromise);71+72+ source.stdin.end('.');73+74+ t.is(await secondPipePromise, await destination);75+ t.like(await destination, {stdout: foobarString});76+ t.like(await source, {stdout: '.'});77+ t.like(await secondSource, {stdout: foobarString});78+});79+80+test('Can unpipe a process among other sources on the same process', async t => {81+ const abortController = new AbortController();82+ const source = execa('stdin-both.js');83+ const destination = execa('stdin.js');84+ const pipePromise = source.pipe(destination, {signal: abortController.signal});85+ const secondPipePromise = source.pipe(destination, {from: 'stderr'});86+87+ abortController.abort();88+ await assertUnPipeError(t, pipePromise);89+90+ source.stdin.end(foobarString);91+92+ t.is(await secondPipePromise, await destination);93+ t.like(await destination, {stdout: foobarString});94+ t.like(await source, {stdout: foobarString, stderr: foobarString});95+});96+97+test('Can unpipe a process among other destinations', async t => {98+ const abortController = new AbortController();99+ const source = execa('stdin.js');100+ const destination = execa('stdin.js');101+ const secondDestination = execa('stdin.js');102+ const pipePromise = source.pipe(destination, {signal: abortController.signal});103+ const secondPipePromise = source.pipe(secondDestination);104+105+ abortController.abort();106+ await assertUnPipeError(t, pipePromise);107+108+ source.stdin.end(foobarString);109+ destination.stdin.end('.');110+111+ t.is(await secondPipePromise, await secondDestination);112+ t.like(await destination, {stdout: '.'});113+ t.like(await source, {stdout: foobarString});114+ t.like(await secondDestination, {stdout: foobarString});115+});116+117+test('Can unpipe then re-pipe a process', async t => {118+ const abortController = new AbortController();119+ const source = execa('stdin.js');120+ const destination = execa('stdin.js');121+ const pipePromise = source.pipe(destination, {signal: abortController.signal});122+123+ source.stdin.write('.');124+ const [firstWrite] = await once(source.stdout, 'data');125+ t.is(firstWrite.toString(), '.');126+127+ abortController.abort();128+ await assertUnPipeError(t, pipePromise);129+130+ source.pipe(destination);131+ source.stdin.end('.');132+133+ t.like(await destination, {stdout: '..'});134+ t.like(await source, {stdout: '..'});135+});136+137+test('Can unpipe to prevent termination to propagate to source', async t => {138+ const abortController = new AbortController();139+ const source = execa('stdin.js');140+ const destination = execa('stdin.js');141+ const pipePromise = source.pipe(destination, {signal: abortController.signal});142+143+ abortController.abort();144+ await assertUnPipeError(t, pipePromise);145+146+ destination.kill();147+ t.like(await t.throwsAsync(destination), {signal: 'SIGTERM'});148+149+ source.stdin.end(foobarString);150+ t.like(await source, {stdout: foobarString});151+});152+153+test('Can unpipe to prevent termination to propagate to destination', async t => {154+ const abortController = new AbortController();155+ const source = execa('noop-forever.js', [foobarString]);156+ const destination = execa('stdin.js');157+ const pipePromise = source.pipe(destination, {signal: abortController.signal});158+159+ abortController.abort();160+ await assertUnPipeError(t, pipePromise);161+162+ source.kill();163+ t.like(await t.throwsAsync(source), {signal: 'SIGTERM'});164+165+ destination.stdin.end(foobarString);166+ t.like(await destination, {stdout: foobarString});167+});added:test/pipe/sequence.js+313 added
1+import {once} from 'node:events';2+import process from 'node:process';3+import {PassThrough} from 'node:stream';4+import test from 'ava';5+import {execa} from '../../index.js';6+import {setFixtureDir} from '../helpers/fixtures-dir.js';7+import {foobarString} from '../helpers/input.js';8+import {noopGenerator} from '../helpers/generator.js';9+import {prematureClose} from '../helpers/stdio.js';10+11+setFixtureDir();12+13+const isLinux = process.platform === 'linux';14+15+test('Source stream abort -> destination success', async t => {16+ const source = execa('noop-repeat.js');17+ const destination = execa('stdin.js');18+ const pipePromise = source.pipe(destination);19+ source.stdout.destroy();20+21+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));22+ t.like(await t.throwsAsync(source), {exitCode: 1});23+ await destination;24+});25+26+test('Source stream error -> destination success', async t => {27+ const source = execa('noop-repeat.js');28+ const destination = execa('stdin.js');29+ const pipePromise = source.pipe(destination);30+ const error = new Error('test');31+ source.stdout.destroy(error);32+33+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));34+ t.like(await t.throwsAsync(source), {originalMessage: error.originalMessage, exitCode: 1});35+ await destination;36+});37+38+test('Destination stream abort -> source failure', async t => {39+ const source = execa('noop-repeat.js');40+ const destination = execa('stdin.js');41+ const pipePromise = source.pipe(destination);42+ destination.stdin.destroy();43+44+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));45+ t.like(await t.throwsAsync(destination), prematureClose);46+ t.like(await t.throwsAsync(source), {exitCode: 1});47+});48+49+test('Destination stream error -> source failure', async t => {50+ const source = execa('noop-repeat.js');51+ const destination = execa('stdin.js');52+ const pipePromise = source.pipe(destination);53+ const error = new Error('test');54+ destination.stdin.destroy(error);55+56+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));57+ t.like(await t.throwsAsync(destination), {originalMessage: error.originalMessage, exitCode: 0});58+ t.like(await t.throwsAsync(source), {exitCode: 1});59+});60+61+test('Source success -> destination success', async t => {62+ const source = execa('noop.js', [foobarString]);63+ const destination = execa('stdin.js');64+ const pipePromise = source.pipe(destination);65+66+ t.like(await source, {stdout: foobarString});67+ t.like(await destination, {stdout: foobarString});68+ t.is(await pipePromise, await destination);69+});70+71+test('Destination stream end -> source failure', async t => {72+ const source = execa('noop-repeat.js');73+ const destination = execa('stdin.js');74+ const pipePromise = source.pipe(destination);75+ destination.stdin.end();76+77+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));78+ await destination;79+ t.like(await t.throwsAsync(source), {exitCode: 1});80+});81+82+test('Source normal failure -> destination success', async t => {83+ const source = execa('noop-fail.js', ['1', foobarString]);84+ const destination = execa('stdin.js');85+ const pipePromise = source.pipe(destination);86+87+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));88+ t.like(await t.throwsAsync(source), {stdout: foobarString, exitCode: 2});89+ await destination;90+});91+92+test('Source normal failure -> deep destination success', async t => {93+ const source = execa('noop-fail.js', ['1', foobarString]);94+ const destination = execa('stdin.js');95+ const secondDestination = execa('stdin.js');96+ const pipePromise = source.pipe(destination);97+ const secondPipePromise = destination.pipe(secondDestination);98+99+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));100+ await secondPipePromise;101+ t.like(await t.throwsAsync(source), {stdout: foobarString, exitCode: 2});102+ await destination;103+ await secondDestination;104+});105+106+const testSourceTerminated = async (t, signal) => {107+ const source = execa('noop-repeat.js');108+ const destination = execa('stdin.js');109+ const pipePromise = source.pipe(destination);110+ source.kill(signal);111+112+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));113+ t.like(await t.throwsAsync(source), {signal});114+ await destination;115+};116+117+test('Source SIGTERM -> destination success', testSourceTerminated, 'SIGTERM');118+test('Source SIGKILL -> destination success', testSourceTerminated, 'SIGKILL');119+120+test('Destination success before source -> source success', async t => {121+ const passThroughStream = new PassThrough();122+ const source = execa('stdin.js', {stdin: ['pipe', passThroughStream]});123+ const destination = execa('empty.js');124+ const pipePromise = source.pipe(destination);125+126+ await destination;127+ passThroughStream.end();128+ await source;129+ t.is(await pipePromise, await destination);130+});131+132+test('Destination normal failure -> source failure', async t => {133+ const source = execa('noop-repeat.js');134+ const destination = execa('fail.js');135+ const pipePromise = source.pipe(destination);136+137+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));138+ t.like(await t.throwsAsync(destination), {exitCode: 2});139+ t.like(await t.throwsAsync(source), {exitCode: 1});140+});141+142+test('Destination normal failure -> deep source failure', async t => {143+ const source = execa('noop-repeat.js');144+ const destination = execa('stdin.js');145+ const secondDestination = execa('fail.js');146+ const pipePromise = source.pipe(destination);147+ const secondPipePromise = destination.pipe(secondDestination);148+149+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));150+ t.is(await t.throwsAsync(secondPipePromise), await t.throwsAsync(secondDestination));151+ t.like(await t.throwsAsync(secondDestination), {exitCode: 2});152+ t.like(await t.throwsAsync(destination), {exitCode: 1});153+ t.like(await t.throwsAsync(source), {exitCode: 1});154+});155+156+const testDestinationTerminated = async (t, signal) => {157+ const source = execa('noop-repeat.js');158+ const destination = execa('stdin.js');159+ const pipePromise = source.pipe(destination);160+ destination.kill(signal);161+162+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));163+ t.like(await t.throwsAsync(destination), {signal});164+ t.like(await t.throwsAsync(source), {exitCode: 1});165+};166+167+test('Destination SIGTERM -> source abort', testDestinationTerminated, 'SIGTERM');168+test('Destination SIGKILL -> source abort', testDestinationTerminated, 'SIGKILL');169+170+test('Source already ended -> ignore source', async t => {171+ const source = execa('noop.js', [foobarString]);172+ await source;173+ const destination = execa('stdin.js');174+ const pipePromise = source.pipe(destination);175+176+ t.is(await pipePromise, await destination);177+ t.like(await source, {stdout: foobarString});178+ t.like(await destination, {stdout: ''});179+});180+181+test('Source already aborted -> ignore source', async t => {182+ const source = execa('noop.js', [foobarString]);183+ source.stdout.destroy();184+ const destination = execa('stdin.js');185+ const pipePromise = source.pipe(destination);186+187+ t.is(await pipePromise, await destination);188+ t.like(await source, {stdout: ''});189+ t.like(await destination, {stdout: ''});190+});191+192+test('Source already errored -> failure', async t => {193+ const source = execa('noop.js', [foobarString]);194+ const error = new Error('test');195+ source.stdout.destroy(error);196+ const destination = execa('stdin.js');197+ const pipePromise = source.pipe(destination);198+199+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));200+ t.is(await t.throwsAsync(source), error);201+ t.like(await destination, {stdout: ''});202+});203+204+test('Destination already ended -> ignore source', async t => {205+ const destination = execa('stdin.js');206+ destination.stdin.end('.');207+ await destination;208+ const source = execa('noop.js', [foobarString]);209+ const pipePromise = source.pipe(destination);210+211+ t.is(await pipePromise, await destination);212+ t.like(await destination, {stdout: '.'});213+ t.like(await source, {stdout: ''});214+});215+216+test('Destination already aborted -> failure', async t => {217+ const destination = execa('stdin.js');218+ destination.stdin.destroy();219+ t.like(await t.throwsAsync(destination), prematureClose);220+ const source = execa('noop.js', [foobarString]);221+ const pipePromise = source.pipe(destination);222+223+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));224+ t.like(await source, {stdout: ''});225+});226+227+test('Destination already errored -> failure', async t => {228+ const destination = execa('stdin.js');229+ const error = new Error('test');230+ destination.stdin.destroy(error);231+ t.is(await t.throwsAsync(destination), error);232+ const source = execa('noop.js', [foobarString]);233+ const pipePromise = source.pipe(destination);234+235+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));236+ t.like(await source, {stdout: ''});237+});238+239+test('Source normal failure + destination normal failure', async t => {240+ const source = execa('noop-fail.js', ['1', foobarString]);241+ const destination = execa('stdin-fail.js');242+ const pipePromise = source.pipe(destination);243+244+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));245+ t.like(await t.throwsAsync(source), {stdout: foobarString, exitCode: 2});246+ t.like(await t.throwsAsync(destination), {stdout: foobarString, exitCode: 2});247+});248+249+test('Simultaneous error on source and destination', async t => {250+ const source = execa('noop.js', ['']);251+ const destination = execa('stdin.js');252+ const pipePromise = source.pipe(destination);253+254+ const sourceError = new Error(foobarString);255+ source.emit('error', sourceError);256+ const destinationError = new Error('other');257+ destination.emit('error', destinationError);258+259+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));260+ t.like(await t.throwsAsync(source), {originalMessage: sourceError.originalMessage});261+ t.like(await t.throwsAsync(destination), {originalMessage: destinationError.originalMessage});262+});263+264+test('Does not need to await individual promises', async t => {265+ const source = execa('fail.js');266+ const destination = execa('fail.js');267+ await t.throwsAsync(source.pipe(destination));268+});269+270+test('Need to await .pipe() return value', async t => {271+ const source = execa('fail.js');272+ const destination = execa('fail.js');273+ const pipePromise = source.pipe(destination);274+ await Promise.all([275+ once(process, 'unhandledRejection'),276+ t.throwsAsync(source),277+ t.throwsAsync(destination),278+ ]);279+ await t.throwsAsync(pipePromise);280+});281+282+if (isLinux) {283+ const testYesHead = async (t, useStdoutTransform, useStdinTransform, all) => {284+ const source = execa('yes', {stdout: useStdoutTransform ? noopGenerator(false) : 'pipe', all});285+ const destination = execa('head', ['-n', '1'], {stdin: useStdinTransform ? noopGenerator(false) : 'pipe'});286+ const pipePromise = source.pipe(destination);287+ t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));288+ t.like(await destination, {stdout: 'y'});289+ t.like(await t.throwsAsync(source), {exitCode: 1, stderr: 'yes: standard output: Connection reset by peer'});290+291+ t.false(source.stdout.readableEnded);292+ t.is(source.stdout.errored, null);293+ t.true(source.stdout.destroyed);294+ t.true(source.stderr.readableEnded);295+ t.is(source.stderr.errored, null);296+ t.true(source.stderr.destroyed);297+298+ if (all) {299+ t.true(source.all.readableEnded);300+ t.is(source.all.errored, null);301+ t.true(source.all.destroyed);302+ }303+ };304+305+ test('Works with yes | head', testYesHead, false, false, false);306+ test('Works with yes | head, input transform', testYesHead, false, true, false);307+ test('Works with yes | head, output transform', testYesHead, true, false, false);308+ test('Works with yes | head, input/output transform', testYesHead, true, true, false);309+ test('Works with yes | head, "all" option', testYesHead, false, false, true);310+ test('Works with yes | head, "all" option, input transform', testYesHead, false, true, true);311+ test('Works with yes | head, "all" option, output transform', testYesHead, true, false, true);312+ test('Works with yes | head, "all" option, input/output transform', testYesHead, true, true, true);313+}added:test/pipe/setup.js+23 added
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {fullStdio} from '../helpers/stdio.js';5+6+setFixtureDir();7+8+const pipeToProcess = async (t, index, from, options) => {9+ const {stdout} = await execa('noop-fd.js', [`${index}`, 'test'], options)10+ .pipe(execa('stdin.js'), {from});11+ t.is(stdout, 'test');12+};13+14+test('pipe(...) can pipe', pipeToProcess, 1, undefined, {});15+test('pipe(..., {from: "stdout"}) can pipe', pipeToProcess, 1, 'stdout', {});16+test('pipe(..., {from: 1}) can pipe', pipeToProcess, 1, 1, {});17+test('pipe(..., {from: "stderr"}) stderr can pipe', pipeToProcess, 2, 'stderr', {});18+test('pipe(..., {from: 2}) can pipe', pipeToProcess, 2, 2, {});19+test('pipe(..., {from: 3}) can pipe', pipeToProcess, 3, 3, fullStdio);20+test('pipe(..., {from: "all"}) can pipe stdout', pipeToProcess, 1, 'all', {all: true});21+test('pipe(..., {from: "all"}) can pipe stderr', pipeToProcess, 2, 'all', {all: true});22+test('pipe(..., {from: "all"}) can pipe stdout even with "stderr: ignore"', pipeToProcess, 1, 'all', {all: true, stderr: 'ignore'});23+test('pipe(..., {from: "all"}) can pipe stderr even with "stdout: ignore"', pipeToProcess, 2, 'all', {all: true, stdout: 'ignore'});added:test/pipe/streaming.js+428 added
1+import {once} from 'node:events';2+import {PassThrough} from 'node:stream';3+import test from 'ava';4+import {execa} from '../../index.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+import {foobarString} from '../helpers/input.js';7+import {assertMaxListeners} from '../helpers/listeners.js';8+9+setFixtureDir();10+11+test('Can pipe two sources to same destination', async t => {12+ const source = execa('noop.js', [foobarString]);13+ const secondSource = execa('noop.js', [foobarString]);14+ const destination = execa('stdin.js');15+ const pipePromise = source.pipe(destination);16+ const secondPipePromise = secondSource.pipe(destination);17+18+ t.like(await source, {stdout: foobarString});19+ t.like(await secondSource, {stdout: foobarString});20+ t.like(await destination, {stdout: `${foobarString}\n${foobarString}`});21+ t.is(await pipePromise, await destination);22+ t.is(await secondPipePromise, await destination);23+});24+25+test('Can pipe three sources to same destination', async t => {26+ const source = execa('noop.js', [foobarString]);27+ const secondSource = execa('noop.js', [foobarString]);28+ const thirdSource = execa('noop.js', [foobarString]);29+ const destination = execa('stdin.js');30+ const pipePromise = source.pipe(destination);31+ const secondPipePromise = secondSource.pipe(destination);32+ const thirdPromise = thirdSource.pipe(destination);33+34+ t.like(await source, {stdout: foobarString});35+ t.like(await secondSource, {stdout: foobarString});36+ t.like(await thirdSource, {stdout: foobarString});37+ t.like(await destination, {stdout: `${foobarString}\n${foobarString}\n${foobarString}`});38+ t.is(await pipePromise, await destination);39+ t.is(await secondPipePromise, await destination);40+ t.is(await thirdPromise, await destination);41+});42+43+const processesCount = 100;44+45+test.serial('Can pipe many sources to same destination', async t => {46+ const checkMaxListeners = assertMaxListeners(t);47+48+ const expectedResults = Array.from({length: processesCount}, (_, index) => `${index}`).sort();49+ const sources = expectedResults.map(expectedResult => execa('noop.js', [expectedResult]));50+ const destination = execa('stdin.js');51+ const pipePromises = sources.map(source => source.pipe(destination));52+53+ const results = await Promise.all(sources);54+ t.deepEqual(results.map(({stdout}) => stdout), expectedResults);55+ const destinationResult = await destination;56+ t.deepEqual(destinationResult.stdout.split('\n').sort(), expectedResults);57+ t.deepEqual(await Promise.all(pipePromises), sources.map(() => destinationResult));58+59+ checkMaxListeners();60+});61+62+test.serial('Can pipe same source to many destinations', async t => {63+ const checkMaxListeners = assertMaxListeners(t);64+65+ const source = execa('noop-fd.js', ['1', foobarString]);66+ const expectedResults = Array.from({length: processesCount}, (_, index) => `${index}`);67+ const destinations = expectedResults.map(expectedResult => execa('noop-stdin-double.js', [expectedResult]));68+ const pipePromises = destinations.map(destination => source.pipe(destination));69+70+ t.like(await source, {stdout: foobarString});71+ const results = await Promise.all(destinations);72+ t.deepEqual(results.map(({stdout}) => stdout), expectedResults.map(result => `${foobarString} ${result}`));73+ t.deepEqual(await Promise.all(pipePromises), results);74+75+ checkMaxListeners();76+});77+78+test('Can pipe two streams from same process to same destination', async t => {79+ const source = execa('noop-both.js', [foobarString]);80+ const destination = execa('stdin.js');81+ const pipePromise = source.pipe(destination);82+ const secondPipePromise = source.pipe(destination, {from: 'stderr'});83+84+ t.like(await source, {stdout: foobarString, stderr: foobarString});85+ t.like(await destination, {stdout: `${foobarString}\n${foobarString}`});86+ t.is(await pipePromise, await destination);87+ t.is(await secondPipePromise, await destination);88+});89+90+test('Can pipe a new source to same destination after some source has already written', async t => {91+ const passThroughStream = new PassThrough();92+ const source = execa('stdin.js', {stdin: ['pipe', passThroughStream]});93+ const destination = execa('stdin.js');94+ const pipePromise = source.pipe(destination);95+96+ passThroughStream.write('foo');97+ const firstWrite = await once(destination.stdout, 'data');98+ t.is(firstWrite.toString(), 'foo');99+100+ const secondSource = execa('noop.js', ['bar']);101+ const secondPipePromise = secondSource.pipe(destination);102+ passThroughStream.end();103+104+ t.like(await source, {stdout: 'foo'});105+ t.like(await secondSource, {stdout: 'bar'});106+ t.like(await destination, {stdout: 'foobar'});107+ t.is(await pipePromise, await destination);108+ t.is(await secondPipePromise, await destination);109+});110+111+test('Can pipe a second source to same destination after destination has already ended', async t => {112+ const source = execa('noop.js', [foobarString]);113+ const destination = execa('stdin.js');114+ const pipePromise = source.pipe(destination);115+116+ t.like(await source, {stdout: foobarString});117+ t.like(await destination, {stdout: foobarString});118+ t.is(await pipePromise, await destination);119+120+ const secondSource = execa('noop.js', [foobarString]);121+ const secondPipePromise = secondSource.pipe(destination);122+123+ t.like(await secondSource, {stdout: ''});124+ t.is(await secondPipePromise, await destination);125+});126+127+test('Can pipe same source to a second destination after source has already ended', async t => {128+ const source = execa('noop.js', [foobarString]);129+ const destination = execa('stdin.js');130+ const pipePromise = source.pipe(destination);131+132+ t.like(await source, {stdout: foobarString});133+ t.like(await destination, {stdout: foobarString});134+ t.is(await pipePromise, await destination);135+136+ const secondDestination = execa('stdin.js');137+ const secondPipePromise = source.pipe(secondDestination);138+139+ t.like(await secondDestination, {stdout: ''});140+ t.is(await secondPipePromise, await secondDestination);141+});142+143+test('Can pipe a new source to same destination after some but not all sources have ended', async t => {144+ const source = execa('noop.js', [foobarString]);145+ const passThroughStream = new PassThrough();146+ const secondSource = execa('stdin.js', {stdin: ['pipe', passThroughStream]});147+ const destination = execa('stdin.js');148+ const pipePromise = source.pipe(destination);149+ const secondPipePromise = secondSource.pipe(destination);150+151+ t.like(await source, {stdout: foobarString});152+153+ const thirdSource = execa('noop.js', [foobarString]);154+ const thirdPipePromise = thirdSource.pipe(destination);155+ passThroughStream.end(`${foobarString}\n`);156+157+ t.like(await secondSource, {stdout: foobarString});158+ t.like(await thirdSource, {stdout: foobarString});159+ t.like(await destination, {stdout: `${foobarString}\n${foobarString}\n${foobarString}`});160+ t.is(await pipePromise, await destination);161+ t.is(await secondPipePromise, await destination);162+ t.is(await thirdPipePromise, await destination);163+});164+165+test('Can pipe two processes already ended', async t => {166+ const source = execa('noop.js', [foobarString]);167+ const destination = execa('stdin.js');168+ destination.stdin.end('.');169+ await Promise.all([source, destination]);170+ const pipePromise = source.pipe(destination);171+172+ t.like(await source, {stdout: foobarString});173+ t.like(await destination, {stdout: '.'});174+ t.is(await pipePromise, await destination);175+});176+177+test('Can pipe to same destination through multiple paths', async t => {178+ const source = execa('noop.js', [foobarString]);179+ const destination = execa('stdin.js');180+ const secondDestination = execa('stdin.js');181+ const pipePromise = source.pipe(destination);182+ const secondPipePromise = destination.pipe(secondDestination);183+ const thirdPipePromise = source.pipe(secondDestination);184+185+ t.like(await source, {stdout: foobarString});186+ t.like(await destination, {stdout: foobarString});187+ t.like(await secondDestination, {stdout: `${foobarString}\n${foobarString}`});188+ t.is(await pipePromise, await destination);189+ t.is(await secondPipePromise, await secondDestination);190+ t.is(await thirdPipePromise, await secondDestination);191+});192+193+test('Can pipe two sources to same destination in objectMode', async t => {194+ const stdoutTransform = {195+ * transform() {196+ yield [foobarString];197+ },198+ objectMode: true,199+ };200+ const source = execa('noop.js', [''], {stdout: stdoutTransform});201+ const secondSource = execa('noop.js', [''], {stdout: stdoutTransform});202+ t.true(source.stdout.readableObjectMode);203+ t.true(secondSource.stdout.readableObjectMode);204+205+ const stdinTransform = {206+ * transform([chunk]) {207+ yield chunk;208+ },209+ objectMode: true,210+ };211+ const destination = execa('stdin.js', {stdin: stdinTransform});212+ const pipePromise = source.pipe(destination);213+ const secondPipePromise = secondSource.pipe(destination);214+215+ t.like(await source, {stdout: [[foobarString]]});216+ t.like(await secondSource, {stdout: [[foobarString]]});217+ t.like(await destination, {stdout: `${foobarString}${foobarString}`});218+ t.is(await pipePromise, await destination);219+ t.is(await secondPipePromise, await destination);220+});221+222+test('Can pipe one source to two destinations', async t => {223+ const source = execa('noop.js', [foobarString]);224+ const destination = execa('stdin.js');225+ const secondDestination = execa('stdin.js');226+ const pipePromise = source.pipe(destination);227+ const secondPipePromise = source.pipe(secondDestination);228+229+ t.like(await source, {stdout: foobarString});230+ t.like(await destination, {stdout: foobarString});231+ t.like(await secondDestination, {stdout: foobarString});232+ t.is(await pipePromise, await destination);233+ t.is(await secondPipePromise, await secondDestination);234+});235+236+test('Can pipe one source to three destinations', async t => {237+ const source = execa('noop.js', [foobarString]);238+ const destination = execa('stdin.js');239+ const secondDestination = execa('stdin.js');240+ const thirdDestination = execa('stdin.js');241+ const pipePromise = source.pipe(destination);242+ const secondPipePromise = source.pipe(secondDestination);243+ const thirdPipePromise = source.pipe(thirdDestination);244+245+ t.like(await source, {stdout: foobarString});246+ t.like(await destination, {stdout: foobarString});247+ t.like(await secondDestination, {stdout: foobarString});248+ t.like(await thirdDestination, {stdout: foobarString});249+ t.is(await pipePromise, await destination);250+ t.is(await secondPipePromise, await secondDestination);251+ t.is(await thirdPipePromise, await thirdDestination);252+});253+254+test('Can create a series of pipes', async t => {255+ const source = execa('noop.js', [foobarString]);256+ const destination = execa('stdin.js');257+ const secondDestination = execa('stdin.js');258+ const pipePromise = source.pipe(destination);259+ const secondPipePromise = destination.pipe(secondDestination);260+261+ t.like(await source, {stdout: foobarString});262+ t.like(await destination, {stdout: foobarString});263+ t.like(await secondDestination, {stdout: foobarString});264+ t.is(await pipePromise, await destination);265+ t.is(await secondPipePromise, await secondDestination);266+});267+268+test('Returns pipedFrom on success', async t => {269+ const source = execa('noop.js', [foobarString]);270+ const destination = execa('stdin.js');271+ const pipePromise = source.pipe(destination);272+273+ const destinationResult = await destination;274+ t.deepEqual(destinationResult.pipedFrom, []);275+ const sourceResult = await source;276+277+ t.like(await pipePromise, {pipedFrom: [sourceResult]});278+ t.deepEqual(destinationResult.pipedFrom, [sourceResult]);279+ t.deepEqual(sourceResult.pipedFrom, []);280+});281+282+test('Returns pipedFrom on deep success', async t => {283+ const source = execa('noop.js', [foobarString]);284+ const destination = execa('stdin.js');285+ const secondDestination = execa('stdin.js');286+ const pipePromise = source.pipe(destination);287+ const secondPipePromise = destination.pipe(secondDestination);288+289+ const destinationResult = await destination;290+ t.deepEqual(destinationResult.pipedFrom, []);291+ const secondDestinationResult = await secondDestination;292+ t.deepEqual(secondDestinationResult.pipedFrom, []);293+ const sourceResult = await source;294+295+ t.like(await secondPipePromise, {pipedFrom: [destinationResult]});296+ t.deepEqual(secondDestinationResult.pipedFrom, [destinationResult]);297+ t.like(await pipePromise, {pipedFrom: [sourceResult]});298+ t.deepEqual(destinationResult.pipedFrom, [sourceResult]);299+ t.deepEqual(sourceResult.pipedFrom, []);300+});301+302+test('Returns pipedFrom on source failure', async t => {303+ const source = execa('noop-fail.js', ['1', foobarString]);304+ const destination = execa('stdin.js');305+ const pipePromise = source.pipe(destination);306+307+ const destinationResult = await destination;308+ t.deepEqual(destinationResult.pipedFrom, []);309+ const sourceResult = await t.throwsAsync(source);310+311+ t.like(await t.throwsAsync(pipePromise), {pipedFrom: []});312+ t.deepEqual(destinationResult.pipedFrom, [sourceResult]);313+ t.deepEqual(sourceResult.pipedFrom, []);314+});315+316+test('Returns pipedFrom on destination failure', async t => {317+ const source = execa('noop.js', [foobarString]);318+ const destination = execa('stdin-fail.js');319+ const pipePromise = source.pipe(destination);320+321+ const destinationResult = await t.throwsAsync(destination);322+ const sourceResult = await source;323+324+ t.like(await t.throwsAsync(pipePromise), {pipedFrom: [sourceResult]});325+ t.deepEqual(destinationResult.pipedFrom, [sourceResult]);326+ t.deepEqual(sourceResult.pipedFrom, []);327+});328+329+test('Returns pipedFrom on source + destination failure', async t => {330+ const source = execa('noop-fail.js', ['1', foobarString]);331+ const destination = execa('stdin-fail.js');332+ const pipePromise = source.pipe(destination);333+334+ const destinationResult = await t.throwsAsync(destination);335+ const sourceResult = await t.throwsAsync(source);336+337+ t.like(await t.throwsAsync(pipePromise), {pipedFrom: [sourceResult]});338+ t.deepEqual(destinationResult.pipedFrom, [sourceResult]);339+ t.deepEqual(sourceResult.pipedFrom, []);340+});341+342+test('Returns pipedFrom on deep failure', async t => {343+ const source = execa('noop-fail.js', ['1', foobarString]);344+ const destination = execa('stdin-fail.js');345+ const secondDestination = execa('stdin.js');346+ const pipePromise = source.pipe(destination);347+ const secondPipePromise = destination.pipe(secondDestination);348+349+ const destinationResult = await t.throwsAsync(destination);350+ const secondDestinationResult = await secondDestination;351+ t.deepEqual(secondDestinationResult.pipedFrom, []);352+ const sourceResult = await t.throwsAsync(source);353+354+ t.like(await t.throwsAsync(secondPipePromise), {pipedFrom: [sourceResult]});355+ t.deepEqual(secondDestinationResult.pipedFrom, [destinationResult]);356+ t.like(await t.throwsAsync(pipePromise), {pipedFrom: [sourceResult]});357+ t.deepEqual(destinationResult.pipedFrom, [sourceResult]);358+ t.deepEqual(sourceResult.pipedFrom, []);359+});360+361+test('Returns pipedFrom from multiple sources', async t => {362+ const source = execa('noop.js', [foobarString]);363+ const secondSource = execa('noop.js', [foobarString]);364+ const destination = execa('stdin.js');365+ const pipePromise = source.pipe(destination);366+ const secondPipePromise = secondSource.pipe(destination);367+368+ const destinationResult = await destination;369+ t.deepEqual(destinationResult.pipedFrom, []);370+ const sourceResult = await source;371+ const secondSourceResult = await secondSource;372+373+ t.like(await pipePromise, {pipedFrom: [sourceResult, secondSourceResult]});374+ t.like(await secondPipePromise, {pipedFrom: [sourceResult, secondSourceResult]});375+ t.deepEqual(destinationResult.pipedFrom, [sourceResult, secondSourceResult]);376+ t.deepEqual(sourceResult.pipedFrom, []);377+ t.deepEqual(secondSourceResult.pipedFrom, []);378+});379+380+test('Returns pipedFrom from already ended processes', async t => {381+ const source = execa('noop.js', [foobarString]);382+ const destination = execa('stdin.js');383+ destination.stdin.end('.');384+ await Promise.all([source, destination]);385+ const pipePromise = source.pipe(destination);386+387+ const destinationResult = await destination;388+ t.deepEqual(destinationResult.pipedFrom, []);389+ const sourceResult = await source;390+ t.deepEqual(sourceResult.pipedFrom, []);391+392+ t.like(await pipePromise, {pipedFrom: [sourceResult]});393+ t.deepEqual(destinationResult.pipedFrom, [sourceResult]);394+ t.deepEqual(sourceResult.pipedFrom, []);395+});396+397+test('Does not return nor set pipedFrom on signal abort', async t => {398+ const abortController = new AbortController();399+ const source = execa('empty.js');400+ const destination = execa('empty.js');401+ const pipePromise = source.pipe(destination, {signal: abortController.signal});402+403+ abortController.abort();404+ t.like(await t.throwsAsync(pipePromise), {pipedFrom: []});405+ const destinationResult = await destination;406+ t.deepEqual(destinationResult.pipedFrom, []);407+ const sourceResult = await source;408+ t.deepEqual(sourceResult.pipedFrom, []);409+});410+411+test('Can pipe same source to same destination twice', async t => {412+ const source = execa('noop.js', [foobarString]);413+ const destination = execa('stdin.js');414+ const pipePromise = source.pipe(destination);415+ const secondPipePromise = source.pipe(destination);416+417+ const destinationResult = await destination;418+ t.like(destinationResult, {pipedFrom: []});419+ const sourceResult = await source;420+ t.like(sourceResult, {pipedFrom: []});421+422+ t.like(await source, {stdout: foobarString});423+ t.like(await destination, {stdout: foobarString});424+ t.is(await pipePromise, destinationResult);425+ t.is(await secondPipePromise, destinationResult);426+ t.deepEqual(destinationResult.pipedFrom, [sourceResult]);427+ t.deepEqual(sourceResult.pipedFrom, []);428+});added:test/pipe/validate.js+165 added
1+import {PassThrough} from 'node:stream';2+import {spawn} from 'node:child_process';3+import process from 'node:process';4+import test from 'ava';5+import {execa} from '../../index.js';6+import {setFixtureDir} from '../helpers/fixtures-dir.js';7+import {foobarString} from '../helpers/input.js';8+9+setFixtureDir();10+11+const assertPipeError = async (t, pipePromise, message) => {12+ const error = await t.throwsAsync(pipePromise);13+14+ t.is(error.command, 'source.pipe(destination)');15+ t.is(error.escapedCommand, error.command);16+17+ t.is(typeof error.cwd, 'string');18+ t.true(error.failed);19+ t.false(error.timedOut);20+ t.false(error.isCanceled);21+ t.false(error.isTerminated);22+ t.is(error.exitCode, undefined);23+ t.is(error.signal, undefined);24+ t.is(error.signalDescription, undefined);25+ t.is(error.stdout, undefined);26+ t.is(error.stderr, undefined);27+ t.is(error.all, undefined);28+ t.deepEqual(error.stdio, Array.from({length: error.stdio.length}));29+ t.deepEqual(error.pipedFrom, []);30+31+ t.true(error.shortMessage.includes(`Command failed: ${error.command}`));32+ t.true(error.shortMessage.includes(error.originalMessage));33+ t.true(error.message.includes(error.shortMessage));34+35+ t.true(error.originalMessage.includes(message));36+};37+38+test('Must set "all" option to "true" to use pipe(..., {from: "all"})', async t => {39+ await assertPipeError(40+ t,41+ execa('empty.js')42+ .pipe(execa('empty.js'), {from: 'all'}),43+ '"all" option must be true',44+ );45+});46+47+const invalidDestination = async (t, getDestination) => {48+ await assertPipeError(49+ t,50+ execa('empty.js')51+ .pipe(getDestination()),52+ 'an Execa child process',53+ );54+};55+56+test('pipe() cannot pipe to non-processes', invalidDestination, () => ({stdin: new PassThrough()}));57+test('pipe() cannot pipe to non-Execa processes', invalidDestination, () => spawn('node', ['--version']));58+59+test('pipe() "from" option cannot be "stdin"', async t => {60+ await assertPipeError(61+ t,62+ execa('empty.js')63+ .pipe(execa('empty.js'), {from: 'stdin'}),64+ 'not be "stdin"',65+ );66+});67+68+const invalidFromOption = async (t, from) => {69+ await assertPipeError(70+ t,71+ execa('empty.js')72+ .pipe(execa('empty.js'), {from}),73+ '"from" option must not be',74+ );75+};76+77+test('pipe() "from" option cannot be any string', invalidFromOption, 'other');78+test('pipe() "from" option cannot be a float', invalidFromOption, 1.5);79+test('pipe() "from" option cannot be a negative number', invalidFromOption, -1);80+81+test('pipe() "from" option cannot be a non-existing file descriptor', async t => {82+ await assertPipeError(83+ t,84+ execa('empty.js')85+ .pipe(execa('empty.js'), {from: 3}),86+ 'file descriptor does not exist',87+ );88+});89+90+test('pipe() "from" option cannot be an input file descriptor', async t => {91+ await assertPipeError(92+ t,93+ execa('stdin-fd.js', ['3'], {stdio: ['pipe', 'pipe', 'pipe', new Uint8Array()]})94+ .pipe(execa('empty.js'), {from: 3}),95+ 'must be a readable stream',96+ );97+});98+99+test('Must set destination "stdin" option to "pipe" to use pipe()', async t => {100+ await assertPipeError(101+ t,102+ execa('empty.js')103+ .pipe(execa('stdin.js', {stdin: 'ignore'})),104+ 'stdin must be available',105+ );106+});107+108+// eslint-disable-next-line max-params109+const invalidSource = async (t, optionName, optionValue, from, options) => {110+ await assertPipeError(111+ t,112+ execa('empty.js', options)113+ .pipe(execa('empty.js'), {from}),114+ `\`${optionName}: ${optionValue}\` option is incompatible`,115+ );116+};117+118+test('Cannot set "stdout" option to "ignore" to use pipe(...)', invalidSource, 'stdout', '"ignore"', undefined, {stdout: 'ignore'});119+test('Cannot set "stdout" option to "ignore" to use pipe(..., 1)', invalidSource, 'stdout', '"ignore"', 1, {stdout: 'ignore'});120+test('Cannot set "stdout" option to "ignore" to use pipe(..., "stdout")', invalidSource, 'stdout', '"ignore"', 'stdout', {stdout: 'ignore'});121+test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(...)', invalidSource, 'stdout', '"ignore"', undefined, {stdout: 'ignore', stderr: 'ignore'});122+test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., 1)', invalidSource, 'stdout', '"ignore"', 1, {stdout: 'ignore', stderr: 'ignore'});123+test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., "stdout")', invalidSource, 'stdout', '"ignore"', 'stdout', {stdout: 'ignore', stderr: 'ignore'});124+test('Cannot set "stdio[1]" option to "ignore" to use pipe(...)', invalidSource, 'stdio[1]', '"ignore"', undefined, {stdio: ['pipe', 'ignore', 'pipe']});125+test('Cannot set "stdio[1]" option to "ignore" to use pipe(..., 1)', invalidSource, 'stdio[1]', '"ignore"', 1, {stdio: ['pipe', 'ignore', 'pipe']});126+test('Cannot set "stdio[1]" option to "ignore" to use pipe(..., "stdout")', invalidSource, 'stdio[1]', '"ignore"', 'stdout', {stdio: ['pipe', 'ignore', 'pipe']});127+test('Cannot set "stderr" option to "ignore" to use pipe(..., 2)', invalidSource, 'stderr', '"ignore"', 2, {stderr: 'ignore'});128+test('Cannot set "stderr" option to "ignore" to use pipe(..., "stderr")', invalidSource, 'stderr', '"ignore"', 'stderr', {stderr: 'ignore'});129+test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., 2)', invalidSource, 'stderr', '"ignore"', 2, {stdout: 'ignore', stderr: 'ignore'});130+test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., "stderr")', invalidSource, 'stderr', '"ignore"', 'stderr', {stdout: 'ignore', stderr: 'ignore'});131+test('Cannot set "stdio[2]" option to "ignore" to use pipe(..., 2)', invalidSource, 'stdio[2]', '"ignore"', 2, {stdio: ['pipe', 'pipe', 'ignore']});132+test('Cannot set "stdio[2]" option to "ignore" to use pipe(..., "stderr")', invalidSource, 'stdio[2]', '"ignore"', 'stderr', {stdio: ['pipe', 'pipe', 'ignore']});133+test('Cannot set "stdio[3]" option to "ignore" to use pipe(..., 3)', invalidSource, 'stdio[3]', '"ignore"', 3, {stdio: ['pipe', 'pipe', 'pipe', 'ignore']});134+test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., "all")', invalidSource, 'stdout', '"ignore"', 'all', {stdout: 'ignore', stderr: 'ignore', all: true});135+test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use pipe(..., "all")', invalidSource, 'stdio[1]', '"ignore"', 'all', {stdio: ['pipe', 'ignore', 'ignore'], all: true});136+test('Cannot set "stdout" option to "inherit" to use pipe()', invalidSource, 'stdout', '"inherit"', 1, {stdout: 'inherit'});137+test('Cannot set "stdout" option to "ipc" to use pipe()', invalidSource, 'stdout', '"ipc"', 1, {stdout: 'ipc'});138+test('Cannot set "stdout" option to file descriptors to use pipe()', invalidSource, 'stdout', '1', 1, {stdout: 1});139+test('Cannot set "stdout" option to Node.js streams to use pipe()', invalidSource, 'stdout', 'Stream', 1, {stdout: process.stdout});140+141+test('Destination stream is ended when first argument is invalid', async t => {142+ const source = execa('empty.js', {stdout: 'ignore'});143+ const destination = execa('stdin.js');144+ const pipePromise = source.pipe(destination);145+146+ await assertPipeError(t, pipePromise, 'option is incompatible');147+ await source;148+ t.like(await destination, {stdout: ''});149+});150+151+test('Source stream is aborted when second argument is invalid', async t => {152+ const source = execa('noop.js', [foobarString]);153+ const pipePromise = source.pipe('');154+155+ await assertPipeError(t, pipePromise, 'an Execa child process');156+ t.like(await source, {stdout: ''});157+});158+159+test('Both arguments might be invalid', async t => {160+ const source = execa('empty.js', {stdout: 'ignore'});161+ const pipePromise = source.pipe('');162+163+ await assertPipeError(t, pipePromise, 'an Execa child process');164+ t.like(await source, {stdout: undefined});165+});modified:test/error.js+2 added
24 unmodified lines25 'stdout',26 'stderr',27 'all',28 'stdio',29+ 'pipedFrom',30 ]);31 });32 33 test('Error properties are not missing and are ordered', async t => {16 unmodified lines50 'stdout',51 'stderr',52 'all',53 'stdio',54+ 'pipedFrom',55 ]);56 });57 58 const testEmptyErrorStdio = async (t, execaMethod) => {274 unmodified linesdeleted:test/pipe.js-110 removed
1-import {PassThrough} from 'node:stream';2-import {spawn} from 'node:child_process';3-import process from 'node:process';4-import test from 'ava';5-import {execa} from '../index.js';6-import {setFixtureDir} from './helpers/fixtures-dir.js';7-import {fullStdio} from './helpers/stdio.js';8-9-setFixtureDir();10-11-const pipeToProcess = async (t, index, streamName) => {12- const {stdout} = await execa('noop-fd.js', [`${index}`, 'test'], {...fullStdio, all: true}).pipe(execa('stdin.js'), streamName);13- t.is(stdout, 'test');14-};15-16-test('pipe() can pipe to Execa child processes', pipeToProcess, 1, undefined);17-test('pipe() stdout can pipe to Execa child processes', pipeToProcess, 1, 'stdout');18-test('pipe() 1 can pipe to Execa child processes', pipeToProcess, 1, 1);19-test('pipe() stderr can pipe to Execa child processes', pipeToProcess, 2, 'stderr');20-test('pipe() 2 can pipe to Execa child processes', pipeToProcess, 2, 2);21-test('pipe() 3 can pipe to Execa child processes', pipeToProcess, 3, 3);22-23-const pipeAllToProcess = async (t, index) => {24- const {stdout} = await execa('noop-fd.js', [`${index}`, 'test'], {...fullStdio, all: true}).pipe(execa('stdin.js'), 'all');25- t.is(stdout, 'test');26-};27-28-test('pipe() all can pipe stdout to Execa child processes', pipeAllToProcess, 1, {all: true});29-test('pipe() all can pipe stdout to Execa child processes even with "stderr: ignore"', pipeAllToProcess, 1, {all: true, stderr: 'ignore'});30-test('pipe() all can pipe stderr to Execa child processes', pipeAllToProcess, 2, {all: true});31-test('pipe() all can pipe stderr to Execa child processes even with "stdout: ignore"', pipeAllToProcess, 1, {all: true, stdout: 'ignore'});32-33-test('Must set "all" option to "true" to use pipe() with "all"', t => {34- t.throws(() => {35- execa('empty.js').pipe(execa('empty.js'), 'all');36- }, {message: /"all" option must be true/});37-});38-39-const invalidTarget = (t, getTarget) => {40- t.throws(() => {41- execa('empty.js').pipe(getTarget());42- }, {message: /an Execa child process/});43-};44-45-test('pipe() cannot pipe to non-processes', invalidTarget, () => ({stdin: new PassThrough()}));46-test('pipe() cannot pipe to non-Execa processes', invalidTarget, () => spawn('node', ['--version']));47-48-test('pipe() second argument cannot be "stdin"', t => {49- t.throws(() => {50- execa('empty.js').pipe(execa('empty.js'), 'stdin');51- }, {message: /not be "stdin"/});52-});53-54-const invalidStreamName = (t, streamName) => {55- t.throws(() => {56- execa('empty.js').pipe(execa('empty.js'), streamName);57- }, {message: /second argument must not be/});58-};59-60-test('pipe() second argument cannot be any string', invalidStreamName, 'other');61-test('pipe() second argument cannot be a float', invalidStreamName, 1.5);62-test('pipe() second argument cannot be a negative number', invalidStreamName, -1);63-64-test('pipe() second argument cannot be a non-existing file descriptor', t => {65- t.throws(() => {66- execa('empty.js').pipe(execa('empty.js'), 3);67- }, {message: /file descriptor does not exist/});68-});69-70-test('pipe() second argument cannot be an input file descriptor', t => {71- t.throws(() => {72- execa('stdin-fd.js', ['3'], {stdio: ['pipe', 'pipe', 'pipe', new Uint8Array()]}).pipe(execa('empty.js'), 3);73- }, {message: /must be a readable stream/});74-});75-76-test('Must set target "stdin" option to "pipe" to use pipe()', t => {77- t.throws(() => {78- execa('empty.js').pipe(execa('stdin.js', {stdin: 'ignore'}));79- }, {message: /stdin must be available/});80-});81-82-// eslint-disable-next-line max-params83-const invalidSource = (t, optionName, optionValue, streamName, options) => {84- t.throws(() => {85- execa('empty.js', options).pipe(execa('empty.js'), streamName);86- }, {message: new RegExp(`\`${optionName}: ${optionValue}\` option is incompatible`)});87-};88-89-test('Cannot set "stdout" option to "ignore" to use pipe(...)', invalidSource, 'stdout', '"ignore"', undefined, {stdout: 'ignore'});90-test('Cannot set "stdout" option to "ignore" to use pipe(..., 1)', invalidSource, 'stdout', '"ignore"', 1, {stdout: 'ignore'});91-test('Cannot set "stdout" option to "ignore" to use pipe(..., "stdout")', invalidSource, 'stdout', '"ignore"', 'stdout', {stdout: 'ignore'});92-test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(...)', invalidSource, 'stdout', '"ignore"', undefined, {stdout: 'ignore', stderr: 'ignore'});93-test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., 1)', invalidSource, 'stdout', '"ignore"', 1, {stdout: 'ignore', stderr: 'ignore'});94-test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., "stdout")', invalidSource, 'stdout', '"ignore"', 'stdout', {stdout: 'ignore', stderr: 'ignore'});95-test('Cannot set "stdio[1]" option to "ignore" to use pipe(...)', invalidSource, 'stdio\\[1\\]', '"ignore"', undefined, {stdio: ['pipe', 'ignore', 'pipe']});96-test('Cannot set "stdio[1]" option to "ignore" to use pipe(..., 1)', invalidSource, 'stdio\\[1\\]', '"ignore"', 1, {stdio: ['pipe', 'ignore', 'pipe']});97-test('Cannot set "stdio[1]" option to "ignore" to use pipe(..., "stdout")', invalidSource, 'stdio\\[1\\]', '"ignore"', 'stdout', {stdio: ['pipe', 'ignore', 'pipe']});98-test('Cannot set "stderr" option to "ignore" to use pipe(..., 2)', invalidSource, 'stderr', '"ignore"', 2, {stderr: 'ignore'});99-test('Cannot set "stderr" option to "ignore" to use pipe(..., "stderr")', invalidSource, 'stderr', '"ignore"', 'stderr', {stderr: 'ignore'});100-test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., 2)', invalidSource, 'stderr', '"ignore"', 2, {stdout: 'ignore', stderr: 'ignore'});101-test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., "stderr")', invalidSource, 'stderr', '"ignore"', 'stderr', {stdout: 'ignore', stderr: 'ignore'});102-test('Cannot set "stdio[2]" option to "ignore" to use pipe(..., 2)', invalidSource, 'stdio\\[2\\]', '"ignore"', 2, {stdio: ['pipe', 'pipe', 'ignore']});103-test('Cannot set "stdio[2]" option to "ignore" to use pipe(..., "stderr")', invalidSource, 'stdio\\[2\\]', '"ignore"', 'stderr', {stdio: ['pipe', 'pipe', 'ignore']});104-test('Cannot set "stdio[3]" option to "ignore" to use pipe(..., 3)', invalidSource, 'stdio\\[3\\]', '"ignore"', 3, {stdio: ['pipe', 'pipe', 'pipe', 'ignore']});105-test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., "all")', invalidSource, 'stdout', '"ignore"', 'all', {stdout: 'ignore', stderr: 'ignore', all: true});106-test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use pipe(..., "all")', invalidSource, 'stdio\\[1\\]', '"ignore"', 'all', {stdio: ['pipe', 'ignore', 'ignore'], all: true});107-test('Cannot set "stdout" option to "inherit" to use pipe()', invalidSource, 'stdout', '"inherit"', 1, {stdout: 'inherit'});108-test('Cannot set "stdout" option to "ipc" to use pipe()', invalidSource, 'stdout', '"ipc"', 1, {stdout: 'ipc'});109-test('Cannot set "stdout" option to file descriptors to use pipe()', invalidSource, 'stdout', '1', 1, {stdout: 1});110-test('Cannot set "stdout" option to Node.js streams to use pipe()', invalidSource, 'stdout', 'Stream', 1, {stdout: process.stdout});modified:index.d.ts+39 added-16 removed
1 import {type ChildProcess} from 'node:child_process';2 import {type Readable, type Writable} from 'node:stream';3 4-type IfAsync<IsSync extends boolean, AsyncValue> = IsSync extends true ? never : AsyncValue;4+type IfAsync<IsSync extends boolean, AsyncValue, SyncValue = never> = IsSync extends true ? SyncValue : AsyncValue;5 6 // When the `stdin`/`stdout`/`stderr`/`stdio` option is set to one of those values, no stream is created7 type NoStreamStdioOption =8 | 'ignore'659 unmodified lines668 669 /**670 The output of the process on `stdout`.671 672- This is `undefined` if the `stdout` option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `lines` option is `true, or if the `stdout` option is a transform in object mode.672+ This is `undefined` if the `stdout` option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `lines` option is `true`, or if the `stdout` option is a transform in object mode.673 */674 stdout: StdioOutput<'1', OptionsType>;675 676 /**677 The output of the process on `stderr`.678 679- This is `undefined` if the `stderr` option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `lines` option is `true, or if the `stderr` option is a transform in object mode.679+ This is `undefined` if the `stderr` option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `lines` option is `true`, or if the `stderr` option is a transform in object mode.680 */681 stderr: StdioOutput<'2', OptionsType>;682 683 /**52 unmodified lines736 This is `undefined` if either:737 - the `all` option is `false` (default value)738 - both `stdout` and `stderr` options are set to [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)739 740- This is an array if the `lines` option is `true, or if either the `stdout` or `stderr` option is a transform in object mode.740+ This is an array if the `lines` option is `true`, or if either the `stdout` or `stderr` option is a transform in object mode.741 */742 all: IfAsync<IsSync, AllOutput<OptionsType>>;743+744+ /**745+ Results of the other processes that were piped into this child process. This is useful to inspect a series of child processes piped with each other.746+747+ This array is initially empty and is populated each time the `.pipe()` method resolves.748+ */749+ pipedFrom: IfAsync<IsSync, ExecaReturnValue[], []>;750 // Workaround for a TypeScript bug: https://github.com/microsoft/TypeScript/issues/57062751 } & {};752 753 export type ExecaReturnValue<OptionsType extends Options = Options> = ExecaCommonReturnValue<false, OptionsType> & ErrorUnlessReject<OptionsType['reject']>;63 unmodified lines817 type AllIfStderr<StderrResultIgnored extends boolean> = StderrResultIgnored extends true818 ? undefined819 : Readable;820 821+type PipeOptions = {822+ /**823+ Which stream to pipe. A file descriptor number can also be passed.824+825+ `"all"` pipes both `stdout` and `stderr`. This requires the `all` option to be `true`.826+ */827+ readonly from?: 'stdout' | 'stderr' | 'all' | number;828+829+ /**830+ Unpipe the child process when the signal aborts.831+832+ The `.pipe()` method will be rejected with a cancellation error.833+ */834+ readonly signal?: AbortSignal;835+};836+837+type PipableProcess = {838+ /**839+ [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to a second Execa child process' `stdin`. This resolves with that second process' result. If either process is rejected, this is rejected with that process' error instead.840+841+ This can be called multiple times to chain a series of processes.842+843+ Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.844+ */845+ pipe<Destination extends ExecaChildProcess>(destination: Destination, options?: PipeOptions): Promise<Awaited<Destination>> & PipableProcess;846+};847+848 export type ExecaChildPromise<OptionsType extends Options = Options> = {849 stdin: StreamUnlessIgnored<'0', OptionsType>;850 851 stdout: StreamUnlessIgnored<'1', OptionsType>;13 unmodified lines865 onRejected?: (reason: ExecaError<OptionsType>) => ResultType | PromiseLike<ResultType>866 ): Promise<ExecaReturnValue<OptionsType> | ResultType>;867 868 /**835- [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to another Execa child process' `stdin`.836-837- A `streamName` can be passed to pipe `"stderr"`, `"all"` (both `stdout` and `stderr`) or any another file descriptor instead of `stdout`.838-839- `childProcess.stdout` (and/or `childProcess.stderr` depending on `streamName`) must not be `undefined`. When `streamName` is `"all"`, the `all` option must be set to `true`.840-841- Returns `execaChildProcess`, which allows chaining `.pipe()` then `await`ing the final result.842- */843- pipe<Target extends ExecaChildProcess>(target: Target, streamName?: 'stdout' | 'stderr' | 'all' | number): Target;844-845- /**869 Sends a [signal](https://nodejs.org/api/os.html#signal-constants) to the child process. The default signal is the `killSignal` option. `killSignal` defaults to `SIGTERM`, which terminates the child process.870 871 This returns `false` when the signal could not be sent, for example when the child process has already exited.872 2 unmodified lines875 [More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)876 */877 kill(signal: Parameters<ChildProcess['kill']>[0], error?: Error): ReturnType<ChildProcess['kill']>;878 kill(error?: Error): ReturnType<ChildProcess['kill']>;856-};879+} & PipableProcess;880 881 export type ExecaChildProcess<OptionsType extends Options = Options> = ChildProcess &882 ExecaChildPromise<OptionsType> &883 Promise<ExecaReturnValue<OptionsType>>;463 unmodified linesmodified:index.js+1 added-1 removed
9 unmodified lines10 import {handleNodeOption} from './lib/node.js';11 import {handleInputAsync, pipeOutputAsync, cleanupStdioStreams} from './lib/stdio/async.js';12 import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';13 import {spawnedKill, validateTimeout, normalizeForceKillAfterDelay, cleanupOnExit, isFailedExit} from './lib/kill.js';14-import {pipeToProcess} from './lib/pipe.js';14+import {pipeToProcess} from './lib/pipe/setup.js';15 import {getSpawnedResult, makeAllStream} from './lib/stream.js';16 import {mergePromise} from './lib/promise.js';17 import {joinCommand} from './lib/escape.js';18 import {parseCommand} from './lib/command.js';300 unmodified linesmodified:index.test-d.ts+23 added-12 removed
2 unmodified lines3 // to get treated as `any` by `@typescript-eslint/no-unsafe-assignment`.4 import * as process from 'node:process';5 import {Readable, Writable} from 'node:stream';6 import {createWriteStream} from 'node:fs';7-import {expectType, expectError, expectAssignable, expectNotAssignable} from 'tsd';7+import {expectType, expectNotType, expectError, expectAssignable, expectNotAssignable} from 'tsd';8 import {9 $,10 execa,11 execaSync,66 unmodified lines78 };79 80 try {81 const execaPromise = execa('unicorns', {all: true});82+ const unicornsResult = await execaPromise;83 84 const execaBufferPromise = execa('unicorns', {encoding: 'buffer', all: true});84- const writeStream = createWriteStream('output.txt');85+ const bufferResult = await execaBufferPromise;86 86- expectType<typeof execaPromise>(execaBufferPromise.pipe(execaPromise));87- expectError(execaBufferPromise.pipe(writeStream));88- expectError(execaBufferPromise.pipe('output.txt'));89- await execaBufferPromise.pipe(execaPromise, 'stdout');90- await execaBufferPromise.pipe(execaPromise, 'stderr');91- await execaBufferPromise.pipe(execaPromise, 'all');92- await execaBufferPromise.pipe(execaPromise, 3);93- expectError(execaBufferPromise.pipe(execaPromise, 'other'));87+ expectType<typeof bufferResult>(await execaPromise.pipe(execaBufferPromise));88+ expectNotType<typeof bufferResult>(await execaPromise.pipe(execaPromise));89+ expectType<typeof bufferResult>(await execaPromise.pipe(execaPromise).pipe(execaBufferPromise));90+ await execaPromise.pipe(execaPromise).pipe(execaBufferPromise, {from: 'stdout'});91+ expectError(execaPromise.pipe(execaBufferPromise).stdout);92+ expectError(execaPromise.pipe(createWriteStream('output.txt')));93+ expectError(execaPromise.pipe('output.txt'));94+ await execaPromise.pipe(execaBufferPromise, {});95+ expectError(execaPromise.pipe(execaBufferPromise, 'stdout'));96+ await execaPromise.pipe(execaBufferPromise, {from: 'stdout'});97+ await execaPromise.pipe(execaBufferPromise, {from: 'stderr'});98+ await execaPromise.pipe(execaBufferPromise, {from: 'all'});99+ await execaPromise.pipe(execaBufferPromise, {from: 3});100+ expectError(execaPromise.pipe(execaBufferPromise, {from: 'other'}));101+ await execaPromise.pipe(execaBufferPromise, {signal: new AbortController().signal});102+ expectError(await execaPromise.pipe(execaBufferPromise, {signal: true}));103 104 expectType<Readable>(execaPromise.all);105 const noAllPromise = execa('unicorns');106 expectType<undefined>(noAllPromise.all);107 const noAllResult = await noAllPromise;108 expectType<undefined>(noAllResult.all);109 101- const unicornsResult = await execaPromise;110 expectType<string>(unicornsResult.command);111 expectType<string>(unicornsResult.escapedCommand);112 expectType<number | undefined>(unicornsResult.exitCode);113 expectType<boolean>(unicornsResult.failed);2 unmodified lines116 expectType<boolean>(unicornsResult.isTerminated);117 expectType<string | undefined>(unicornsResult.signal);118 expectType<string | undefined>(unicornsResult.signalDescription);119 expectType<string>(unicornsResult.cwd);120+ expectType<ExecaReturnValue[]>(unicornsResult.pipedFrom);121 122 expectType<undefined>(unicornsResult.stdio[0]);123 expectType<string>(unicornsResult.stdout);124 expectType<string>(unicornsResult.stdio[1]);5 unmodified lines130 expectType<Writable>(execaBufferPromise.stdin);131 expectType<Readable>(execaBufferPromise.stdout);132 expectType<Readable>(execaBufferPromise.stderr);133 expectType<Readable>(execaBufferPromise.all);125- const bufferResult = await execaBufferPromise;134 expectType<Uint8Array>(bufferResult.stdout);135 expectType<Uint8Array>(bufferResult.stdio[1]);136 expectType<Uint8Array>(bufferResult.stderr);137 expectType<Uint8Array>(bufferResult.stdio[2]);292 unmodified lines430 expectType<string | undefined>(execaError.signalDescription);431 expectType<string>(execaError.cwd);432 expectType<string>(execaError.shortMessage);433 expectType<string | undefined>(execaError.originalMessage);434+ expectType<ExecaReturnValue[]>(execaError.pipedFrom);435 436 expectType<undefined>(execaError.stdio[0]);437 438 const noAllError = error as ExecaError<{}>;137 unmodified lines576 expectType<boolean>(unicornsResult.isTerminated);577 expectType<string | undefined>(unicornsResult.signal);578 expectType<string | undefined>(unicornsResult.signalDescription);579 expectType<string>(unicornsResult.cwd);580+ expectType<[]>(unicornsResult.pipedFrom);581 582 expectType<undefined>(unicornsResult.stdio[0]);583 expectType<string>(unicornsResult.stdout);584 expectType<string>(unicornsResult.stdio[1]);63 unmodified lines648 expectType<string | undefined>(execaError.signalDescription);649 expectType<string>(execaError.cwd);650 expectType<string>(execaError.shortMessage);651 expectType<string | undefined>(execaError.originalMessage);652+ expectType<[]>(execaError.pipedFrom);653 654 expectType<undefined>(execaError.stdio[0]);655 656 const execaStringError = error as ExecaSyncError<{}>;769 unmodified linesmodified:package.json+1 added-1 removed
43 unmodified lines44 "local",45 "zx"46 ],47 "dependencies": {48- "@sindresorhus/merge-streams": "^2.0.1",48+ "@sindresorhus/merge-streams": "^3.0.0",49 "cross-spawn": "^7.0.3",50 "get-stream": "^8.0.1",51 "human-signals": "^6.0.0",52 "is-stream": "^4.0.1",40 unmodified linesmodified:readme.md+48 added-17 removed
180 unmodified lines181 182 ```js183 import {execa} from 'execa';184 185-// Similar to `echo unicorns | cat` in Bash186-const {stdout} = await execa('echo', ['unicorns']).pipe(execa('cat'));187-console.log(stdout);188-//=> 'unicorns'185+// Similar to `npm run build | sort | head -n2` in Bash186+const {stdout, pipedFrom} = await execa('npm', ['run', 'build'])187+ .pipe(execa('sort'))188+ .pipe(execa('head', ['-n2']));189+console.log(stdout); // Result of `head -n2`190+console.log(pipedFrom[0]); // Result of `sort`191+console.log(pipedFrom[0].pipedFrom[0]); // Result of `npm run build`192 ```193 194 ### Handling Errors195 79 unmodified lines275 Same as [`execa()`](#execacommandcommand-options) but synchronous.276 277 Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`ipc`](#ipc), [`serialization`](#serialization), [`signal`](#signal) and [`lines`](#lines). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio-1) and [`input`](#input) options cannot be an array, an iterable or a web stream. Node.js streams [must have a file descriptor](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr) unless the `input` option is used.278 276-Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipeexecachildprocess-streamname) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.279+Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipesecondchildprocess-pipeoptions) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.280 281 #### $.sync\`command\`282 #### $.s\`command\`283 284 Same as [$\`command\`](#command) but synchronous.285 286 Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`ipc`](#ipc), [`serialization`](#serialization), [`signal`](#signal) and [`lines`](#lines). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio-1) and [`input`](#input) options cannot be an array, an iterable or a web stream. Node.js streams [must have a file descriptor](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr) unless the `input` option is used.287 285-Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipeexecachildprocess-streamname) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.288+Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipesecondchildprocess-pipeoptions) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.289 290 #### execaCommandSync(command, options?)291 292 Same as [`execaCommand()`](#execacommand-command-options) but synchronous.293 294 Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`ipc`](#ipc), [`serialization`](#serialization), [`signal`](#signal) and [`lines`](#lines). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio-1) and [`input`](#input) options cannot be an array, an iterable or a web stream. Node.js streams [must have a file descriptor](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr) unless the `input` option is used.295 293-Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipeexecachildprocess-streamname) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.296+Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipesecondchildprocess-pipeoptions) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.297 298 ### Shell syntax299 300 For all the [methods above](#methods), no shell interpreter (Bash, cmd.exe, etc.) is used unless the [`shell` option](#shell) is set. This means shell-specific characters and expressions (`$variable`, `&&`, `||`, `;`, `|`, etc.) have no special meaning and do not need to be escaped.13 unmodified lines314 This is `undefined` if either:315 - the [`all` option](#all-2) is `false` (the default value)316 - both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)317 315-#### pipe(execaChildProcess, streamName?)318+#### pipe(secondChildProcess, pipeOptions?)319 317-`execaChildProcess`: [`execa()` return value](#pipe-multiple-processes)\318-`streamName`: `"stdout"` (default), `"stderr"`, `"all"` or file descriptor index320+`secondChildProcess`: [`execa()` return value](#pipe-multiple-processes)\321+`pipeOptions`: [`PipeOptions`](#pipeoptions)\322+_Returns_: [`Promise<ChildProcessResult>`](#childprocessresult)323 320-[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to another Execa child process' `stdin`.324+[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to a second Execa child process' `stdin`. This resolves with that second process' [result](#childprocessresult). If either process is rejected, this is rejected with that process' [error](#childprocessresult) instead.325 322-A `streamName` can be passed to pipe `"stderr"`, `"all"` (both `stdout` and `stderr`) or any another file descriptor instead of `stdout`.326+This can be called multiple times to chain a series of processes.327 324-[`childProcess.stdout`](#stdout) (and/or [`childProcess.stderr`](#stderr) depending on `streamName`) must not be `undefined`. When `streamName` is `"all"`, the [`all` option](#all-2) must be set to `true`.328+Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.329 326-Returns `execaChildProcess`, which allows chaining `.pipe()` then `await`ing the [final result](#childprocessresult).330+##### pipeOptions331 332+Type: `object`333+334+##### pipeOptions.from335+336+Type: `"stdout" | "stderr" | "all" | number`\337+Default: `"stdout"`338+339+Which stream to pipe. A file descriptor number can also be passed.340+341+`"all"` pipes both `stdout` and `stderr`. This requires the [`all` option](#all-2) to be `true`.342+343+##### pipeOptions.signal344+345+Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)346+347+Unpipe the child process when the signal aborts.348+349+The [`.pipe()`](#pipesecondchildprocess-pipeoptions) method will be rejected with a cancellation error.350+351 #### kill(signal, error?)352 #### kill(error?)353 354 `signal`: `string | number`\49 unmodified lines404 Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`405 406 The output of the process on `stdout`.407 385-This is `undefined` if the [`stdout`](#stdout-1) option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the [`lines` option](#lines) is `true, or if the `stdout` option is a [transform in object mode](docs/transform.md#object-mode).408+This is `undefined` if the [`stdout`](#stdout-1) option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the [`lines` option](#lines) is `true`, or if the `stdout` option is a [transform in object mode](docs/transform.md#object-mode).409 410 #### stderr411 412 Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`413 414 The output of the process on `stderr`.415 393-This is `undefined` if the [`stderr`](#stderr-1) option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the [`lines` option](#lines) is `true, or if the `stderr` option is a [transform in object mode](docs/transform.md#object-mode).416+This is `undefined` if the [`stderr`](#stderr-1) option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the [`lines` option](#lines) is `true`, or if the `stderr` option is a [transform in object mode](docs/transform.md#object-mode).417 418 #### all419 420 Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`3 unmodified lines424 This is `undefined` if either:425 - the [`all` option](#all-2) is `false` (the default value)426 - both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)427 405-This is an array if the [`lines` option](#lines) is `true, or if either the `stdout` or `stderr` option is a [transform in object mode](docs/transform.md#object-mode).428+This is an array if the [`lines` option](#lines) is `true`, or if either the `stdout` or `stderr` option is a [transform in object mode](docs/transform.md#object-mode).429 430 #### stdio431 432 Type: `Array<string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined>`75 unmodified lines508 A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.509 510 If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.511 512+#### pipedFrom513+514+Type: [`ChildProcessResult[]`](#childprocessresult)515+516+Results of the other processes that were [piped](#pipe-multiple-processes) into this child process. This is useful to inspect a series of child processes piped with each other.517+518+This array is initially empty and is populated each time the [`.pipe()`](#pipesecondchildprocess-pipeoptions) method resolves.519+520 ### options521 522 Type: `object`523 467 unmodified lines