Skip to content
Myr

Fix `.pipe()` and stream conversion edge cases

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

authored by Sindre Sorhus · committed by Sindre Sorhus · parent fb92da1 · Browse files · 16 files+394 added−26 removed
This commit

State

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

Diff stats

16 files+394 added−26 removed

  • tests:+303 added−1 removed
  • other:+91 added−25 removed

16 files+394 added−26 removed

modified:lib/convert/readable.js+6 added-5 removed
modified:lib/convert/shared.js+3 added-3 removed
modified:lib/convert/writable.js+10 added-7 removed
5 unmodified lines
6import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';7import {8 safeWaitForSubprocessStdout,9 waitForSubprocessStdin,10 waitForSubprocess,10 throwDestroyError,11 destroyOtherStream,12} from './shared.js';1314// Create a `Writable` stream that forwards to `stdin` and awaits the subprocess
62 unmodified lines
77 writable.end();78 }79 } catch (error) {80 await safeWaitForSubprocessStdout(subprocessStdout);81 // `writable.writable` is already `false` once `writable.end()` is called, although its pending writes still wait for `stdin`81 destroyOtherWritable(writable, await getSubprocessError(subprocess, error));82 destroyOtherStream(writable, !writable.writableFinished, await getSubprocessError(subprocess, error));83 }84};8586const getSubprocessError = async (subprocess, error) => {
9 unmodified lines
9697 return error;98};99100// `EPIPE` happens when the subprocess fails without reading its `stdin`, e.g. when it fails to spawn101const shouldUseSubprocessError = error => error === undefined100 || isStreamAbort(error);102 || isStreamAbort(error)103 || error.code === 'EPIPE';104105// When `writable` aborts/errors, do the same on `subprocess.stdin`106export const onWritableDestroy = async ({subprocessStdin, subprocess, waitWritableFinal, waitWritableDestroy}, error) => {107 await waitForConcurrentStreams(waitWritableFinal, subprocess);105 if (!await waitForConcurrentStreams(waitWritableDestroy, subprocess)) {106 return;108 if (await waitForConcurrentStreams(waitWritableDestroy, subprocess)) {109 destroyOtherWritable(subprocessStdin, error);110 await subprocess;111 }112109 destroyOtherWritable(subprocessStdin, error);110 await waitForSubprocess(subprocess, error);113 throwDestroyError(error);114};115116const destroyOtherWritable = (stream, error) => {117 destroyOtherStream(stream, stream.writable, error);
1 unmodified line
modified:lib/io/pipeline.js+9 added-4 removed
1import {finished} from 'node:stream/promises';2import {isStandardStream} from '../utils/standard-stream.js';34// Similar to `Stream.pipeline(source, destination)`, but does not destroy standard streams5export const pipeStreams = (source, destination) => {4// Similar to `Stream.pipeline(source, destination)`, but does not destroy standard streams.5// `onDestinationEnd` runs when the destination ends, before the source is aborted.6export const pipeStreams = (source, destination, onDestinationEnd) => {7 source.pipe(destination);8 onSourceFinish(source, destination);8 onDestinationFinish(source, destination);9 onDestinationFinish(source, destination, onDestinationEnd);10};1112// `source.pipe(destination)` makes `destination` end when `source` ends.13// But it does not propagate aborts or errors. This function does it.
15 unmodified lines
29 }30};3132// We do the same thing in the other direction as well.32const onDestinationFinish = async (source, destination) => {33const onDestinationFinish = async (source, destination, onDestinationEnd) => {34 if (isStandardStream(source) || isStandardStream(destination)) {35 return;36 }3738 try {39 await finished(destination, {cleanup: true, readable: false, writable: true});40 } catch {}4142 if (onDestinationEnd !== undefined) {43 await onDestinationEnd();44 }4546 abortSourceStream(source);47};4849export const abortSourceStream = source => {
4 unmodified lines
modified:lib/pipe/abort.js+2 added-1 removed
1import {aborted} from 'node:util';2import {createNonCommandError} from './throw.js';3import {unpipeSubprocessStream} from './streaming.js';45// When passing an `unpipeSignal` option, abort piping when the signal is aborted.6// However, do not terminate the subprocesses.7export const unpipeOnAbort = (unpipeSignal, unpipeContext) => unpipeSignal === undefined
1 unmodified line
9 : [unpipeOnSignalAbort(unpipeSignal, unpipeContext)];1011const unpipeOnSignalAbort = async (unpipeSignal, {sourceStream, mergedStream, fileDescriptors, sourceOptions, startTime}) => {12 await aborted(unpipeSignal, sourceStream);12 await mergedStream.remove(sourceStream);13 await unpipeSubprocessStream(mergedStream, sourceStream);14 const error = new Error('Pipe canceled by `unpipeSignal` option.');15 throw createNonCommandError({16 error,17 fileDescriptors,
4 unmodified lines
modified:lib/pipe/pipe-arguments.js+1 added
15 unmodified lines
16 } = getDestinationStream(boundOptions, createNested, pipeArguments);17 const {sourceStream, sourceError} = getSourceStream(source, from);18 const {options: sourceOptions, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);19 return {20 source,21 sourcePromise,22 sourceStream,23 sourceOptions,24 sourceError,
99 unmodified lines
modified:lib/pipe/sequence.js+3 added-2 removed
4 unmodified lines
5export const waitForBothSubprocesses = async subprocessPromises => {6 const [7 {status: sourceStatus, reason: sourceReason, value: sourceResult = sourceReason},8 {status: destinationStatus, reason: destinationReason, value: destinationResult = destinationReason},9 {reason: pipedFromReason, value: pipedFromResult = pipedFromReason},10 ] = await subprocessPromises;1111 if (!destinationResult.pipedFrom.includes(sourceResult)) {12 destinationResult.pipedFrom.push(sourceResult);12 if (!destinationResult.pipedFrom.includes(pipedFromResult)) {13 destinationResult.pipedFrom.push(pipedFromResult);14 }1516 if (destinationStatus === 'rejected') {17 throw destinationResult;
8 unmodified lines
modified:lib/pipe/setup.js+12 added-2 removed
19 unmodified lines
20 boundOptions: {...sourceInfo.boundOptions, ...pipeArguments[0]},21 });22 }2324 // The previous `.pipe()` failed because of its arguments, so there is no source. Its promise rejects with that error.25 // The destination is not spawned, since nothing would end its `stdin`.26 if (sourceInfo.source === undefined) {27 return sourceInfo.sourcePromise;28 }2930 const {destination, ...normalizedInfo} = normalizePipeArguments(sourceInfo, ...pipeArguments);31 const pipeFailureController = new AbortController();32 const promise = handlePipePromise({...normalizedInfo, destination, pipeFailureController});33 promise.pipe = pipeToSubprocess.bind(undefined, {
46 unmodified lines
80 Object.defineProperty(promise, 'all', {81 get() {82 setAllProperty(promise, destination.all);83 const all = promise.readable({from: 'all'});84 // Like `subprocess.all`, the pipe's failure is handled by awaiting it, not by listening to the stream's `error` event. Consumers like `text(all)` still fail.85 all.on('error', () => {});86 setAllProperty(promise, all);87 return all;88 },89 enumerable: true,
98 unmodified lines
188// `writable()`, `duplex()`, `writableStream()` and `transformStream()` are intentionally not forwarded: they write to the destination's `stdin`, which is already being piped from the source.189190// Asynchronous logic when piping subprocesses191const handlePipePromise = async ({192 source,193 sourcePromise,194 sourceStream,195 sourceOptions,196 sourceError,
6 unmodified lines
203 pipeFailureController,204}) => {205 const maxListenersController = new AbortController();206 try {198 const subprocessPromises = getSubprocessPromises(sourcePromise, destination);207 const subprocessPromises = getSubprocessPromises(sourcePromise, destination, source);208 handlePipeArgumentsError({209 sourceStream,210 sourceError,211 destinationStream,
23 unmodified lines
235236// `.pipe()` awaits the subprocess promises.237// When invalid arguments are passed to `.pipe()`, we throw an error, which prevents awaiting them.238// We need to ensure this does not create unhandled rejections.230const getSubprocessPromises = (sourcePromise, destination) => Promise.allSettled([sourcePromise, destination]);239// With `source.pipe(destination).pipe(secondDestination)`, the second `sourcePromise` is the first `.pipe()`, which rejects with the error of either subprocess. However, `secondDestination` is only piped from `destination`.240const getSubprocessPromises = (sourcePromise, destination, source) => Promise.allSettled([sourcePromise, destination, source]);
modified:lib/pipe/streaming.js+44 added-1 removed
20 unmodified lines
2122// We use `merge-streams` to allow for multiple sources to pipe to the same destination.23const pipeFirstSubprocessStream = (sourceStream, destinationStream) => {24 const mergedStream = mergeStreams([sourceStream]);25 pipeStreams(mergedStream, destinationStream);25 addMergeSource(mergedStream, sourceStream);26 pipeStreams(mergedStream, destinationStream, () => unpipeSourcesOnDestinationEnd(mergedStream));27 MERGED_STREAMS.set(destinationStream, mergedStream);28 return mergedStream;29};3031const pipeMoreSubprocessStream = (sourceStream, destinationStream) => {32 const mergedStream = MERGED_STREAMS.get(destinationStream);33 mergedStream.add(sourceStream);34 addMergeSource(mergedStream, sourceStream);35 return mergedStream;36};3738/*39One source stream can be piped to multiple destinations, e.g. `subprocess.pipe(first)` and `subprocess.pipe(second)`.40When a destination ends, its source must only be aborted when it is its last destination, so the other destinations keep receiving data.41Sources with several destinations are then only removed from the ended destination's merge stream, instead of being aborted.42This also holds when a source has been piped to one destination and unpiped from another one.43*/44const MERGE_SOURCES = new WeakMap();45const SOURCE_MERGES = new WeakMap();4647const addMergeSource = (mergedStream, sourceStream) => {48 addToSetMap(MERGE_SOURCES, mergedStream, sourceStream);49 addToSetMap(SOURCE_MERGES, sourceStream, mergedStream);50};5152const addToSetMap = (map, key, value) => {53 if (!map.has(key)) {54 map.set(key, new Set());55 }5657 map.get(key).add(value);58};5960// Stop piping a source into a destination, e.g. with the `unpipeSignal` option61export const unpipeSubprocessStream = async (mergedStream, sourceStream) => {62 MERGE_SOURCES.get(mergedStream)?.delete(sourceStream);63 SOURCE_MERGES.get(sourceStream)?.delete(mergedStream);64 await mergedStream.remove(sourceStream);65};6667const unpipeSourcesOnDestinationEnd = async mergedStream => {68 for (const sourceStream of MERGE_SOURCES.get(mergedStream)) {69 const mergedStreams = SOURCE_MERGES.get(sourceStream);70 mergedStreams.delete(mergedStream);71 if (mergedStreams.size > 0) {72 // Other destinations still need that source, so it must not be aborted73 // eslint-disable-next-line no-await-in-loop74 await mergedStream.remove(sourceStream);75 }76 }77};7879const cleanupMergedStreamsMap = async destinationStream => {80 try {81 await finished(destinationStream, {cleanup: true, readable: false, writable: true});82 } catch {}
12 unmodified lines
modified:lib/resolve/wait-stream.js+1 added
95 unmodified lines
9697// When `stream.destroy()` is called without an `error` argument, stream is aborted.98// This is the only way to abort a readable stream, which can be useful in some instances.99// Therefore, we ignore this error on readable streams.100// Breaking out of `for await (const chunk of subprocess.stdout)` aborts it with an `AbortError` instead. However, that error cannot be told apart from an `AbortError` thrown by a transform, which must make the subprocess fail. So this is not supported, and `subprocess.readable()` or `subprocess.iterable()` should be used instead.101export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';102103// When `stream.write()` is called but the underlying source has been closed, `EPIPE` is emitted.104// When piping subprocesses, the source subprocess usually decides when to stop piping.
4 unmodified lines
modified:test/convert/readable.js+32 added
81 unmodified lines
8283test('.readable() buffers until read', () => testBuffering('readable'));84test('.duplex() buffers until read', () => testBuffering('duplex'));8586// Breaking out of `for await` or cancelling a web stream destroys the stream with an `AbortError`, which aborts it like `stream.destroy()`87const testStopIteration = async stopIteration => {88 const subprocess = execa('noop-delay.js', ['1', foobarString]);89 await stopIteration(subprocess);90 const {exitCode} = await subprocess;91 assert.equal(exitCode, 0);92};9394const stopIterator = async asyncIterable => {95 const iterator = asyncIterable[Symbol.asyncIterator]();96 await iterator.next();97 await iterator.return();98};99100const cancelReader = async readableStream => {101 const reader = readableStream.getReader();102 await reader.read();103 await reader.cancel();104};105106test('.readable() iteration can be stopped', () => testStopIteration(subprocess => stopIterator(subprocess.readable())));107// This destroys `subprocess.stdout` with an `AbortError`, which cannot be told apart from an `AbortError` thrown by a transform. So this is not supported, and `subprocess.readable()` or `subprocess.iterable()` must be used instead.108test('subprocess.stdout iteration cannot be stopped', async () => {109 const subprocess = execa('noop-delay.js', ['1', foobarString]);110 await stopIterator(subprocess.stdout);111 const {code} = await assertRejects(subprocess);112 assert.equal(code, 'ABORT_ERR');113});114test('.readableStream() can be cancelled', () => testStopIteration(subprocess => cancelReader(subprocess.readableStream())));115test('.readableStream() iteration can be stopped', () => testStopIteration(subprocess => stopIterator(subprocess.readableStream())));116test('.iterable() iteration can be stopped', () => testStopIteration(subprocess => stopIterator(subprocess.iterable())));117118test('.readable() abort -> subprocess fail', async () => {119 const subprocess = execa('noop-repeat.js');120 const stream = subprocess.readable();121
374 unmodified lines
modified:test/convert/shared.js+94 added
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {setImmediate} from 'node:timers/promises';4import test from 'node:test';5import {assertRejects, assertThrows} from '../helpers/assert.js';6import {execa} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';
50 unmodified lines
58test('Do not need to await subprocess with .readable()', () => testSubprocessError('readable'));59test('Do not need to await subprocess with .writable()', () => testSubprocessError('writable'));60test('Do not need to await subprocess with .duplex()', () => testSubprocessError('duplex'));6162// Once the subprocess has ended, the error passed to `stream.destroy(error)` must still be emitted, including when another stream uses the same file descriptor63const testDestroyAfterExit = async (methodName, fixtureName, otherMethodName) => {64 const subprocess = execa(fixtureName, {reject: false});65 const stream = subprocess[methodName]();66 if (otherMethodName !== undefined) {67 subprocess[otherMethodName]().on('error', () => {});68 }6970 await subprocess;71 const cause = new Error(foobarString);72 let errorEvent;73 stream.on('error', error => {74 errorEvent = error;75 });76 stream.destroy(cause);77 await assertRejects(finishedStream(stream));78 assert.equal(errorEvent, cause);79};8081test('.readable() destroy error after the subprocess ended', () => testDestroyAfterExit('readable', 'empty.js'));82test('.writable() destroy error after the subprocess ended', () => testDestroyAfterExit('writable', 'empty.js'));83test('.duplex() destroy error after the subprocess ended', () => testDestroyAfterExit('duplex', 'empty.js'));84test('.readable() destroy error after the subprocess ended, with .duplex()', () => testDestroyAfterExit('readable', 'empty.js', 'duplex'));85test('.writable() destroy error after the subprocess ended, with .duplex()', () => testDestroyAfterExit('writable', 'empty.js', 'duplex'));86test('.duplex() destroy error after the subprocess ended, with .writable()', () => testDestroyAfterExit('duplex', 'empty.js', 'writable'));87test('.duplex() destroy error after the subprocess ended, with .duplex()', () => testDestroyAfterExit('duplex', 'empty.js', 'duplex'));88test('.readable() destroy error after the subprocess failed, with .duplex()', () => testDestroyAfterExit('readable', 'fail.js', 'duplex'));89test('.writable() destroy error after the subprocess failed, with .duplex()', () => testDestroyAfterExit('writable', 'fail.js', 'duplex'));90test('.duplex() destroy error after the subprocess failed, with .writable()', () => testDestroyAfterExit('duplex', 'fail.js', 'writable'));9192// The pending write waits for the `drain` event, so it must fail instead of hanging93test('.writable() write fails when the subprocess fails to spawn', async () => {94 const subprocess = execa('nonexistent-command-for-execa');95 const stream = subprocess.writable();96 const chunk = '.'.repeat(1e5);97 const writeAll = async () => {98 for (let index = 0; index < 1e2; index += 1) {99 if (!stream.write(chunk)) {100 // eslint-disable-next-line no-await-in-loop101 await once(stream, 'drain');102 }103 }104105 stream.end();106 await finishedStream(stream);107 };108109 const error = await assertRejects(writeAll());110 assert.equal(error, await assertRejects(subprocess));111});112113// The subprocess error is more useful than the `EPIPE` error it causes on `stdin`114const testSpawnFailureWrite = async methodName => {115 const subprocess = execa('nonexistent-command-for-execa');116 const stream = subprocess[methodName]();117 stream.end(foobarString);118 const error = await assertRejects(finishedStream(stream));119 assert.equal(error, await assertRejects(subprocess));120 assert.equal(error.code, 'ENOENT');121};122123test('.writable() fails with the subprocess error when the subprocess fails to spawn', () => testSpawnFailureWrite('writable'));124test('.duplex() fails with the subprocess error when the subprocess fails to spawn', () => testSpawnFailureWrite('duplex'));125126// The pending write waits for the `drain` event of `stdin`, which has been destroyed, so the stream must be destroyed too, even though it is ending127const testWriteAfterExit = async (methodName, isSameTick) => {128 const subprocess = execa('empty.js');129 await subprocess;130 const stream = subprocess[methodName]();131 if (!isSameTick) {132 await setImmediate();133 }134135 stream.end(foobarString);136 const error = await assertRejects(finishedStream(stream));137 assert.equal(error.code, 'ERR_STREAM_PREMATURE_CLOSE');138};139140test('.writable() fails when ending it after the subprocess ended', () => testWriteAfterExit('writable', true));141test('.duplex() fails when ending it after the subprocess ended', () => testWriteAfterExit('duplex', true));142test('.writable() fails when ending it later after the subprocess ended', () => testWriteAfterExit('writable', false));143test('.duplex() fails when ending it later after the subprocess ended', () => testWriteAfterExit('duplex', false));144145test('.writable() fails with the subprocess error when the subprocess fails without reading stdin', async () => {146 const subprocess = execa('fail.js');147 const stream = subprocess.writable();148 stream.end('.'.repeat(1e6));149 const error = await assertRejects(finishedStream(stream));150 assert.equal(error, await assertRejects(subprocess));151 assert.equal(error.exitCode, 2);152});153154const testNullOptions = async methodName => {155 const subprocess = getReadWriteSubprocess();156 subprocess.stdin.end();157 assertThrows(() => {
9 unmodified lines
modified:test/pipe/methods.js+23 added-1 removed
1import assert from 'node:assert/strict';2import {setTimeout} from 'node:timers/promises';3import {Readable} from 'node:stream';3import {Readable, Writable} from 'node:stream';4import {text} from 'node:stream/consumers';5import test from 'node:test';6import {assertThrows, assertRejects} from '../helpers/assert.js';7import {execa} from '../../index.js';
369 unmodified lines
377378 await assertRejects(text(piped.all), {message: /Command failed with exit code 2/});379});380381// Like `subprocess.all`, `.all` does not need an `error` listener, as long as the pipe is awaited382test('The .pipe() return value .all does not need an error listener on source failure', async () => {383 const piped = execa('fail.js').pipe('stdin.js', {all: true});384 piped.all.resume();385 await assertRejects(piped, {message: /Command failed with exit code 2/});386 await setTimeout(0);387});388389test('The .pipe() return value .all does not need an error listener when piped', async () => {390 const piped = execa('fail.js').pipe('stdin.js', {all: true});391 const chunks = [];392 piped.all.pipe(new Writable({393 write(chunk, encoding, done) {394 chunks.push(chunk);395 done();396 },397 }));398 await assertRejects(piped, {message: /Command failed with exit code 2/});399 await setTimeout(0);400 assert.deepEqual(chunks, []);401});402403const assertCanceledPipeReader = async (t, getReader, shouldAbortBeforePipe = false) => {404 const abortController = new AbortController();405 if (shouldAbortBeforePipe) {406 abortController.abort();
50 unmodified lines
modified:test/pipe/streaming.js+86 added
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {setTimeout} from 'node:timers/promises';4import {PassThrough} from 'node:stream';5import test from 'node:test';6import {assertRejects, assertLike} from '../helpers/assert.js';7import {execa} from '../../index.js';
364 unmodified lines
372 assert.deepEqual(destinationResult.pipedFrom, [sourceResult]);373 assert.deepEqual(sourceResult.pipedFrom, []);374});375376// The second destination is piped from the first destination, not from the source which failed377test('Returns pipedFrom on deep source failure', async () => {378 const source = execa('noop-fail.js', ['1', foobarString]);379 const destination = execa('stdin.js');380 const secondDestination = execa('stdin.js');381 const pipePromise = source.pipe(destination);382 const secondPipePromise = pipePromise.pipe(secondDestination);383384 const destinationResult = await destination;385 const secondDestinationResult = await secondDestination;386 const sourceResult = await assertRejects(source);387388 assert.equal(await assertRejects(secondPipePromise), sourceResult);389 assert.deepEqual(secondDestinationResult.pipedFrom, [destinationResult]);390 assert.equal(await assertRejects(pipePromise), sourceResult);391 assert.deepEqual(destinationResult.pipedFrom, [sourceResult]);392 assert.deepEqual(sourceResult.pipedFrom, []);393});394395test('Returns pipedFrom on deep success, with a template string', async () => {396 const pipePromise = execa('noop.js', [foobarString]).pipe`stdin.js`.pipe`stdin.js`;397 const {stdout, pipedFrom} = await pipePromise;398 assert.equal(stdout, foobarString);399 const [destinationResult] = pipedFrom;400 assert.equal(destinationResult.command, 'stdin.js');401 assert.equal(destinationResult.pipedFrom[0].command, `noop.js ${foobarString}`);402});403404test('Returns pipedFrom from multiple sources', async () => {405 const source = execa('noop.js', [foobarString]);406 const secondSource = execa('noop.js', [foobarString]);407 const destination = execa('stdin.js');
70 unmodified lines
478 stdio: ['pipe', 'pipe', 'pipe', {value: 'pipe', input: true}],479 });480 assert.equal(stdout, foobarString);481});482483// `noop-repeat.js` writes every 10ms. `noop.js` exits right away, since it does not read its `stdin`.484const testNoStarvation = async ({pipeOptions, sourceOptions, getExitingDestination = () => execa('noop.js')}) => {485 const source = execa('noop-repeat.js', ['1', `${foobarString}\n`], sourceOptions);486 const exitingDestination = getExitingDestination();487 const receivingDestination = execa('stdin.js');488 source.pipe(exitingDestination, pipeOptions).catch(() => {});489 source.pipe(receivingDestination, pipeOptions).catch(() => {});490491 await exitingDestination;492 await setTimeout(100);493 source.kill();494 // The source is not aborted with `EPIPE` when the first destination exits495 const {isTerminated} = await assertRejects(source);496 assert.ok(isTerminated);497 const {stdout} = await receivingDestination;498 assert.ok(stdout.split('\n').length > 2);499};500501test('One destination exiting does not starve the other destinations', () => testNoStarvation({}));502test('One destination exiting does not starve the other destinations, from "all"', () => testNoStarvation({sourceOptions: {all: true}, pipeOptions: {from: 'all'}}));503// `stdin.js` exits when its `stdin` ends, while `noop-repeat.js` keeps running504test('One destination ending its stdin does not starve the other destinations', () => testNoStarvation({505 getExitingDestination() {506 const destination = execa('stdin.js');507 destination.stdin.end();508 return destination;509 },510}));511512test('The source is aborted when all its destinations exit', async () => {513 const source = execa('noop-repeat.js', ['1', `${foobarString}\n`]);514 source.pipe(execa('noop.js')).catch(() => {});515 source.pipe(execa('noop.js')).catch(() => {});516 const {isTerminated, exitCode} = await assertRejects(source);517 assert.ok(!isTerminated);518 assert.equal(exitCode, 1);519});520521test('The other sources of an exiting destination are aborted, unless they have other destinations', async () => {522 const source = execa('noop-repeat.js', ['1', `${foobarString}\n`]);523 const secondSource = execa('noop-repeat.js', ['1', `${foobarString}\n`]);524 const exitingDestination = execa('noop.js');525 const receivingDestination = execa('stdin.js');526 source.pipe(exitingDestination).catch(() => {});527 secondSource.pipe(exitingDestination).catch(() => {});528 source.pipe(receivingDestination).catch(() => {});529530 const {exitCode} = await assertRejects(secondSource);531 assert.equal(exitCode, 1);532 await setTimeout(200);533 source.kill();534 const {isTerminated} = await assertRejects(source);535 assert.ok(isTerminated);536 const {stdout} = await receivingDestination;537 assert.ok(stdout.split('\n').length > 2);538});
modified:test/pipe/throw.js+23 added
38 unmodified lines
39 const {stdout} = await source;40 assert.equal(stdout, undefined);41});4243// When a previous `.pipe()` failed because of its arguments, the next `.pipe()` has no source.44// It must reject with that error, without spawning its destination, which would otherwise keep waiting for its `stdin`.45const testChainedInvalidPipe = async (getPipePromise, firstPipeArguments = [false], expectedMessage = 'an Execa subprocess') => {46 const source = execa('noop.js', [foobarString]);47 let isSpawned = false;48 const verbose = (verboseLine, {type}) => {49 if (type === 'command') {50 isSpawned = true;51 }52 };5354 const pipePromise = getPipePromise(source.pipe(...firstPipeArguments), verbose);55 await assertPipeError(pipePromise, expectedMessage);56 assert.equal(isSpawned, false);57 await source;58};5960test('.pipe("file") after invalid arguments', () => testChainedInvalidPipe((pipePromise, verbose) => pipePromise.pipe('stdin.js', {verbose})));61test('.pipe`command` after invalid arguments', () => testChainedInvalidPipe((pipePromise, verbose) => pipePromise.pipe({verbose})`stdin.js`));62test('.pipe.pipe("file") after invalid arguments', () => testChainedInvalidPipe((pipePromise, verbose) => pipePromise.pipe('stdin.js', {verbose}).pipe('stdin.js', {verbose})));63test('.pipe(false) after invalid arguments', () => testChainedInvalidPipe(pipePromise => pipePromise.pipe(false)));64test('.pipe("file") after an invalid "to" option', () => testChainedInvalidPipe((pipePromise, verbose) => pipePromise.pipe('stdin.js', {verbose}), ['empty.js', {to: 'fd9'}], 'fd9'));6566// The destination subprocess is spawned before the `to` option is validated, so its error must be handled.67// This runs in another process, since that is where the unhandled rejection crashes it.68test('Destination subprocess error is not unhandled when the "to" option is invalid', async () => {69 const {stdout} = await execa('pipe-destination-error.js', ['fail.js']);
28 unmodified lines
modified:test/transform/generator-error.js+45 added
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {setTimeout} from 'node:timers/promises';4import {readFile, rm} from 'node:fs/promises';5import test from 'node:test';6import tempfile from 'tempfile';7import {assertThrows, assertRejects, assertLike} from '../helpers/assert.js';
109 unmodified lines
117};118119test('Transform errors on stdout do not skip the stderr file', () => testTransformErrorOtherFd(execa));120test('Transform errors on stdout do not skip the stderr file, sync', () => testTransformErrorOtherFd(execaSync));121122// Many signal-aware Node.js APIs reject with an `AbortError`, which must not be mistaken for the stream being aborted123const testAbortErrorTransform = async abortedLine => {124 const controller = new AbortController();125 const {failed, cause} = await execa('noop-fd.js', ['1', 'a\nb\nc'], {126 async * stdout(line) {127 if (line === abortedLine) {128 controller.abort();129 }130131 await setTimeout(0, undefined, {signal: controller.signal});132 yield line;133 },134 reject: false,135 });136 assert.equal(failed, true);137 assert.equal(cause.code, 'ABORT_ERR');138};139140test('Output generators throwing an AbortError make the subprocess fail', () => testAbortErrorTransform('a'));141test('Output generators throwing an AbortError after some output make the subprocess fail', () => testAbortErrorTransform('b'));142143const abortErrorGenerator = async function * (line) {144 await setTimeout(0, undefined, {signal: AbortSignal.abort()});145 yield line;146};147148const testAbortErrorConversion = async consumeOutput => {149 const subprocess = execa('noop-fd.js', ['1', foobarString], {stdout: abortErrorGenerator});150 const error = await assertRejects(consumeOutput(subprocess));151 assert.equal(error.cause.code, 'ABORT_ERR');152 await assertRejects(subprocess);153};154155test('Output generators throwing an AbortError make the subprocess fail, with .readable()', () => testAbortErrorConversion(subprocess => subprocess.readable().toArray()));156test('Output generators throwing an AbortError make the subprocess fail, with .duplex()', () => testAbortErrorConversion(subprocess => subprocess.duplex().toArray()));157test('Output generators throwing an AbortError make the subprocess fail, with .iterable()', () => testAbortErrorConversion(subprocess => Array.fromAsync(subprocess.iterable())));158test('Output generators throwing an AbortError make the subprocess fail, with .readableStream()', () => testAbortErrorConversion(subprocess => Array.fromAsync(subprocess.readableStream())));159160test('Input generators throwing an AbortError make the subprocess fail', async () => {161 const {failed, cause} = await execa('stdin.js', {stdin: abortErrorGenerator, input: foobarString, reject: false});162 assert.equal(failed, true);163 assert.equal(cause.code, 'ABORT_ERR');164});