Allow passing generators to the `std*` options (#693)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 1825aea · Browse files · 15 files·+722 added−31 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+722 added−31 removed
- tests:+420 added−1 removed
- other:+302 added−30 removed
Provenance
- Commit
e8f6bbd- Tree
facc499- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
1825aea
15 files changed+722 added−31 removed
added:docs/transform.md+57 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657# Transforms
## Summary
Transforms map or filter the input or output of a child process. They are defined by passing an [async generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function*) to the [`stdin`](../readme.md#stdin), [`stdout`](../readme.md#stdout-1), [`stderr`](../readme.md#stderr-1) or [`stdio`](../readme.md#stdio-1) option.
```jsimport {execa} from 'execa';
const transform = async function * (chunks) { for await (const chunk of chunks) { yield chunk.toUpperCase(); }};
const {stdout} = await execa('echo', ['hello'], {stdout: transform});console.log(stdout); // HELLO```
## Encoding
The `chunks` argument passed to the transform is an [`AsyncIterable<string>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). If the [`encoding`](../readme.md#encoding) option is `buffer`, it is an `AsyncIterable<Uint8Array>` instead.
The transform can `yield` either a `string` or an `Uint8Array`, regardless of the `chunks` argument's type.
## Filtering
`yield` can be called 0, 1 or multiple times. Not calling `yield` enables filtering a specific chunk.
```jsimport {execa} from 'execa';
const transform = async function * (chunks) { for await (const chunk of chunks) { if (!chunk.includes('secret')) { yield chunk; } }};
const {stdout} = await execa('echo', ['This is a secret.'], {stdout: transform});console.log(stdout); // ''```
## Combining
The [`stdin`](../readme.md#stdin), [`stdout`](../readme.md#stdout-1), [`stderr`](../readme.md#stderr-1) and [`stdio`](../readme.md#stdio-1) options can accept an array of values. While this is not specific to transforms, this can be useful with them too. For example, the following transform impacts the value printed by `inherit`.
```jsawait execa('echo', ['hello'], {stdout: [transform, 'inherit']});```
This also allows using multiple transforms.
```jsawait execa('echo', ['hello'], {stdout: [transform, otherTransform]});```modified:lib/stdio/async.js+14 added-2 removed
2 unmodified lines345678910112 unmodified lines1415161718192021222324252627282930316 unmodified lines3839404139404243444546474849505152535455565758596061626364657 unmodified lines2 unmodified linesimport {Readable, Writable} from 'node:stream';import mergeStreams from '@sindresorhus/merge-streams';import {handleInput} from './handle.js';import {TYPE_TO_MESSAGE} from './type.js';import {generatorToTransformStream, pipeGenerator} from './generator.js';
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async modeexport const handleInputAsync = options => handleInput(addPropertiesAsync, options);
2 unmodified lines};
const addPropertiesAsync = { input: { generator: generatorToTransformStream, fileUrl: ({value}) => ({value: createReadStream(value)}), filePath: ({value}) => ({value: createReadStream(value.file)}), webStream: ({value}) => ({value: Readable.fromWeb(value)}), iterable: ({value}) => ({value: Readable.from(value)}), string: ({value}) => ({value: Readable.from(value)}), uint8Array: ({value}) => ({value: Readable.from(Buffer.from(value))}), }, output: { generator: generatorToTransformStream, fileUrl: ({value}) => ({value: createWriteStream(value)}), filePath: ({value}) => ({value: createWriteStream(value.file)}), webStream: ({value}) => ({value: Writable.fromWeb(value)}), iterable: forbiddenIfAsync,6 unmodified linesexport const pipeOutputAsync = (spawned, stdioStreamsGroups) => { const inputStreamsGroups = {};
for (const stdioStreams of stdioStreamsGroups) { for (const stdioStream of stdioStreams) { pipeStdioOption(spawned, stdioStream, inputStreamsGroups); const generatorStreams = sortGeneratorStreams(stdioStreams.filter(({type}) => type === 'generator')); const nonGeneratorStreams = stdioStreams.filter(({type}) => type !== 'generator');
for (const generatorStream of generatorStreams) { pipeGenerator(spawned, generatorStream); }
for (const nonGeneratorStream of nonGeneratorStreams) { pipeStdioOption(spawned, nonGeneratorStream, inputStreamsGroups); } }
for (const [index, inputStreams] of Object.entries(inputStreamsGroups)) { const value = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams); value.pipe(spawned.stdio[index]); }};
const sortGeneratorStreams = generatorStreams => generatorStreams[0]?.direction === 'input' ? generatorStreams.reverse() : generatorStreams;
const pipeStdioOption = (spawned, {type, value, direction, index}, inputStreamsGroups) => { if (type === 'native') { return; }7 unmodified linesmodified:lib/stdio/direction.js+1 added
29 unmodified lines30313233343536373830 unmodified lines29 unmodified linesconst alwaysInput = () => 'input';
// `string` can only be added through the `input` option, i.e. does not need to be handled hereconst guessStreamDirection = { generator: anyDirection, fileUrl: anyDirection, filePath: anyDirection, iterable: alwaysInput, uint8Array: alwaysInput,30 unmodified linesadded:lib/stdio/generator.js+109 added
1+import {Duplex, Readable, PassThrough, getDefaultHighWaterMark} from 'node:stream';2+3+/*4+Generators can be used to transform/filter standard streams.5+6+Generators have a simple syntax, yet allows all of the following:7+- Sharing state between chunks, by using logic before the `for` loop8+- Flushing logic, by using logic after the `for` loop9+- Asynchronous logic10+- Emitting multiple chunks from a single source chunk, even if spaced in time, by using multiple `yield`11+- Filtering, by using no `yield`12+13+Therefore, there is no need to allow Node.js or web transform streams.14+15+The `highWaterMark` is kept as the default value, since this is what `childProcess.std*` uses.16+17+We ensure `objectMode` is `false` for better buffering.18+19+Chunks are currently processed serially. We could add a `concurrency` option to parallelize in the future.20+21+We return a `Duplex`, created by `Duplex.from()` made of a writable stream and a readable stream, piped to each other.22+- The writable stream is a simple `PassThrough`, so it only forwards data to the readable part.23+- The `PassThrough` is read as an iterable using `passThrough.iterator()`.24+- This iterable is transformed to another iterable, by applying the encoding generators.25+ Those convert the chunk type from `Buffer` to `string | Uint8Array` depending on the encoding option.26+- This new iterable is transformed again to another one, this time by applying the user-supplied generator.27+- Finally, `Readable.from()` is used to convert this final iterable to a `Readable` stream.28+*/29+export const generatorToTransformStream = ({value}, {encoding}) => {30+ const objectMode = false;31+ const highWaterMark = getDefaultHighWaterMark(objectMode);32+ const passThrough = new PassThrough({objectMode, highWaterMark, destroy: destroyPassThrough});33+ const iterable = passThrough.iterator();34+ const encodedIterable = applyEncoding(iterable, encoding);35+ const mappedIterable = value(encodedIterable);36+ const readableStream = Readable.from(mappedIterable, {objectMode, highWaterMark});37+ const duplexStream = Duplex.from({writable: passThrough, readable: readableStream});38+ return {value: duplexStream};39+};40+41+/*42+When an error is thrown in a generator, the PassThrough is aborted.43+44+This creates a race condition for which error is propagated, due to the Duplex throwing twice:45+- The writable side is aborted (PassThrough)46+- The readable side propagate the generator's error47+48+In order for the later to win that race, we need to wait one microtask.49+- However we wait one macrotask instead to be on the safe side50+- See https://github.com/sindresorhus/execa/pull/693#discussion_r145380945051+*/52+const destroyPassThrough = (error, done) => {53+ setTimeout(() => {54+ done(error);55+ }, 0);56+};57+58+// When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.59+// This allows generator functions to operate with those types instead.60+const applyEncoding = (iterable, encoding) => encoding === 'buffer'61+ ? encodingStartBufferGenerator(iterable)62+ : encodingStartStringGenerator(iterable);63+64+/*65+Chunks might be Buffer, Uint8Array or strings since:66+- `childProcess.stdout|stderr` emits Buffers67+- `childProcess.stdin.write()` accepts Buffer, Uint8Array or string68+- Previous generators might return Uint8Array or string69+70+However, those are converted to Buffer:71+- on writes: `Duplex.writable` `decodeStrings: true` default option72+- on reads: `Duplex.readable` `readableEncoding: null` default option73+*/74+const encodingStartStringGenerator = async function * (chunks) {75+ const textDecoder = new TextDecoder();76+77+ for await (const chunk of chunks) {78+ yield textDecoder.decode(chunk, {stream: true});79+ }80+81+ const lastChunk = textDecoder.decode();82+ if (lastChunk !== '') {83+ yield lastChunk;84+ }85+};86+87+const encodingStartBufferGenerator = async function * (chunks) {88+ for await (const chunk of chunks) {89+ yield new Uint8Array(chunk);90+ }91+};92+93+// `childProcess.stdin|stdout|stderr|stdio` is directly mutated.94+export const pipeGenerator = (spawned, {value, direction, index}) => {95+ if (direction === 'output') {96+ spawned.stdio[index].pipe(value);97+ } else {98+ value.pipe(spawned.stdio[index]);99+ }100+101+ const streamProperty = PROCESS_STREAM_PROPERTIES[index];102+ if (streamProperty !== undefined) {103+ spawned[streamProperty] = value;104+ }105+106+ spawned.stdio[index] = value;107+};108+109+const PROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];modified:lib/stdio/handle.js+4 added-4 removed
9 unmodified lines10 const [stdinStreams, ...otherStreamsGroups] = stdio.map((stdioOption, index) => getStdioStreams(stdioOption, index));11 const stdioStreamsGroups = [[...stdinStreams, ...handleInputOptions(options)], ...otherStreamsGroups]12 .map(stdioStreams => validateStreams(stdioStreams))13 .map(stdioStreams => addStreamDirection(stdioStreams))14- .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties));14+ .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties, options));15 options.stdio = transformStdio(stdioStreamsGroups);16 return stdioStreamsGroups;17 };18 31 unmodified lines50 // However, we do allow it if the array has a single item.51 const INVALID_STDIO_ARRAY_OPTIONS = ['ignore', 'ipc'];52 53 const getStdioStream = ({stdioOption, optionName, index, isStdioArray}) => {54- const type = getStdioOptionType(stdioOption);54+ const type = getStdioOptionType(stdioOption, optionName);55 const stdioStream = {type, value: stdioOption, optionName, index};56 return handleNativeStream(stdioStream, isStdioArray);57 };58 18 unmodified lines77 78 // Some `stdio` values require Execa to create streams.79 // For example, file paths create file read/write streams.80 // Those transformations are specified in `addProperties`, which is both direction-specific and type-specific.81-const addStreamsProperties = (stdioStreams, addProperties) => stdioStreams.map(stdioStream => ({81+const addStreamsProperties = (stdioStreams, addProperties, options) => stdioStreams.map(stdioStream => ({82 ...stdioStream,83- ...addProperties[stdioStream.direction][stdioStream.type]?.(stdioStream),83+ ...addProperties[stdioStream.direction][stdioStream.type]?.(stdioStream, options),84 }));85 86 // When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `spawned.std*`.87 // When the `std*: Array` option is used, we emulate some of the native values ('inherit', Node.js stream and file descriptor integer). To do so, we also need to pipe to `spawned.std*`.11 unmodified linesmodified:lib/stdio/sync.js+2 added
23 unmodified lines24 };25 26 const addPropertiesSync = {27 input: {28+ generator: forbiddenIfSync,29 fileUrl: ({value}) => ({value: bufferToUint8Array(readFileSync(value)), type: 'uint8Array'}),30 filePath: ({value}) => ({value: bufferToUint8Array(readFileSync(value.file)), type: 'uint8Array'}),31 webStream: forbiddenIfSync,32 nodeStream: forbiddenIfSync,33 iterable: forbiddenIfSync,34 native: forbiddenIfStreamSync,35 },36 output: {37+ generator: forbiddenIfSync,38 filePath: ({value}) => ({value: value.file}),39 webStream: forbiddenIfSync,40 nodeStream: forbiddenIfSync,41 iterable: forbiddenIfSync,40 unmodified linesmodified:lib/stdio/type.js+13 added-1 removed
1 import {isStream as isNodeStream} from 'is-stream';2 import {isUint8Array} from './utils.js';3 4 // The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.5-export const getStdioOptionType = stdioOption => {5+export const getStdioOptionType = (stdioOption, optionName) => {6+ if (isAsyncGenerator(stdioOption)) {7+ return 'generator';8+ }9+10+ if (isSyncGenerator(stdioOption)) {11+ throw new TypeError(`The \`${optionName}\` option must use an asynchronous generator, not a synchronous one.`);12+ }13+14 if (isUrl(stdioOption)) {15 return 'fileUrl';16 }17 19 unmodified lines37 38 return 'native';39 };40 41+const isAsyncGenerator = stdioOption => Object.prototype.toString.call(stdioOption) === '[object AsyncGeneratorFunction]';42+const isSyncGenerator = stdioOption => Object.prototype.toString.call(stdioOption) === '[object GeneratorFunction]';43+44 export const isUrl = stdioOption => Object.prototype.toString.call(stdioOption) === '[object URL]';45 export const isRegularUrl = stdioOption => isUrl(stdioOption) && stdioOption.protocol !== 'file:';46 47 const isFilePathObject = stdioOption => typeof stdioOption === 'object'15 unmodified lines63 && (typeof stdioOption[Symbol.asyncIterator] === 'function' || typeof stdioOption[Symbol.iterator] === 'function');64 65 // Convert types to human-friendly strings for error messages66 export const TYPE_TO_MESSAGE = {67+ generator: 'a generator',68 fileUrl: 'a file URL',69 filePath: 'a file path string',70 webStream: 'a web stream',71 nodeStream: 'a Node.js stream',5 unmodified linesadded:test/fixtures/all-fail.js+6 added
123456#!/usr/bin/env nodeimport process from 'node:process';
console.log('stdout');console.error('stderr');process.exit(1);added:test/fixtures/all.js+3 added
123#!/usr/bin/env nodeconsole.log('stdout');console.error('stderr');added:test/fixtures/nested-inherit.js+10 added
1+#!/usr/bin/env node2+import {execa} from '../../index.js';3+4+const uppercaseGenerator = async function * (chunks) {5+ for await (const chunk of chunks) {6+ yield chunk.toUpperCase();7+ }8+};9+10+await execa('noop-fd.js', ['1'], {stdout: ['inherit', uppercaseGenerator]});modified:test/fixtures/noop-fail.js+1 added-1 removed
1 #!/usr/bin/env node2 import process from 'node:process';3 import {writeSync} from 'node:fs';4 5-writeSync(Number(process.argv[2]), 'foobar');5+writeSync(Number(process.argv[2]), process.argv[3] || 'foobar');6 process.exit(2);added:test/stdio/generator.js+400 added
1+import {Buffer} from 'node:buffer';2+import {readFile, writeFile, rm} from 'node:fs/promises';3+import {getDefaultHighWaterMark, PassThrough} from 'node:stream';4+import {setTimeout} from 'node:timers/promises';5+import test from 'ava';6+import getStream from 'get-stream';7+import tempfile from 'tempfile';8+import {execa, execaSync} from '../../index.js';9+import {setFixtureDir} from '../helpers/fixtures-dir.js';10+import {getStdio} from '../helpers/stdio.js';11+12+setFixtureDir();13+14+const foobarString = 'foobar';15+const foobarUppercase = foobarString.toUpperCase();16+const foobarBuffer = Buffer.from(foobarString);17+const foobarUint8Array = new TextEncoder().encode(foobarString);18+19+const uppercaseGenerator = async function * (chunks) {20+ for await (const chunk of chunks) {21+ yield chunk.toUpperCase();22+ }23+};24+25+const testGeneratorInput = async (t, index) => {26+ const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [foobarUint8Array, uppercaseGenerator]));27+ t.is(stdout, foobarUppercase);28+};29+30+test('Can use generators with result.stdin', testGeneratorInput, 0);31+test('Can use generators with result.stdio[*] as input', testGeneratorInput, 3);32+33+const testGeneratorInputPipe = async (t, index, useShortcutProperty, encoding) => {34+ const childProcess = execa('stdin-fd.js', [`${index}`], getStdio(index, uppercaseGenerator));35+ const stream = useShortcutProperty ? childProcess.stdin : childProcess.stdio[index];36+ stream.end(encoding === 'buffer' ? foobarBuffer : foobarBuffer.toString(encoding), encoding);37+ const {stdout} = await childProcess;38+ t.is(stdout, foobarUppercase);39+};40+41+test('Can use generators with childProcess.stdio[0] and default encoding', testGeneratorInputPipe, 0, false, 'utf8');42+test('Can use generators with childProcess.stdin and default encoding', testGeneratorInputPipe, 0, true, 'utf8');43+test('Can use generators with childProcess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, 0, false, 'buffer');44+test('Can use generators with childProcess.stdin and encoding "buffer"', testGeneratorInputPipe, 0, true, 'buffer');45+test('Can use generators with childProcess.stdio[0] and encoding "hex"', testGeneratorInputPipe, 0, false, 'hex');46+test('Can use generators with childProcess.stdin and encoding "hex"', testGeneratorInputPipe, 0, true, 'hex');47+48+test('Can use generators with childProcess.stdio[*] as input', async t => {49+ const childProcess = execa('stdin-fd.js', ['3'], getStdio(3, [new Uint8Array(), uppercaseGenerator]));50+ childProcess.stdio[3].write(foobarUint8Array);51+ const {stdout} = await childProcess;52+ t.is(stdout, foobarUppercase);53+});54+55+const testGeneratorOutput = async (t, index, reject, useShortcutProperty) => {56+ const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';57+ const {stdout, stderr, stdio} = await execa(fixtureName, [`${index}`, foobarString], {...getStdio(index, uppercaseGenerator), reject});58+ const result = useShortcutProperty ? [stdout, stderr][index - 1] : stdio[index];59+ t.is(result, foobarUppercase);60+};61+62+test('Can use generators with result.stdio[1]', testGeneratorOutput, 1, true, false);63+test('Can use generators with result.stdout', testGeneratorOutput, 1, true, true);64+test('Can use generators with result.stdio[2]', testGeneratorOutput, 2, true, false);65+test('Can use generators with result.stderr', testGeneratorOutput, 2, true, true);66+test('Can use generators with result.stdio[*] as output', testGeneratorOutput, 3, true, false);67+test('Can use generators with error.stdio[1]', testGeneratorOutput, 1, false, false);68+test('Can use generators with error.stdout', testGeneratorOutput, 1, false, true);69+test('Can use generators with error.stdio[2]', testGeneratorOutput, 2, false, false);70+test('Can use generators with error.stderr', testGeneratorOutput, 2, false, true);71+test('Can use generators with error.stdio[*] as output', testGeneratorOutput, 3, false, false);72+73+const testGeneratorOutputPipe = async (t, index, useShortcutProperty) => {74+ const childProcess = execa('noop-fd.js', [`${index}`, foobarString], {...getStdio(index, uppercaseGenerator), buffer: false});75+ const stream = useShortcutProperty ? [childProcess.stdout, childProcess.stderr][index - 1] : childProcess.stdio[index];76+ const [result] = await Promise.all([getStream(stream), childProcess]);77+ t.is(result, foobarUppercase);78+};79+80+test('Can use generators with childProcess.stdio[1]', testGeneratorOutputPipe, 1, false);81+test('Can use generators with childProcess.stdout', testGeneratorOutputPipe, 1, true);82+test('Can use generators with childProcess.stdio[2]', testGeneratorOutputPipe, 2, false);83+test('Can use generators with childProcess.stderr', testGeneratorOutputPipe, 2, true);84+test('Can use generators with childProcess.stdio[*] as output', testGeneratorOutputPipe, 3, false);85+86+const testGeneratorAll = async (t, reject) => {87+ const fixtureName = reject ? 'all.js' : 'all-fail.js';88+ const {all} = await execa(fixtureName, {all: true, reject, stdout: uppercaseGenerator, stderr: uppercaseGenerator});89+ t.is(all, 'STDOUT\nSTDERR');90+};91+92+test('Can use generators with result.all', testGeneratorAll, true);93+test('Can use generators with error.all', testGeneratorAll, false);94+95+test('Can use generators with input option', async t => {96+ const {stdout} = await execa('stdin-fd.js', ['0'], {stdin: uppercaseGenerator, input: foobarUint8Array});97+ t.is(stdout, foobarUppercase);98+});99+100+const syncGenerator = function * () {};101+102+const testSyncGenerator = (t, index) => {103+ t.throws(() => {104+ execa('empty.js', getStdio(index, syncGenerator));105+ }, {message: /asynchronous generator/});106+};107+108+test('Cannot use sync generators with stdin', testSyncGenerator, 0);109+test('Cannot use sync generators with stdout', testSyncGenerator, 1);110+test('Cannot use sync generators with stderr', testSyncGenerator, 2);111+test('Cannot use sync generators with stdio[*]', testSyncGenerator, 3);112+113+const testSyncMethods = (t, index) => {114+ t.throws(() => {115+ execaSync('empty.js', getStdio(index, uppercaseGenerator));116+ }, {message: /cannot be a generator/});117+};118+119+test('Cannot use generators with sync methods and stdin', testSyncMethods, 0);120+test('Cannot use generators with sync methods and stdout', testSyncMethods, 1);121+test('Cannot use generators with sync methods and stderr', testSyncMethods, 2);122+test('Cannot use generators with sync methods and stdio[*]', testSyncMethods, 3);123+124+const repeatHighWaterMark = 10;125+126+const writerGenerator = async function * (chunks) {127+ // eslint-disable-next-line no-unused-vars128+ for await (const chunk of chunks) {129+ for (let index = 0; index < getDefaultHighWaterMark() * repeatHighWaterMark; index += 1) {130+ yield '.';131+ }132+ }133+};134+135+const passThroughGenerator = async function * (chunks) {136+ for await (const chunk of chunks) {137+ yield `${chunk.length}`;138+ }139+};140+141+test('Stream respects highWaterMark', async t => {142+ const index = 1;143+ const {stdout} = await execa('noop-fd.js', [`${index}`], getStdio(index, [writerGenerator, passThroughGenerator]));144+ t.is(stdout, `${getDefaultHighWaterMark()}`.repeat(repeatHighWaterMark));145+});146+147+const typeofGenerator = async function * (chunks) {148+ for await (const chunk of chunks) {149+ yield Object.prototype.toString.call(chunk);150+ }151+};152+153+const testGeneratorFirstEncoding = async (t, input, encoding) => {154+ const childProcess = execa('stdin.js', {stdin: typeofGenerator, encoding});155+ childProcess.stdin.end(input);156+ const {stdout} = await childProcess;157+ const output = Buffer.from(stdout, encoding).toString();158+ t.is(output, encoding === 'buffer' ? '[object Uint8Array]' : '[object String]');159+};160+161+test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8');162+test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8');163+test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8');164+test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer');165+test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer');166+test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer');167+test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex');168+test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex');169+test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex');170+171+const outputGenerator = async function * (input, chunks) {172+ // eslint-disable-next-line no-unused-vars173+ for await (const chunk of chunks) {174+ yield input;175+ }176+};177+178+const testGeneratorNextEncoding = async (t, input, encoding) => {179+ const {stdout} = await execa('noop.js', ['other'], {stdout: [outputGenerator.bind(undefined, input), typeofGenerator], encoding});180+ const output = Buffer.from(stdout, encoding).toString();181+ t.is(output, encoding === 'buffer' ? '[object Uint8Array]' : '[object String]');182+};183+184+test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8');185+test('Next generator argument is string with default encoding, with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'utf8');186+test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8');187+test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer');188+test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'buffer');189+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer');190+test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex');191+test('Next generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'hex');192+test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex');193+194+const testGeneratorReturnType = async (t, input, encoding) => {195+ const {stdout} = await execa('noop.js', ['other'], {stdout: outputGenerator.bind(undefined, input), encoding});196+ const output = Buffer.from(stdout, encoding).toString();197+ t.is(output, foobarString);198+};199+200+test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8');201+test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8');202+test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer');203+test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer');204+test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex');205+test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex');206+207+const multibyteChar = '\u{1F984}';208+const multibyteString = `${multibyteChar}${multibyteChar}`;209+const multibyteUint8Array = new TextEncoder().encode(multibyteString);210+const breakingLength = multibyteUint8Array.length * 0.75;211+const brokenSymbol = '\uFFFD';212+213+const noopGenerator = async function * (chunks) {214+ for await (const chunk of chunks) {215+ yield chunk;216+ }217+};218+219+test('Generator handles multibyte characters with Uint8Array', async t => {220+ const childProcess = execa('stdin.js', {stdin: noopGenerator});221+ childProcess.stdin.write(multibyteUint8Array.slice(0, breakingLength));222+ await setTimeout(0);223+ childProcess.stdin.end(multibyteUint8Array.slice(breakingLength));224+ const {stdout} = await childProcess;225+ t.is(stdout, multibyteString);226+});227+228+test('Generator handles partial multibyte characters with Uint8Array', async t => {229+ const {stdout} = await execa('stdin.js', {stdin: [multibyteUint8Array.slice(0, breakingLength), noopGenerator]});230+ t.is(stdout, `${multibyteChar}${brokenSymbol}`);231+});232+233+// eslint-disable-next-line require-yield234+const noYieldGenerator = async function * (chunks) {235+ // eslint-disable-next-line no-empty, no-unused-vars236+ for await (const chunk of chunks) {}237+};238+239+test('Generator can filter by not calling yield', async t => {240+ const {stdout} = await execa('noop.js', {stdout: noYieldGenerator});241+ t.is(stdout, '');242+});243+244+const prefix = '> ';245+const suffix = ' <';246+247+const multipleYieldGenerator = async function * (chunks) {248+ for await (const chunk of chunks) {249+ yield prefix;250+ await setTimeout(0);251+ yield chunk;252+ await setTimeout(0);253+ yield suffix;254+ }255+};256+257+test('Generator can yield multiple times at different moments', async t => {258+ const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: multipleYieldGenerator});259+ t.is(stdout, `${prefix}${foobarString}${suffix}`);260+});261+262+const testInputFile = async (t, getOptions, reversed) => {263+ const filePath = tempfile();264+ await writeFile(filePath, foobarString);265+ const {stdin, ...options} = getOptions(filePath);266+ const reversedStdin = reversed ? stdin.reverse() : stdin;267+ const {stdout} = await execa('stdin-fd.js', ['0'], {...options, stdin: reversedStdin});268+ t.is(stdout, foobarUppercase);269+ await rm(filePath);270+};271+272+test('Can use generators with a file as input', testInputFile, filePath => ({stdin: [{file: filePath}, uppercaseGenerator]}), false);273+test('Can use generators with a file as input, reversed', testInputFile, filePath => ({stdin: [{file: filePath}, uppercaseGenerator]}), true);274+test('Can use generators with inputFile option', testInputFile, filePath => ({inputFile: filePath, stdin: uppercaseGenerator}), false);275+276+const testOutputFile = async (t, reversed) => {277+ const filePath = tempfile();278+ const stdoutOption = [uppercaseGenerator, {file: filePath}];279+ const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;280+ const {stdout} = await execa('noop-fd.js', ['1'], {stdout: reversedStdoutOption});281+ t.is(stdout, foobarUppercase);282+ t.is(await readFile(filePath, 'utf8'), foobarUppercase);283+ await rm(filePath);284+};285+286+test('Can use generators with a file as output', testOutputFile, false);287+test('Can use generators with a file as output, reversed', testOutputFile, true);288+289+test('Can use generators to a Writable stream', async t => {290+ const passThrough = new PassThrough();291+ const [{stdout}, streamOutput] = await Promise.all([292+ execa('noop-fd.js', ['1', foobarString], {stdout: [uppercaseGenerator, passThrough]}),293+ getStream(passThrough),294+ ]);295+ t.is(stdout, foobarUppercase);296+ t.is(streamOutput, foobarUppercase);297+});298+299+test('Can use generators from a Readable stream', async t => {300+ const passThrough = new PassThrough();301+ const childProcess = execa('stdin-fd.js', ['0'], {stdin: [passThrough, uppercaseGenerator]});302+ passThrough.end(foobarString);303+ const {stdout} = await childProcess;304+ t.is(stdout, foobarUppercase);305+});306+307+test('Can use generators with "inherit"', async t => {308+ const {stdout} = await execa('nested-inherit.js');309+ t.is(stdout, foobarUppercase);310+});311+312+const casedSuffix = 'k';313+314+const appendGenerator = async function * (chunks) {315+ for await (const chunk of chunks) {316+ yield `${chunk}${casedSuffix}`;317+ }318+};319+320+const testAppendInput = async (t, reversed) => {321+ const stdin = [foobarUint8Array, uppercaseGenerator, appendGenerator];322+ const reversedStdin = reversed ? stdin.reverse() : stdin;323+ const {stdout} = await execa('stdin-fd.js', ['0'], {stdin: reversedStdin});324+ const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;325+ t.is(stdout, `${foobarUppercase}${reversedSuffix}`);326+};327+328+test('Can use multiple generators as input', testAppendInput, false);329+test('Can use multiple generators as input, reversed', testAppendInput, true);330+331+const testAppendOutput = async (t, reversed) => {332+ const stdoutOption = [uppercaseGenerator, appendGenerator];333+ const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;334+ const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: reversedStdoutOption});335+ const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;336+ t.is(stdout, `${foobarUppercase}${reversedSuffix}`);337+};338+339+test('Can use multiple generators as output', testAppendOutput, false);340+test('Can use multiple generators as output, reversed', testAppendOutput, true);341+342+const maxBuffer = 10;343+344+test('Generators take "maxBuffer" into account', async t => {345+ const bigString = '.'.repeat(maxBuffer);346+ const {stdout} = await execa('noop.js', {maxBuffer, stdout: outputGenerator.bind(undefined, bigString)});347+ t.is(stdout, bigString);348+349+ await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: outputGenerator.bind(undefined, `${bigString}.`)}));350+});351+352+const timeoutGenerator = async function * (timeout, chunks) {353+ for await (const chunk of chunks) {354+ await setTimeout(timeout);355+ yield chunk;356+ }357+};358+359+test('Generators are awaited on success', async t => {360+ const {stdout} = await execa('noop-fd.js', ['1', foobarString], {maxBuffer, stdout: timeoutGenerator.bind(undefined, 1e3)});361+ t.is(stdout, foobarString);362+});363+364+// eslint-disable-next-line require-yield365+const throwingGenerator = async function * (chunks) {366+ // eslint-disable-next-line no-unreachable-loop367+ for await (const chunk of chunks) {368+ throw new Error(`Generator error ${chunk}`);369+ }370+};371+372+test('Generators errors make process fail', async t => {373+ await t.throwsAsync(374+ execa('noop-fd.js', ['1', foobarString], {stdout: throwingGenerator}),375+ {message: /Generator error foobar/},376+ );377+});378+379+// eslint-disable-next-line require-yield380+const errorHandlerGenerator = async function * (state, chunks) {381+ try {382+ // eslint-disable-next-line no-unused-vars383+ for await (const chunk of chunks) {384+ await setTimeout(1e8);385+ }386+ } catch (error) {387+ state.error = error;388+ }389+};390+391+test.serial('Process streams failures make generators throw', async t => {392+ const state = {};393+ const childProcess = execa('noop-fail.js', ['1'], {stdout: errorHandlerGenerator.bind(undefined, state)});394+ const error = new Error('test');395+ childProcess.stdout.emit('error', error);396+ const thrownError = await t.throwsAsync(childProcess);397+ t.is(error, thrownError);398+ await setTimeout(0);399+ t.is(state.error.code, 'ABORT_ERR');400+});modified:index.d.ts+17 added-8 removed
16 unmodified lines17 | 'overlapped'18 | 'ignore'19 | 'inherit';20 21-type CommonStdioOption =21+type CommonStdioOption<IsSync extends boolean = boolean> =22 | BaseStdioOption23 | 'ipc'24 | number25 | undefined26 | URL27- | {file: string};27+ | {file: string}28+ // TODO: Use either `Iterable<string>` or `Iterable<Uint8Array>` based on whether `encoding: 'buffer'` is used.29+ // See https://github.com/sindresorhus/execa/issues/69430+ | IfAsync<IsSync, ((chunks: Iterable<string | Uint8Array>) => AsyncGenerator<string | Uint8Array, void, void>)>;31 32 type InputStdioOption<IsSync extends boolean = boolean> =33 | Uint8Array34 | IfAsync<IsSync,6 unmodified lines41 | Writable42 | WritableStream>;43 44 export type StdinOption<IsSync extends boolean = boolean> =42- CommonStdioOption | InputStdioOption<IsSync>43- | Array<CommonStdioOption | InputStdioOption<IsSync>>;45+ CommonStdioOption<IsSync> | InputStdioOption<IsSync>46+ | Array<CommonStdioOption<IsSync> | InputStdioOption<IsSync>>;47 export type StdoutStderrOption<IsSync extends boolean = boolean> =45- CommonStdioOption | OutputStdioOption<IsSync>46- | Array<CommonStdioOption | OutputStdioOption<IsSync>>;48+ CommonStdioOption<IsSync> | OutputStdioOption<IsSync>49+ | Array<CommonStdioOption<IsSync> | OutputStdioOption<IsSync>>;50 export type StdioOption<IsSync extends boolean = boolean> =48- CommonStdioOption | InputStdioOption | OutputStdioOption<IsSync>49- | Array<CommonStdioOption | InputStdioOption | OutputStdioOption<IsSync>>;51+ CommonStdioOption<IsSync> | InputStdioOption | OutputStdioOption<IsSync>52+ | Array<CommonStdioOption<IsSync> | InputStdioOption | OutputStdioOption<IsSync>>;53 54 type StdioOptionsArray<IsSync extends boolean = boolean> = readonly [55 StdinOption<IsSync>,56 StdoutStderrOption<IsSync>,186 unmodified lines243 - an `Uint8Array`.244 245 This can be an [array of values](https://github.com/sindresorhus/execa#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.246 247+ This can also be an async generator function to transform the input. [Learn more.](https://github.com/sindresorhus/execa/tree/main/docs/transform.md)248+249 @default `inherit` with `$`, `pipe` otherwise250 */251 readonly stdin?: StdinOption<IsSync>;252 11 unmodified lines264 - a web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).265 266 This can be an [array of values](https://github.com/sindresorhus/execa#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.267 268+ This can also be an async generator function to transform the output. [Learn more.](https://github.com/sindresorhus/execa/tree/main/docs/transform.md)269+270 @default 'pipe'271 */272 readonly stdout?: StdoutStderrOption<IsSync>;273 11 unmodified lines285 - a web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).286 287 This can be an [array of values](https://github.com/sindresorhus/execa#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.288 289+ This can also be an async generator function to transform the output. [Learn more.](https://github.com/sindresorhus/execa/tree/main/docs/transform.md)290+291 @default 'pipe'292 */293 readonly stderr?: StdoutStderrOption<IsSync>;294 928 unmodified linesmodified:index.test-d.ts+75 added-11 removed
549 unmodified lines550 expectType<string | undefined>(noRejectsSyncResult.message);551 expectType<string | undefined>(noRejectsSyncResult.shortMessage);552 expectType<string | undefined>(noRejectsSyncResult.originalMessage);553 554-const stringGenerator = function * () {554+const emptyStringGenerator = function * () {555 yield '';556 };557 558 const binaryGenerator = function * () {9 unmodified lines568 };569 570 const fileUrl = new URL('file:///test');571 572+const stringOrUint8ArrayGenerator = async function * (chunks: Iterable<string | Uint8Array>) {573+ for await (const chunk of chunks) {574+ yield chunk;575+ }576+};577+578+const booleanGenerator = async function * (chunks: Iterable<boolean>) {579+ for await (const chunk of chunks) {580+ yield chunk;581+ }582+};583+584+const arrayGenerator = async function * (chunks: string[]) {585+ for await (const chunk of chunks) {586+ yield chunk;587+ }588+};589+590+const invalidReturnGenerator = async function * (chunks: Iterable<string>) {591+ for await (const chunk of chunks) {592+ yield chunk;593+ }594+595+ return false;596+};597+598+const syncGenerator = function * (chunks: Iterable<string>) {599+ for (const chunk of chunks) {600+ yield chunk;601+ }602+603+ return false;604+};605+606 expectAssignable<Options>({cleanup: false});607 expectNotAssignable<SyncOptions>({cleanup: false});608 expectAssignable<SyncOptions>({preferLocal: false});609 65 unmodified lines675 expectError(execa('unicorns', {stdin: [new WritableStream()]}));676 expectError(execaSync('unicorns', {stdin: [new WritableStream()]}));677 execa('unicorns', {stdin: new Uint8Array()});678 execaSync('unicorns', {stdin: new Uint8Array()});645-execa('unicorns', {stdin: stringGenerator()});646-expectError(execaSync('unicorns', {stdin: stringGenerator()}));647-execa('unicorns', {stdin: [stringGenerator()]});648-expectError(execaSync('unicorns', {stdin: [stringGenerator()]}));679+execa('unicorns', {stdin: emptyStringGenerator()});680+expectError(execaSync('unicorns', {stdin: emptyStringGenerator()}));681+execa('unicorns', {stdin: [emptyStringGenerator()]});682+expectError(execaSync('unicorns', {stdin: [emptyStringGenerator()]}));683 execa('unicorns', {stdin: binaryGenerator()});684 expectError(execaSync('unicorns', {stdin: binaryGenerator()}));685 execa('unicorns', {stdin: [binaryGenerator()]});686 expectError(execaSync('unicorns', {stdin: [binaryGenerator()]}));16 unmodified lines703 execa('unicorns', {stdin: 1});704 execaSync('unicorns', {stdin: 1});705 execa('unicorns', {stdin: [1]});706 execaSync('unicorns', {stdin: [1]});707+execa('unicorns', {stdin: stringOrUint8ArrayGenerator});708+expectError(execaSync('unicorns', {stdin: stringOrUint8ArrayGenerator}));709+execa('unicorns', {stdin: [stringOrUint8ArrayGenerator]});710+expectError(execaSync('unicorns', {stdin: [stringOrUint8ArrayGenerator]}));711+expectError(execa('unicorns', {stdin: booleanGenerator}));712+expectError(execa('unicorns', {stdin: arrayGenerator}));713+expectError(execa('unicorns', {stdin: invalidReturnGenerator}));714+expectError(execa('unicorns', {stdin: syncGenerator}));715 execa('unicorns', {stdin: undefined});716 execaSync('unicorns', {stdin: undefined});717 execa('unicorns', {stdin: [undefined]});718 execaSync('unicorns', {stdin: [undefined]});50 unmodified lines769 execa('unicorns', {stdout: 1});770 execaSync('unicorns', {stdout: 1});771 execa('unicorns', {stdout: [1]});772 execaSync('unicorns', {stdout: [1]});773+execa('unicorns', {stdout: stringOrUint8ArrayGenerator});774+expectError(execaSync('unicorns', {stdout: stringOrUint8ArrayGenerator}));775+execa('unicorns', {stdout: [stringOrUint8ArrayGenerator]});776+expectError(execaSync('unicorns', {stdout: [stringOrUint8ArrayGenerator]}));777+expectError(execa('unicorns', {stdout: booleanGenerator}));778+expectError(execa('unicorns', {stdout: arrayGenerator}));779+expectError(execa('unicorns', {stdout: invalidReturnGenerator}));780+expectError(execa('unicorns', {stdout: syncGenerator}));781 execa('unicorns', {stdout: undefined});782 execaSync('unicorns', {stdout: undefined});783 execa('unicorns', {stdout: [undefined]});784 execaSync('unicorns', {stdout: [undefined]});50 unmodified lines835 execa('unicorns', {stderr: 1});836 execaSync('unicorns', {stderr: 1});837 execa('unicorns', {stderr: [1]});838 execaSync('unicorns', {stderr: [1]});839+execa('unicorns', {stderr: stringOrUint8ArrayGenerator});840+expectError(execaSync('unicorns', {stderr: stringOrUint8ArrayGenerator}));841+execa('unicorns', {stderr: [stringOrUint8ArrayGenerator]});842+expectError(execaSync('unicorns', {stderr: [stringOrUint8ArrayGenerator]}));843+expectError(execa('unicorns', {stderr: booleanGenerator}));844+expectError(execa('unicorns', {stderr: arrayGenerator}));845+expectError(execa('unicorns', {stderr: invalidReturnGenerator}));846+expectError(execa('unicorns', {stderr: syncGenerator}));847 execa('unicorns', {stderr: undefined});848 execaSync('unicorns', {stderr: undefined});849 execa('unicorns', {stderr: [undefined]});850 execaSync('unicorns', {stderr: [undefined]});28 unmodified lines879 expectError(execa('unicorns', {stdio: 'ipc'}));880 expectError(execaSync('unicorns', {stdio: 'ipc'}));881 expectError(execa('unicorns', {stdio: 1}));882 expectError(execaSync('unicorns', {stdio: 1}));883+expectError(execa('unicorns', {stdio: stringOrUint8ArrayGenerator}));884+expectError(execaSync('unicorns', {stdio: stringOrUint8ArrayGenerator}));885 expectError(execa('unicorns', {stdio: fileUrl}));886 expectError(execaSync('unicorns', {stdio: fileUrl}));887 expectError(execa('unicorns', {stdio: {file: './test'}}));888 expectError(execaSync('unicorns', {stdio: {file: './test'}}));4 unmodified lines893 expectError(execa('unicorns', {stdio: new WritableStream()}));894 expectError(execaSync('unicorns', {stdio: new WritableStream()}));895 expectError(execa('unicorns', {stdio: new ReadableStream()}));896 expectError(execaSync('unicorns', {stdio: new ReadableStream()}));837-expectError(execa('unicorns', {stdio: stringGenerator()}));838-expectError(execaSync('unicorns', {stdio: stringGenerator()}));897+expectError(execa('unicorns', {stdio: emptyStringGenerator()}));898+expectError(execaSync('unicorns', {stdio: emptyStringGenerator()}));899 expectError(execa('unicorns', {stdio: asyncStringGenerator()}));900 expectError(execaSync('unicorns', {stdio: asyncStringGenerator()}));901 expectError(execa('unicorns', {stdio: ['pipe', 'pipe']}));902 expectError(execaSync('unicorns', {stdio: ['pipe', 'pipe']}));29 unmodified lines932 'ignore',933 'inherit',934 process.stdin,935 1,936+ stringOrUint8ArrayGenerator,937 undefined,938 fileUrl,939 {file: './test'},940 new Writable(),941 new Readable(),942 new WritableStream(),943 new ReadableStream(),944 new Uint8Array(),884- stringGenerator(),945+ emptyStringGenerator(),946 asyncStringGenerator(),947 ],948 });949 execaSync('unicorns', {10 unmodified lines960 {file: './test'},961 new Uint8Array(),962 ],963 });964+expectError(execaSync('unicorns', {stdio: [stringOrUint8ArrayGenerator]}));965 expectError(execaSync('unicorns', {stdio: [new Writable()]}));966 expectError(execaSync('unicorns', {stdio: [new Readable()]}));967 expectError(execaSync('unicorns', {stdio: [new WritableStream()]}));968 expectError(execaSync('unicorns', {stdio: [new ReadableStream()]}));907-expectError(execaSync('unicorns', {stdio: [stringGenerator()]}));969+expectError(execaSync('unicorns', {stdio: [emptyStringGenerator()]}));970 expectError(execaSync('unicorns', {stdio: [asyncStringGenerator()]}));971 execa('unicorns', {972 stdio: [973 ['pipe'],3 unmodified lines977 ['ignore'],978 ['inherit'],979 [process.stdin],980 [1],981+ [stringOrUint8ArrayGenerator],982 [undefined],983 [fileUrl],984 [{file: './test'}],985 [new Writable()],986 [new Readable()],987 [new WritableStream()],988 [new ReadableStream()],989 [new Uint8Array()],927- [stringGenerator()],990+ [emptyStringGenerator()],991 [asyncStringGenerator()],992 ],993 });994 execaSync('unicorns', {11 unmodified lines1006 [{file: './test'}],1007 [new Uint8Array()],1008 ],1009 });1010+expectError(execaSync('unicorns', {stdio: [[stringOrUint8ArrayGenerator]]}));1011 expectError(execaSync('unicorns', {stdio: [[new Writable()]]}));1012 expectError(execaSync('unicorns', {stdio: [[new Readable()]]}));1013 expectError(execaSync('unicorns', {stdio: [[new WritableStream()]]}));1014 expectError(execaSync('unicorns', {stdio: [[new ReadableStream()]]}));951-expectError(execaSync('unicorns', {stdio: [[stringGenerator()]]}));1015+expectError(execaSync('unicorns', {stdio: [[emptyStringGenerator()]]}));1016 expectError(execaSync('unicorns', {stdio: [[asyncStringGenerator()]]}));1017 execa('unicorns', {serialization: 'advanced'});1018 expectError(execaSync('unicorns', {serialization: 'advanced'}));1019 execa('unicorns', {detached: true});138 unmodified linesmodified:readme.md+10 added-4 removed
580 unmodified lines581 See also the [`input`](#input) and [`stdin`](#stdin) options.582 583 #### stdin584 585-Type: `string | number | stream.Readable | ReadableStream | URL | Uint8Array | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array>` (or a tuple of those types)\585+Type: `string | number | stream.Readable | ReadableStream | URL | Uint8Array | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array> | AsyncGeneratorFunction<string | Uint8Array>` (or a tuple of those types)\586 Default: `inherit` with [`$`](#command), `pipe` otherwise587 588 [How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard input. This can be:589 - `'pipe'`: Sets [`childProcess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin) stream.10 unmodified lines600 - an `Uint8Array`.601 602 This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.603 604+This can also be an async generator function to transform the input. [Learn more.](docs/transform.md)605+606 #### stdout607 606-Type: `string | number | stream.Writable | WritableStream | URL` (or a tuple of those types)\608+Type: `string | number | stream.Writable | WritableStream | URL | AsyncGeneratorFunction<string | Uint8Array>` (or a tuple of those types)\609 Default: `pipe`610 611 [How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard output. This can be:612 - `'pipe'`: Sets [`childProcessResult.stdout`](#stdout) (as a string or `Uint8Array`) and [`childProcess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout) (as a stream).8 unmodified lines621 - a web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).622 623 This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.624 625+This can also be an async generator function to transform the output. [Learn more.](docs/transform.md)626+627 #### stderr628 625-Type: `string | number | stream.Writable | WritableStream | URL` (or a tuple of those types)`\629+Type: `string | number | stream.Writable | WritableStream | URL | AsyncGeneratorFunction<string | Uint8Array>` (or a tuple of those types)`\630 Default: `pipe`631 632 [How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard error. This can be:633 - `'pipe'`: Sets [`childProcessResult.stderr`](#stderr) (as a string or `Uint8Array`) and [`childProcess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr) (as a stream).8 unmodified lines642 - a web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).643 644 This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.645 646+This can also be an async generator function to transform the output. [Learn more.](docs/transform.md)647+648 #### stdio649 644-Type: `string | Array<string | number | stream.Readable | stream.Writable | ReadableStream | WritableStream | URL | Uint8Array | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array>>` (or a tuple of those types)\650+Type: `string | Array<string | number | stream.Readable | stream.Writable | ReadableStream | WritableStream | URL | Uint8Array | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array> | AsyncGeneratorFunction<string | Uint8Array>>` (or a tuple of those types)\651 Default: `pipe`652 653 Like the [`stdin`](#stdin), [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options but for all file descriptors at once. For example, `{stdio: ['ignore', 'pipe', 'pipe']}` is the same as `{stdin: 'ignore', stdout: 'pipe', stderr: 'pipe'}`.654 289 unmodified lines