Allow any type with transforms (#709)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent f8dffc1 · Browse files · 29 files·+1107 added−418 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
29 files+1107 added−418 removed
- tests:+589 added−243 removed
- other:+518 added−175 removed
Provenance
- Commit
ed8b2ce- Tree
b2781fa- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
f8dffc1
29 files changed+1107 added−418 removed
modified:docs/transform.md+30 added
54 unmodified lines55565758596061626364656667686970717273747576777879808182838485868788899091929 unmodified lines54 unmodified linesThis is more efficient and recommended if the data is either: - Binary: Which does not have lines. - Text: But the transform works even if a line or word is split across multiple chunks.
## Object mode
By default, `stdout` and `stderr`'s transforms must return a string or an `Uint8Array`. However, if a `{transform, objectMode: true}` plain object is passed, any type can be returned instead. The process' [`stdout`](../readme.md#stdout)/[`stderr`](../readme.md#stderr) will be an array of values.
```jsconst transform = async function * (lines) { for await (const line of lines) { yield JSON.parse(line) }}
const {stdout} = await execa('./jsonlines-output.js', {stdout: {transform, objectMode: true}});for (const data of stdout) { console.log(stdout) // {...}}```
`stdin` can also use `objectMode: true`.
```jsconst transform = async function * (lines) { for await (const line of lines) { yield JSON.stringify(line) }}
const input = [{event: 'example'}, {event: 'otherExample'}]await execa('./jsonlines-input.js', {stdin: [input, {transform, objectMode: true}]});```
## 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`.
9 unmodified linesmodified:lib/stdio/async.js+2 added-7 removed
37 unmodified lines3839404142434445424344454946474849502 unmodified lines535455566061575859607 unmodified lines37 unmodified linesexport const pipeOutputAsync = (spawned, stdioStreamsGroups) => { const inputStreamsGroups = {};
for (const stdioStreams of stdioStreamsGroups) { const generatorStreams = sortGeneratorStreams(stdioStreams.filter(({type}) => type === 'generator')); const nonGeneratorStreams = stdioStreams.filter(({type}) => type !== 'generator');
for (const generatorStream of generatorStreams) { for (const generatorStream of stdioStreams.filter(({type}) => type === 'generator')) { pipeGenerator(spawned, generatorStream); }
for (const nonGeneratorStream of nonGeneratorStreams) { for (const nonGeneratorStream of stdioStreams.filter(({type}) => type !== 'generator')) { pipeStdioOption(spawned, nonGeneratorStream, inputStreamsGroups); } }
2 unmodified lines 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/duplex.js+10 added-4 removed
9 unmodified lines10 Those convert the chunk type from `Buffer` to `string | Uint8Array` depending on the encoding option.11 - This new iterable is transformed again to another one, this time by applying the user-supplied generator.12 - Finally, `Readable.from()` is used to convert this final iterable to a `Readable` stream.13 */14-export const generatorsToDuplex = (generators, {objectMode}) => {15- const highWaterMark = getDefaultHighWaterMark(objectMode);16- const passThrough = new PassThrough({objectMode, highWaterMark, destroy: destroyPassThrough});14+export const generatorsToDuplex = (generators, {writableObjectMode, readableObjectMode}) => {15+ const passThrough = new PassThrough({16+ objectMode: writableObjectMode,17+ highWaterMark: getDefaultHighWaterMark(writableObjectMode),18+ destroy: destroyPassThrough,19+ });20 let iterable = passThrough.iterator();21 22 for (const generator of generators) {23 iterable = generator(iterable);24 }25 23- const readableStream = Readable.from(iterable, {objectMode, highWaterMark});26+ const readableStream = Readable.from(iterable, {27+ objectMode: readableObjectMode,28+ highWaterMark: getDefaultHighWaterMark(readableObjectMode),29+ });30 const duplexStream = Duplex.from({writable: passThrough, readable: readableStream});31 return duplexStream;32 };33 16 unmodified linesmodified:lib/stdio/encoding.js+16 added-3 removed
1 import {StringDecoder} from 'node:string_decoder';2+import {Buffer} from 'node:buffer';3+import {isUint8Array} from './utils.js';4 5 // Apply the `encoding` option using an implicit generator.6 // This encodes the final output of `stdout`/`stderr`.7 export const handleStreamsEncoding = (stdioStreams, {encoding}, isSync) => {1 unmodified line9 return stdioStreams.map(stdioStream => ({...stdioStream, encoding}));10 }11 12 const transform = encodingEndGenerator.bind(undefined, encoding);13+ const objectMode = stdioStreams.findLast(({type}) => type === 'generator')?.value.readableObjectMode === true;14 return [15 ...stdioStreams,16 {17 ...stdioStreams[0],18 type: 'generator',16- value: {transform, binary: true},19+ value: {transform, binary: true, readableObjectMode: objectMode, writableObjectMode: objectMode},20 encoding: 'buffer',21 },22 ];23 };30 unmodified lines54 ? encodingStartBufferGenerator55 : encodingStartStringGenerator;56 57 const encodingStartBufferGenerator = async function * (chunks) {58+ const textEncoder = new TextEncoder();59+60 for await (const chunk of chunks) {61+ if (Buffer.isBuffer(chunk)) {56- yield new Uint8Array(chunk);62+ yield new Uint8Array(chunk);63+ } else if (typeof chunk === 'string') {64+ yield textEncoder.encode(chunk);65+ } else {66+ yield chunk;67+ }68 }69 };70 71 const encodingStartStringGenerator = async function * (chunks) {72 const textDecoder = new TextDecoder();73 74 for await (const chunk of chunks) {64- yield textDecoder.decode(chunk, {stream: true});75+ yield Buffer.isBuffer(chunk) || isUint8Array(chunk)76+ ? textDecoder.decode(chunk, {stream: true})77+ : chunk;78 }79 80 const lastChunk = textDecoder.decode();81 if (lastChunk !== '') {3 unmodified linesmodified:lib/stdio/generator.js+68 added-5 removed
1 import {generatorsToDuplex} from './duplex.js';2 import {getEncodingStartGenerator} from './encoding.js';3 import {getLinesGenerator} from './lines.js';4 import {isGeneratorOptions} from './type.js';5+import {isBinary} from './utils.js';6 7+export const normalizeGenerators = stdioStreams => {8+ const nonGenerators = stdioStreams.filter(({type}) => type !== 'generator');9+ const generators = stdioStreams.filter(({type}) => type === 'generator');10+11+ const newGenerators = Array.from({length: generators.length});12+13+ for (const [index, stdioStream] of Object.entries(generators)) {14+ newGenerators[index] = normalizeGenerator(stdioStream, Number(index), newGenerators);15+ }16+17+ return [...nonGenerators, ...sortGenerators(newGenerators)];18+};19+20+const normalizeGenerator = ({value, ...stdioStream}, index, newGenerators) => {21+ const {transform, binary = false, objectMode = false} = isGeneratorOptions(value) ? value : {transform: value};22+ const objectModes = stdioStream.direction === 'output'23+ ? getOutputObjectModes(objectMode, index, newGenerators)24+ : getInputObjectModes(objectMode, index, newGenerators);25+ return {...stdioStream, value: {transform, binary, ...objectModes}};26+};27+28 /*29+`objectMode` determines the return value's type, i.e. the `readableObjectMode`.30+The chunk argument's type is based on the previous generator's return value, i.e. the `writableObjectMode` is based on the previous `readableObjectMode`.31+The last input's generator is read by `childProcess.stdin` which:32+- should not be in `objectMode` for performance reasons.33+- can only be strings, Buffers and Uint8Arrays.34+Therefore its `readableObjectMode` must be `false`.35+The same applies to the first output's generator's `writableObjectMode`.36+*/37+const getOutputObjectModes = (objectMode, index, newGenerators) => {38+ const writableObjectMode = index !== 0 && newGenerators[index - 1].value.readableObjectMode;39+ const readableObjectMode = objectMode;40+ return {writableObjectMode, readableObjectMode};41+};42+43+const getInputObjectModes = (objectMode, index, newGenerators) => {44+ const writableObjectMode = index === 045+ ? objectMode46+ : newGenerators[index - 1].value.readableObjectMode;47+ const readableObjectMode = index !== newGenerators.length - 1 && objectMode;48+ return {writableObjectMode, readableObjectMode};49+};50+51+const sortGenerators = newGenerators => newGenerators[0]?.direction === 'input' ? newGenerators.reverse() : newGenerators;52+53+/*54 Generators can be used to transform/filter standard streams.55 56 Generators have a simple syntax, yet allows all of the following:57 - Sharing state between chunks, by using logic before the `for` loop5 unmodified lines63 Therefore, there is no need to allow Node.js or web transform streams.64 65 The `highWaterMark` is kept as the default value, since this is what `childProcess.std*` uses.66 20-We ensure `objectMode` is `false` for better buffering.21-67 Chunks are currently processed serially. We could add a `concurrency` option to parallelize in the future.68 */24-export const generatorToDuplexStream = ({value, encoding}) => {25- const {transform, binary} = isGeneratorOptions(value) ? value : {transform: value};69+export const generatorToDuplexStream = ({70+ value: {transform, binary, writableObjectMode, readableObjectMode},71+ encoding,72+ optionName,73+}) => {74 const generators = [75 getEncodingStartGenerator(encoding),76 getLinesGenerator(encoding, binary),77 transform,78+ getValidateTransformReturn(readableObjectMode, optionName),79 ].filter(Boolean);31- const duplexStream = generatorsToDuplex(generators, {objectMode: false});80+ const duplexStream = generatorsToDuplex(generators, {writableObjectMode, readableObjectMode});81 return {value: duplexStream};82 };83 84+const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode85+ ? undefined86+ : validateTransformReturn.bind(undefined, optionName);87+88+const validateTransformReturn = async function * (optionName, chunks) {89+ for await (const chunk of chunks) {90+ if (typeof chunk !== 'string' && !isBinary(chunk)) {91+ throw new Error(`The \`${optionName}\` option's function must return a string or an Uint8Array, not ${typeof chunk}.`);92+ }93+94+ yield chunk;95+ }96+};97+98 // `childProcess.stdin|stdout|stderr|stdio` is directly mutated.99 export const pipeGenerator = (spawned, {value, direction, index}) => {100 if (direction === 'output') {101 spawned.stdio[index].pipe(value);13 unmodified linesmodified:lib/stdio/handle.js+2 added
2 unmodified lines3 import {normalizeStdio} from './normalize.js';4 import {handleNativeStream} from './native.js';5 import {handleInputOptions} from './input.js';6 import {handleStreamsEncoding} from './encoding.js';7+import {normalizeGenerators} from './generator.js';8 9 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode10 export const handleInput = (addProperties, options, isSync) => {11 const stdio = normalizeStdio(options);12 const [stdinStreams, ...otherStreamsGroups] = stdio.map((stdioOption, index) => getStdioStreams(stdioOption, index));13 const stdioStreamsGroups = [[...stdinStreams, ...handleInputOptions(options)], ...otherStreamsGroups]14 .map(stdioStreams => validateStreams(stdioStreams))15 .map(stdioStreams => addStreamDirection(stdioStreams))16+ .map(stdioStreams => normalizeGenerators(stdioStreams))17 .map(stdioStreams => handleStreamsEncoding(stdioStreams, options, isSync))18 .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties));19 options.stdio = transformStdio(stdioStreamsGroups);20 return stdioStreamsGroups;87 unmodified linesmodified:lib/stdio/lines.js+23 added-3 removed
1+import {isUint8Array} from './utils.js';2+3 // Split chunks line-wise4 export const getLinesGenerator = (encoding, binary) => {5 if (binary) {6 return;2 unmodified lines9 return encoding === 'buffer' ? linesUint8ArrayGenerator : linesStringGenerator;10 };11 12 const linesUint8ArrayGenerator = async function * (chunks) {11- yield * linesGenerator(chunks, new Uint8Array(0), 0x0A, concatUint8Array);13+ yield * linesGenerator({14+ chunks,15+ emptyValue: new Uint8Array(0),16+ newline: 0x0A,17+ concat: concatUint8Array,18+ isValidType: isUint8Array,19+ });20 };21 22 const concatUint8Array = (firstChunk, secondChunk) => {23 const chunk = new Uint8Array(firstChunk.length + secondChunk.length);2 unmodified lines26 return chunk;27 };28 29 const linesStringGenerator = async function * (chunks) {22- yield * linesGenerator(chunks, '', '\n', concatString);30+ yield * linesGenerator({31+ chunks,32+ emptyValue: '',33+ newline: '\n',34+ concat: concatString,35+ isValidType: isString,36+ });37 };38 39 const concatString = (firstChunk, secondChunk) => `${firstChunk}${secondChunk}`;40+const isString = chunk => typeof chunk === 'string';41 42 // This imperative logic is much faster than using `String.split()` and uses very low memory.43 // Also, it allows sharing it with `Uint8Array`.29-const linesGenerator = async function * (chunks, emptyValue, newline, concat) {44+const linesGenerator = async function * ({chunks, emptyValue, newline, concat, isValidType}) {45 let previousChunks = emptyValue;46 47 for await (const chunk of chunks) {48+ if (!isValidType(chunk)) {49+ yield chunk;50+ continue;51+ }52+53 let start = -1;54 55 for (let end = 0; end < chunk.length; end += 1) {56 if (chunk[end] === newline) {21 unmodified linesmodified:lib/stdio/sync.js+2 added-2 removed
1 import {readFileSync, writeFileSync} from 'node:fs';2 import {handleInput} from './handle.js';3 import {TYPE_TO_MESSAGE} from './type.js';4-import {bufferToUint8Array} from './utils.js';4+import {bufferToUint8Array, binaryToString} from './utils.js';5 6 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode7 export const handleInputSync = options => {8 const stdioStreamsGroups = handleInput(addPropertiesSync, options, true);34 unmodified lines43 ? inputs[0].value44 : inputs.map(stdioStream => serializeInput(stdioStream)).join('');45 };46 47-const serializeInput = ({type, value}) => type === 'string' ? value : new TextDecoder().decode(value);47+const serializeInput = ({type, value}) => type === 'string' ? value : binaryToString(value);48 49 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in sync mode50 export const pipeOutputSync = (stdioStreamsGroups, result) => {51 if (result.output === null) {19 unmodified linesmodified:lib/stdio/type.js+9 added-5 removed
40 unmodified lines41 42 return 'native';43 };44 45-const getGeneratorObjectType = ({transform, binary}, optionName) => {45+const getGeneratorObjectType = ({transform, binary, objectMode}, optionName) => {46 if (!isAsyncGenerator(transform)) {47 throw new TypeError(`The \`${optionName}.transform\` option must use an asynchronous generator.`);48 }49 50- if (binary !== undefined && typeof binary !== 'boolean') {51- throw new TypeError(`The \`${optionName}.binary\` option must use a boolean.`);52- }50+ checkBooleanOption(binary, `${optionName}.binary`);51+ checkBooleanOption(objectMode, `${optionName}.objectMode`);52 53 return 'generator';54 };55 56+const checkBooleanOption = (value, optionName) => {57+ if (value !== undefined && typeof value !== 'boolean') {58+ throw new TypeError(`The \`${optionName}\` option must use a boolean.`);59+ }60+};61+62 const isAsyncGenerator = stdioOption => Object.prototype.toString.call(stdioOption) === '[object AsyncGeneratorFunction]';63 const isSyncGenerator = stdioOption => Object.prototype.toString.call(stdioOption) === '[object GeneratorFunction]';64 export const isGeneratorOptions = stdioOption => typeof stdioOption === 'object'65 && stdioOption !== null16 unmodified lines82 const isWebStream = stdioOption => isReadableStream(stdioOption) || isWritableStream(stdioOption);83 84 const isIterableObject = stdioOption => typeof stdioOption === 'object'85 && stdioOption !== null81- && !Array.isArray(stdioOption)86 && (typeof stdioOption[Symbol.asyncIterator] === 'function' || typeof stdioOption[Symbol.iterator] === 'function');87 88 // Convert types to human-friendly strings for error messages89 export const TYPE_TO_MESSAGE = {10 unmodified linesmodified:lib/stdio/utils.js+4 added
1 unmodified line2 3 export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);4 5 export const isUint8Array = value => Object.prototype.toString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);6+export const isBinary = value => isUint8Array(value) || Buffer.isBuffer(value);7+8+const textDecoder = new TextDecoder();9+export const binaryToString = uint8ArrayOrBuffer => textDecoder.decode(uint8ArrayOrBuffer);modified:lib/command.js+3 added-2 removed
1 import {ChildProcess} from 'node:child_process';2+import {isBinary, binaryToString} from './stdio/utils.js';3 4 const normalizeArgs = (file, args = []) => {5 if (!Array.isArray(args)) {6 return [file];57 unmodified lines64 if (typeOfStdout === 'string') {65 return expression.stdout;66 }67 67- if (ArrayBuffer.isView(expression.stdout)) {68- return new TextDecoder().decode(expression.stdout);68+ if (isBinary(expression.stdout)) {69+ return binaryToString(expression.stdout);70 }71 72 throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);73 }46 unmodified linesmodified:lib/error.js+10 added-6 removed
1 import process from 'node:process';2 import {signalsByName} from 'human-signals';3 import stripFinalNewline from 'strip-final-newline';4-import {isUint8Array} from './stdio/utils.js';4+import {isBinary, binaryToString} from './stdio/utils.js';5 6 const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {7 if (timedOut) {8 return `timed out after ${timeout} milliseconds`;17 unmodified lines26 27 return 'failed';28 };29 30+const serializeMessagePart = messagePart => Array.isArray(messagePart)31+ ? messagePart.map(messageItem => serializeMessageItem(messageItem)).join('')32+ : serializeMessageItem(messagePart);33+30-const serializeMessagePart = messagePart => {31- if (typeof messagePart === 'string') {32- return messagePart;34+const serializeMessageItem = messageItem => {35+ if (typeof messageItem === 'string') {36+ return messageItem;37 }38 35- if (isUint8Array(messagePart)) {36- return new TextDecoder().decode(messagePart);39+ if (isBinary(messageItem)) {40+ return binaryToString(messageItem);41 }42 43 return '';44 };64 unmodified linesmodified:lib/stream.js+37 added-7 removed
1 import {once} from 'node:events';2 import {finished} from 'node:stream/promises';3-import getStream, {getStreamAsArrayBuffer} from 'get-stream';3+import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';4 import mergeStreams from '@sindresorhus/merge-streams';5 import {throwOnTimeout, cleanupOnExit} from './kill.js';6 import {STANDARD_STREAMS} from './stdio/native.js';7+import {generatorToDuplexStream} from './stdio/generator.js';8 9 // `all` interleaves `stdout` and `stderr`10 export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)11 ? mergeStreams([stdout, stderr].filter(Boolean))6 unmodified lines18 const getBufferedData = async (streamPromise, encoding) => {19 try {20 return await streamPromise;21 } catch (error) {21- return error.bufferedData === undefined ? undefined : applyEncoding(error.bufferedData, encoding);22+ return error.bufferedData === undefined || Array.isArray(error.bufferedData)23+ ? error.bufferedData24+ : applyEncoding(error.bufferedData, encoding);25 }26 };27 25-const getStdioPromise = ({stream, index, stdioStreamsGroups, encoding, buffer, maxBuffer}) => stdioStreamsGroups[index]?.[0]?.direction === 'output'26- ? getStreamPromise(stream, {encoding, buffer, maxBuffer})28+const getStdioPromise = ({stream, stdioStreams, encoding, buffer, maxBuffer}) => stdioStreams[0].direction === 'output'29+ ? getStreamPromise({stream, encoding, buffer, maxBuffer, objectMode: stream?.readableObjectMode})30 : undefined;31 29-const getStreamPromise = async (stream, {encoding, buffer, maxBuffer}) => {32+const getAllPromise = ({spawned, encoding, buffer, maxBuffer}) => {33+ const stream = getAllStream(spawned, encoding);34+ const objectMode = spawned.stdout?.readableObjectMode || spawned.stderr?.readableObjectMode;35+ return getStreamPromise({stream, encoding, buffer, maxBuffer, objectMode});36+};37+38+// When `childProcess.stdout` is in objectMode but not `childProcess.stderr` (or the opposite), we need to use both:39+// - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk40+// - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array41+// We do this by emulating the Buffer -> string|Uint8Array conversion performed by `get-stream` with our own, which is identical.42+const getAllStream = ({all, stdout, stderr}, encoding) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode43+ ? all.pipe(generatorToDuplexStream({value: allStreamGenerator, encoding}).value)44+ : all;45+46+const allStreamGenerator = {47+ async * transform(chunks) {48+ yield * chunks;49+ },50+ binary: true,51+ writableObjectMode: true,52+ readableObjectMode: true,53+};54+55+const getStreamPromise = async ({stream, encoding, buffer, maxBuffer, objectMode}) => {56 if (!stream || !buffer) {57 return;58 }59 60+ if (objectMode) {61+ return getStreamAsArray(stream, {maxBuffer});62+ }63+64 const contents = encoding === 'buffer'65 ? await getStreamAsArrayBuffer(stream, {maxBuffer})66 : await getStream(stream, {maxBuffer});67 return applyEncoding(contents, encoding);51 unmodified lines119 const finalizers = [];120 cleanupOnExit(spawned, cleanup, detached, finalizers);121 const customStreams = getCustomStreams(stdioStreamsGroups);122 93- const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, index, stdioStreamsGroups, encoding, buffer, maxBuffer}));94- const allPromise = getStreamPromise(spawned.all, {encoding, buffer, maxBuffer: maxBuffer * 2});123+ const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, stdioStreams: stdioStreamsGroups[index], encoding, buffer, maxBuffer}));124+ const allPromise = getAllPromise({spawned, encoding, buffer, maxBuffer: maxBuffer * 2});125 126 try {127 return await Promise.race([128 Promise.all([24 unmodified linesmodified:test/helpers/generator.js+33 added-28 removed
1-import {setTimeout} from 'node:timers/promises';1+import {foobarObject} from './input.js';2 3-export const stringGenerator = function * () {4- yield * ['foo', 'bar'];5-};3+export const noopGenerator = objectMode => ({4+ async * transform(lines) {5+ yield * lines;6+ },7+ objectMode,8+});9 7-const textEncoder = new TextEncoder();8-const binaryFoo = textEncoder.encode('foo');9-const binaryBar = textEncoder.encode('bar');10-11-export const binaryGenerator = function * () {12- yield * [binaryFoo, binaryBar];10+export const serializeGenerator = {11+ async * transform(objects) {12+ for await (const object of objects) {13+ yield JSON.stringify(object);14+ }15+ },16+ objectMode: true,17 };18 15-export const asyncGenerator = async function * () {16- await setTimeout(0);17- yield * ['foo', 'bar'];18-};19+export const getOutputsGenerator = (inputs, objectMode) => ({20+ async * transform(lines) {21+ // eslint-disable-next-line no-unused-vars22+ for await (const line of lines) {23+ yield * inputs;24+ }25+ },26+ objectMode,27+});28 20-// eslint-disable-next-line require-yield21-export const throwingGenerator = function * () {22- throw new Error('generator error');23-};29+export const getOutputGenerator = (input, objectMode) => ({30+ async * transform(lines) {31+ // eslint-disable-next-line no-unused-vars32+ for await (const line of lines) {33+ yield input;34+ }35+ },36+ objectMode,37+});38 25-export const infiniteGenerator = () => {26- const controller = new AbortController();27-28- const generator = async function * () {29- yield 'foo';30- await setTimeout(1e7, undefined, {signal: controller.signal});31- };32-33- return {iterable: generator(), abort: controller.abort.bind(controller)};34-};39+export const outputObjectGenerator = getOutputGenerator(foobarObject, true);added:test/helpers/input.js+12 added
1+import {Buffer} from 'node:buffer';2+3+const textEncoder = new TextEncoder();4+5+export const foobarString = 'foobar';6+export const foobarUint8Array = textEncoder.encode('foobar');7+export const foobarArrayBuffer = foobarUint8Array.buffer;8+export const foobarUint16Array = new Uint16Array(foobarArrayBuffer);9+export const foobarBuffer = Buffer.from(foobarString);10+export const foobarDataView = new DataView(foobarArrayBuffer);11+export const foobarObject = {foo: 'bar'};12+export const foobarObjectString = JSON.stringify(foobarObject);modified:test/stdio/array.js+1 added-2 removed
2 unmodified lines3 import test from 'ava';4 import tempfile from 'tempfile';5 import {execa, execaSync} from '../../index.js';6 import {fullStdio, getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';7-import {stringGenerator} from '../helpers/generator.js';7 import {setFixtureDir} from '../helpers/fixtures-dir.js';8 9 setFixtureDir();10 110 unmodified lines121 122 const testAmbiguousMultiple = async (t, index) => {123 const filePath = tempfile();124 await writeFile(filePath, 'foobar');126- const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [{file: filePath}, stringGenerator()]));125+ const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [{file: filePath}, ['foo', 'bar']]));126 t.is(stdout, 'foobarfoobar');127 await rm(filePath);128 };129 125 unmodified linesmodified:test/stdio/encoding.js+7 added-4 removed
143 unmodified lines144 yield foobarArray[3];145 }146 };147 148-test('Handle multibyte characters', async t => {149- const {stdout} = await execa('noop.js', {stdout: delayedGenerator, encoding: 'base64'});150- t.is(stdout, btoa(foobarArray.join('')));151-});148+const testMultiByteCharacter = async (t, objectMode) => {149+ const {stdout} = await execa('noop.js', {stdout: {transform: delayedGenerator, objectMode}, encoding: 'base64'});150+ t.is(objectMode ? stdout.join('') : stdout, btoa(foobarArray.join('')));151+};152+153+test('Handle multibyte characters', testMultiByteCharacter, false);154+test('Handle multibyte characters, with objectMode', testMultiByteCharacter, true);modified:test/stdio/file-path.js+2 added-3 removed
6 unmodified lines7 import {execa, execaSync} from '../../index.js';8 import {setFixtureDir} from '../helpers/fixtures-dir.js';9 import {identity, getStdio} from '../helpers/stdio.js';10 import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';11+import {foobarUint8Array} from '../helpers/input.js';12 13 setFixtureDir();14 14-const textEncoder = new TextEncoder();15-const binaryFoobar = textEncoder.encode('foobar');15 const nonFileUrl = new URL('https://example.com');16 17 const getAbsolutePath = file => ({file});18 const getRelativePath = filePath => ({file: relative('.', filePath)});5 unmodified lines24 return {input: 'foobar'};25 }26 27 if (index === 'binary') {29- return {input: binaryFoobar};28+ return {input: foobarUint8Array};29 }30 31 return getStdioFile(index, file);32 };171 unmodified linesmodified:test/stdio/generator.js+349 added-130 removed
1 unmodified line2 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';6+import getStream, {getStreamAsArray} 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+import {foobarString, foobarUint8Array, foobarBuffer, foobarObject, foobarObjectString} from '../helpers/input.js';12+import {serializeGenerator, noopGenerator, getOutputsGenerator, getOutputGenerator, outputObjectGenerator} from '../helpers/generator.js';13 14 setFixtureDir();15 14-const foobarString = 'foobar';16+const textEncoder = new TextEncoder();17+const textDecoder = new TextDecoder();18+19 const foobarUppercase = foobarString.toUpperCase();16-const foobarBuffer = Buffer.from(foobarString);17-const foobarUint8Array = new TextEncoder().encode(foobarString);20+const foobarHex = foobarBuffer.toString('hex');21 22 const uppercaseGenerator = async function * (lines) {23 for await (const line of lines) {24 yield line.toUpperCase();25 }26 };27 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+const uppercaseBufferGenerator = async function * (lines) {29+ for await (const line of lines) {30+ yield textDecoder.decode(line).toUpperCase();31+ }32 };33 30-test('Can use generators with result.stdin', testGeneratorInput, 0);31-test('Can use generators with result.stdio[*] as input', testGeneratorInput, 3);34+const getInputObjectMode = objectMode => objectMode35+ ? {input: [foobarObject], generator: serializeGenerator, output: foobarObjectString}36+ : {input: foobarUint8Array, generator: uppercaseGenerator, output: foobarUppercase};37 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);38+const getOutputObjectMode = objectMode => objectMode39+ ? {generator: outputObjectGenerator, output: [foobarObject], getStreamMethod: getStreamAsArray}40+ : {generator: uppercaseGenerator, output: foobarUppercase, getStreamMethod: getStream};41+42+const testGeneratorInput = async (t, index, objectMode) => {43+ const {input, generator, output} = getInputObjectMode(objectMode);44+ const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [input, generator]));45+ t.is(stdout, output);46+};47+48+test('Can use generators with result.stdin', testGeneratorInput, 0, false);49+test('Can use generators with result.stdio[*] as input', testGeneratorInput, 3, false);50+test('Can use generators with result.stdin, objectMode', testGeneratorInput, 0, true);51+test('Can use generators with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true);52+53+const testGeneratorInputPipe = async (t, useShortcutProperty, objectMode, input) => {54+ const {generator, output} = getInputObjectMode(objectMode);55+ const childProcess = execa('stdin-fd.js', ['0'], getStdio(0, generator));56+ const stream = useShortcutProperty ? childProcess.stdin : childProcess.stdio[0];57+ stream.end(...input);58 const {stdout} = await childProcess;38- t.is(stdout, foobarUppercase);59+ t.is(stdout, output);60 };61 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');62+test('Can use generators with childProcess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, [foobarString, 'utf8']);63+test('Can use generators with childProcess.stdin and default encoding', testGeneratorInputPipe, true, false, [foobarString, 'utf8']);64+test('Can use generators with childProcess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, [foobarBuffer, 'buffer']);65+test('Can use generators with childProcess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, [foobarBuffer, 'buffer']);66+test('Can use generators with childProcess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, [foobarHex, 'hex']);67+test('Can use generators with childProcess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, [foobarHex, 'hex']);68+test('Can use generators with childProcess.stdio[0], objectMode', testGeneratorInputPipe, false, true, [foobarObject]);69+test('Can use generators with childProcess.stdin, objectMode', testGeneratorInputPipe, true, true, [foobarObject]);70 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);71+const testGeneratorStdioInputPipe = async (t, objectMode) => {72+ const {input, generator, output} = getInputObjectMode(objectMode);73+ const childProcess = execa('stdin-fd.js', ['3'], getStdio(3, [new Uint8Array(), generator]));74+ childProcess.stdio[3].write(Array.isArray(input) ? input[0] : input);75 const {stdout} = await childProcess;52- t.is(stdout, foobarUppercase);53-});76+ t.is(stdout, output);77+};78 79+test('Can use generators with childProcess.stdio[*] as input', testGeneratorStdioInputPipe, false);80+test('Can use generators with childProcess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true);81+82+const testGeneratorReturn = async (t, index, generators, fixtureName) => {83+ await t.throwsAsync(84+ execa(fixtureName, [`${index}`], getStdio(index, generators)),85+ {message: /a string or an Uint8Array/},86+ );87+};88+89+const inputObjectGenerators = [foobarUint8Array, getOutputGenerator(foobarObject, false), serializeGenerator];90+const lastInputObjectGenerators = [foobarUint8Array, getOutputGenerator(foobarObject, true)];91+const invalidOutputObjectGenerator = getOutputGenerator(foobarObject, false);92+93+test('Generators with result.stdin cannot return an object if not in objectMode', testGeneratorReturn, 0, inputObjectGenerators, 'stdin-fd.js');94+test('Generators with result.stdio[*] as input cannot return an object if not in objectMode', testGeneratorReturn, 3, inputObjectGenerators, 'stdin-fd.js');95+test('The last generator with result.stdin cannot return an object even in objectMode', testGeneratorReturn, 0, lastInputObjectGenerators, 'stdin-fd.js');96+test('The last generator with result.stdio[*] as input cannot return an object even in objectMode', testGeneratorReturn, 3, lastInputObjectGenerators, 'stdin-fd.js');97+test('Generators with result.stdout cannot return an object if not in objectMode', testGeneratorReturn, 1, invalidOutputObjectGenerator, 'noop-fd.js');98+test('Generators with result.stderr cannot return an object if not in objectMode', testGeneratorReturn, 2, invalidOutputObjectGenerator, 'noop-fd.js');99+test('Generators with result.stdio[*] as output cannot return an object if not in objectMode', testGeneratorReturn, 3, invalidOutputObjectGenerator, 'noop-fd.js');100+101+// eslint-disable-next-line max-params55-const testGeneratorOutput = async (t, index, reject, useShortcutProperty) => {102+const testGeneratorOutput = async (t, index, reject, useShortcutProperty, objectMode) => {103+ const {generator, output} = getOutputObjectMode(objectMode);104 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';57- const {stdout, stderr, stdio} = await execa(fixtureName, [`${index}`, foobarString], {...getStdio(index, uppercaseGenerator), reject});105+ const {stdout, stderr, stdio} = await execa(fixtureName, [`${index}`, foobarString], {...getStdio(index, generator), reject});106 const result = useShortcutProperty ? [stdout, stderr][index - 1] : stdio[index];59- t.is(result, foobarUppercase);107+ t.deepEqual(result, output);108 };109 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);110+test('Can use generators with result.stdio[1]', testGeneratorOutput, 1, true, false, false);111+test('Can use generators with result.stdout', testGeneratorOutput, 1, true, true, false);112+test('Can use generators with result.stdio[2]', testGeneratorOutput, 2, true, false, false);113+test('Can use generators with result.stderr', testGeneratorOutput, 2, true, true, false);114+test('Can use generators with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false);115+test('Can use generators with error.stdio[1]', testGeneratorOutput, 1, false, false, false);116+test('Can use generators with error.stdout', testGeneratorOutput, 1, false, true, false);117+test('Can use generators with error.stdio[2]', testGeneratorOutput, 2, false, false, false);118+test('Can use generators with error.stderr', testGeneratorOutput, 2, false, true, false);119+test('Can use generators with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false);120+test('Can use generators with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true);121+test('Can use generators with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true);122+test('Can use generators with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true);123+test('Can use generators with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true);124+test('Can use generators with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true);125+test('Can use generators with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true);126+test('Can use generators with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true);127+test('Can use generators with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true);128+test('Can use generators with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true);129+test('Can use generators with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true);130 73-const testGeneratorOutputPipe = async (t, index, useShortcutProperty) => {74- const childProcess = execa('noop-fd.js', [`${index}`, foobarString], {...getStdio(index, uppercaseGenerator), buffer: false});131+const testGeneratorOutputPipe = async (t, index, useShortcutProperty, objectMode) => {132+ const {generator, output, getStreamMethod} = getOutputObjectMode(objectMode);133+ const childProcess = execa('noop-fd.js', [`${index}`, foobarString], {...getStdio(index, generator), buffer: false});134 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);135+ const [result] = await Promise.all([getStreamMethod(stream), childProcess]);136+ t.deepEqual(result, output);137 };138 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);139+test('Can use generators with childProcess.stdio[1]', testGeneratorOutputPipe, 1, false, false);140+test('Can use generators with childProcess.stdout', testGeneratorOutputPipe, 1, true, false);141+test('Can use generators with childProcess.stdio[2]', testGeneratorOutputPipe, 2, false, false);142+test('Can use generators with childProcess.stderr', testGeneratorOutputPipe, 2, true, false);143+test('Can use generators with childProcess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false);144+test('Can use generators with childProcess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true);145+test('Can use generators with childProcess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true);146+test('Can use generators with childProcess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true);147+test('Can use generators with childProcess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true);148+test('Can use generators with childProcess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true);149 86-const testGeneratorAll = async (t, reject) => {150+const getAllStdioOption = (stdioOption, encoding, objectMode) => {151+ if (stdioOption) {152+ return 'pipe';153+ }154+155+ if (objectMode) {156+ return outputObjectGenerator;157+ }158+159+ return encoding === 'buffer' ? uppercaseBufferGenerator : uppercaseGenerator;160+};161+162+const getStdoutStderrOutput = (output, stdioOption, encoding, objectMode) => {163+ if (objectMode && !stdioOption) {164+ return [foobarObject];165+ }166+167+ const stdioOutput = stdioOption ? output : output.toUpperCase();168+ return encoding === 'buffer' ? textEncoder.encode(stdioOutput) : stdioOutput;169+};170+171+const getAllOutput = (stdoutOutput, stderrOutput, encoding, objectMode) => {172+ if (objectMode) {173+ return [stdoutOutput, stderrOutput].flat();174+ }175+176+ return encoding === 'buffer'177+ ? new Uint8Array([...stdoutOutput, ...stderrOutput])178+ : `${stdoutOutput}${stderrOutput}`;179+};180+181+// eslint-disable-next-line max-params182+const testGeneratorAll = async (t, reject, encoding, objectMode, stdoutOption, stderrOption) => {183 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');184+ const {stdout, stderr, all} = await execa(fixtureName, {185+ all: true,186+ reject,187+ stdout: getAllStdioOption(stdoutOption, encoding, objectMode),188+ stderr: getAllStdioOption(stderrOption, encoding, objectMode),189+ encoding,190+ stripFinalNewline: false,191+ });192+193+ const stdoutOutput = getStdoutStderrOutput('stdout\n', stdoutOption, encoding, objectMode);194+ t.deepEqual(stdout, stdoutOutput);195+ const stderrOutput = getStdoutStderrOutput('stderr\n', stderrOption, encoding, objectMode);196+ t.deepEqual(stderr, stderrOutput);197+ const allOutput = getAllOutput(stdoutOutput, stderrOutput, encoding, objectMode);198+ t.deepEqual(all, allOutput);199 };200 92-test('Can use generators with result.all', testGeneratorAll, true);93-test('Can use generators with error.all', testGeneratorAll, false);201+test('Can use generators with result.all = transform + transform', testGeneratorAll, true, 'utf8', false, false, false);202+test('Can use generators with error.all = transform + transform', testGeneratorAll, false, 'utf8', false, false, false);203+test('Can use generators with result.all = transform + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, false);204+test('Can use generators with error.all = transform + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, false);205+test('Can use generators with result.all = transform + pipe', testGeneratorAll, true, 'utf8', false, false, true);206+test('Can use generators with error.all = transform + pipe', testGeneratorAll, false, 'utf8', false, false, true);207+test('Can use generators with result.all = transform + pipe, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, true);208+test('Can use generators with error.all = transform + pipe, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, true);209+test('Can use generators with result.all = pipe + transform', testGeneratorAll, true, 'utf8', false, true, false);210+test('Can use generators with error.all = pipe + transform', testGeneratorAll, false, 'utf8', false, true, false);211+test('Can use generators with result.all = pipe + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, true, false);212+test('Can use generators with error.all = pipe + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, true, false);213+test('Can use generators with result.all = transform + transform, objectMode', testGeneratorAll, true, 'utf8', true, false, false);214+test('Can use generators with error.all = transform + transform, objectMode', testGeneratorAll, false, 'utf8', true, false, false);215+test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, false);216+test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, false);217+test('Can use generators with result.all = transform + pipe, objectMode', testGeneratorAll, true, 'utf8', true, false, true);218+test('Can use generators with error.all = transform + pipe, objectMode', testGeneratorAll, false, 'utf8', true, false, true);219+test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, true);220+test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, true);221+test('Can use generators with result.all = pipe + transform, objectMode', testGeneratorAll, true, 'utf8', true, true, false);222+test('Can use generators with error.all = pipe + transform, objectMode', testGeneratorAll, false, 'utf8', true, true, false);223+test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, true, false);224+test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, true, false);225 226 test('Can use generators with input option', async t => {227 const {stdout} = await execa('stdin-fd.js', ['0'], {stdin: uppercaseGenerator, input: foobarUint8Array});228 t.is(stdout, foobarUppercase);19 unmodified lines248 test('Cannot use invalid "transform" with stdout', testInvalidGenerator, 1, {transform: true});249 test('Cannot use invalid "transform" with stderr', testInvalidGenerator, 2, {transform: true});250 test('Cannot use invalid "transform" with stdio[*]', testInvalidGenerator, 3, {transform: true});251 121-const testInvalidBinary = (t, index) => {252+const testInvalidBinary = (t, index, optionName) => {253 t.throws(() => {123- execa('empty.js', getStdio(index, {transform: uppercaseGenerator, binary: 'true'}));254+ execa('empty.js', getStdio(index, {transform: uppercaseGenerator, [optionName]: 'true'}));255 }, {message: /a boolean/});256 };257 127-test('Cannot use invalid "binary" with stdin', testInvalidBinary, 0);128-test('Cannot use invalid "binary" with stdout', testInvalidBinary, 1);129-test('Cannot use invalid "binary" with stderr', testInvalidBinary, 2);130-test('Cannot use invalid "binary" with stdio[*]', testInvalidBinary, 3);258+test('Cannot use invalid "binary" with stdin', testInvalidBinary, 0, 'binary');259+test('Cannot use invalid "binary" with stdout', testInvalidBinary, 1, 'binary');260+test('Cannot use invalid "binary" with stderr', testInvalidBinary, 2, 'binary');261+test('Cannot use invalid "binary" with stdio[*]', testInvalidBinary, 3, 'binary');262+test('Cannot use invalid "objectMode" with stdin', testInvalidBinary, 0, 'objectMode');263+test('Cannot use invalid "objectMode" with stdout', testInvalidBinary, 1, 'objectMode');264+test('Cannot use invalid "objectMode" with stderr', testInvalidBinary, 2, 'objectMode');265+test('Cannot use invalid "objectMode" with stdio[*]', testInvalidBinary, 3, 'objectMode');266 267 const testSyncMethods = (t, index) => {268 t.throws(() => {269 execaSync('empty.js', getStdio(index, uppercaseGenerator));25 unmodified lines295 yield `${chunk.length}`;296 }297 };298 164-const testHighWaterMark = async (t, passThrough) => {165- const index = 1;166- const {stdout} = await execa('noop-fd.js', [`${index}`], getStdio(index, [167- writerGenerator,168- ...passThrough,169- {transform: getLengthGenerator, binary: true},170- ]));299+const testHighWaterMark = async (t, passThrough, binary, objectMode) => {300+ const {stdout} = await execa('noop.js', {301+ stdout: [302+ ...(objectMode ? [outputObjectGenerator] : []),303+ writerGenerator,304+ ...(passThrough ? [{transform: passThroughGenerator, binary}] : []),305+ {transform: getLengthGenerator, binary: true},306+ ],307+ });308 t.is(stdout, `${getDefaultHighWaterMark()}`.repeat(repeatHighWaterMark));309 };310 174-test('Stream respects highWaterMark, no passThrough', testHighWaterMark, []);175-test('Stream respects highWaterMark, line-wise passThrough', testHighWaterMark, [passThroughGenerator]);176-test('Stream respects highWaterMark, binary passThrough', testHighWaterMark, [{transform: passThroughGenerator, binary: true}]);311+test('Stream respects highWaterMark, no passThrough', testHighWaterMark, false, false, false);312+test('Stream respects highWaterMark, line-wise passThrough', testHighWaterMark, true, false, false);313+test('Stream respects highWaterMark, binary passThrough', testHighWaterMark, true, true, false);314+test('Stream respects highWaterMark, objectMode as input but not output', testHighWaterMark, false, false, true);315 316+const getTypeofGenerator = objectMode => ({178-const typeofGenerator = async function * (lines) {179- for await (const line of lines) {180- yield Object.prototype.toString.call(line);181- }182-};317+ async * transform(lines) {318+ for await (const line of lines) {319+ yield Object.prototype.toString.call(line);320+ }321+ },322+ objectMode,323+});324 325+// eslint-disable-next-line max-params184-const testGeneratorFirstEncoding = async (t, input, encoding) => {185- const childProcess = execa('stdin.js', {stdin: typeofGenerator, encoding});326+const testGeneratorFirstEncoding = async (t, input, encoding, output, objectMode) => {327+ const childProcess = execa('stdin.js', {stdin: getTypeofGenerator(objectMode), encoding});328 childProcess.stdin.end(input);329 const {stdout} = await childProcess;188- const output = Buffer.from(stdout, encoding).toString();189- t.is(output, encoding === 'buffer' ? '[object Uint8Array]' : '[object String]');330+ const result = Buffer.from(stdout, encoding).toString();331+ t.is(result, output);332 };333 192-test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8');193-test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8');194-test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8');195-test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer');196-test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer');197-test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer');198-test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex');199-test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex');200-test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex');334+test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8', '[object String]', false);335+test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8', '[object String]', false);336+test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8', '[object String]', false);337+test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer', '[object Uint8Array]', false);338+test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer', '[object Uint8Array]', false);339+test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer', '[object Uint8Array]', false);340+test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex', '[object String]', false);341+test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex', '[object String]', false);342+test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex', '[object String]', false);343+test('First generator argument can be string with objectMode', testGeneratorFirstEncoding, foobarString, 'utf8', '[object String]', true);344+test('First generator argument can be objects with objectMode', testGeneratorFirstEncoding, foobarObject, 'utf8', '[object Object]', true);345 202-const outputGenerator = async function * (input, lines) {203- // eslint-disable-next-line no-unused-vars204- for await (const line of lines) {205- yield input;206- }346+const testEncodingIgnored = async (t, encoding) => {347+ const input = Buffer.from(foobarString).toString(encoding);348+ const childProcess = execa('stdin.js', {stdin: noopGenerator(true)});349+ childProcess.stdin.end(input, encoding);350+ const {stdout} = await childProcess;351+ t.is(stdout, input);352 };353 209-const testGeneratorNextEncoding = async (t, input, encoding) => {210- const {stdout} = await execa('noop.js', ['other'], {stdout: [outputGenerator.bind(undefined, input), typeofGenerator], encoding});211- const output = Buffer.from(stdout, encoding).toString();212- t.is(output, encoding === 'buffer' ? '[object Uint8Array]' : '[object String]');354+test('Write call encoding "utf8" is ignored with objectMode', testEncodingIgnored, 'utf8');355+test('Write call encoding "utf16le" is ignored with objectMode', testEncodingIgnored, 'utf16le');356+test('Write call encoding "hex" is ignored with objectMode', testEncodingIgnored, 'hex');357+test('Write call encoding "base64" is ignored with objectMode', testEncodingIgnored, 'base64');358+359+// eslint-disable-next-line max-params360+const testGeneratorNextEncoding = async (t, input, encoding, firstObjectMode, secondObjectMode, expectedType) => {361+ const {stdout} = await execa('noop.js', ['other'], {362+ stdout: [363+ getOutputGenerator(input, firstObjectMode),364+ getTypeofGenerator(secondObjectMode),365+ ],366+ encoding,367+ });368+ const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;369+ const output = Buffer.from(typeofChunk, encoding === 'buffer' ? undefined : encoding).toString();370+ t.is(output, `[object ${expectedType}]`);371 };372 215-test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8');216-test('Next generator argument is string with default encoding, with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'utf8');217-test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8');218-test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer');219-test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'buffer');220-test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer');221-test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex');222-test('Next generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'hex');223-test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex');373+test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String');374+test('Next generator argument is string with default encoding, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String');375+test('Next generator argument is string with default encoding, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String');376+test('Next generator argument is string with default encoding, with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'utf8', false, false, 'String');377+test('Next generator argument is string with default encoding, with Buffer writes, objectMode first', testGeneratorNextEncoding, foobarBuffer, 'utf8', true, false, 'String');378+test('Next generator argument is string with default encoding, with Buffer writes, objectMode both', testGeneratorNextEncoding, foobarBuffer, 'utf8', true, true, 'String');379+test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String');380+test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'String');381+test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'String');382+test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array');383+test('Next generator argument is Uint8Array with encoding "buffer", with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'Uint8Array');384+test('Next generator argument is Uint8Array with encoding "buffer", with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'Uint8Array');385+test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'buffer', false, false, 'Uint8Array');386+test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes, objectMode first', testGeneratorNextEncoding, foobarBuffer, 'buffer', true, false, 'Uint8Array');387+test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes, objectMode both', testGeneratorNextEncoding, foobarBuffer, 'buffer', true, true, 'Uint8Array');388+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array');389+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array');390+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array');391+test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'String');392+test('Next generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'hex', false, false, 'String');393+test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'String');394+test('Next generator argument is object with default encoding, with object writes, objectMode first', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object');395+test('Next generator argument is object with default encoding, with object writes, objectMode both', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object');396 225-const testGeneratorReturnType = async (t, input, encoding) => {226- const {stdout} = await execa('noop.js', ['other'], {stdout: outputGenerator.bind(undefined, input), encoding});227- const output = Buffer.from(stdout, encoding).toString();397+const testFirstOutputGeneratorArgument = async (t, index) => {398+ const {stdio} = await execa('noop-fd.js', [`${index}`], getStdio(index, getTypeofGenerator(true)));399+ t.deepEqual(stdio[index], ['[object String]']);400+};401+402+test('The first generator with result.stdout does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 1);403+test('The first generator with result.stderr does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 2);404+test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3);405+406+// eslint-disable-next-line max-params407+const testGeneratorReturnType = async (t, input, encoding, reject, objectMode) => {408+ const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';409+ const {stdout} = await execa(fixtureName, ['1', 'other'], {410+ stdout: getOutputGenerator(input, objectMode),411+ encoding,412+ reject,413+ });414+ const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;415+ const output = Buffer.from(typeofChunk, encoding === 'buffer' ? undefined : encoding).toString();416 t.is(output, foobarString);417 };418 231-test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8');232-test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8');233-test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer');234-test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer');235-test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex');236-test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex');419+test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false);420+test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false);421+test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false);422+test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false);423+test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false);424+test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false);425+test('Generator can return string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false);426+test('Generator can return Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false);427+test('Generator can return string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false);428+test('Generator can return Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false);429+test('Generator can return string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false);430+test('Generator can return Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false);431+test('Generator can return string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true);432+test('Generator can return Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true);433+test('Generator can return string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true);434+test('Generator can return Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true);435+test('Generator can return string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true);436+test('Generator can return Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true);437+test('Generator can return string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true);438+test('Generator can return Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true);439+test('Generator can return string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true);440+test('Generator can return Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true);441+test('Generator can return string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true);442+test('Generator can return Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true);443 444 const multibyteChar = '\u{1F984}';445 const multibyteString = `${multibyteChar}${multibyteChar}`;240-const multibyteUint8Array = new TextEncoder().encode(multibyteString);446+const multibyteUint8Array = textEncoder.encode(multibyteString);447 const breakingLength = multibyteUint8Array.length * 0.75;448 const brokenSymbol = '\uFFFD';449 244-const noopGenerator = async function * (lines) {245- yield * lines;246-};247-248-test('Generator handles multibyte characters with Uint8Array', async t => {249- const childProcess = execa('stdin.js', {stdin: noopGenerator});450+const testMultibyte = async (t, objectMode) => {451+ const childProcess = execa('stdin.js', {stdin: noopGenerator(objectMode)});452 childProcess.stdin.write(multibyteUint8Array.slice(0, breakingLength));453 await setTimeout(0);454 childProcess.stdin.end(multibyteUint8Array.slice(breakingLength));455 const {stdout} = await childProcess;456 t.is(stdout, multibyteString);255-});457+};458 257-test('Generator handles partial multibyte characters with Uint8Array', async t => {258- const {stdout} = await execa('stdin.js', {stdin: [multibyteUint8Array.slice(0, breakingLength), noopGenerator]});459+test('Generator handles multibyte characters with Uint8Array', testMultibyte, false);460+test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true);461+462+const testMultibytePartial = async (t, objectMode) => {463+ const {stdout} = await execa('stdin.js', {stdin: [multibyteUint8Array.slice(0, breakingLength), noopGenerator(objectMode)]});464 t.is(stdout, `${multibyteChar}${brokenSymbol}`);260-});465+};466 467+test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false);468+test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true);469+470 // eslint-disable-next-line require-yield471 const noYieldGenerator = async function * (lines) {472 // eslint-disable-next-line no-empty, no-unused-vars473 for await (const line of lines) {}474 };475 268-test('Generator can filter by not calling yield', async t => {269- const {stdout} = await execa('noop.js', {stdout: noYieldGenerator});270- t.is(stdout, '');271-});476+const testNoYield = async (t, objectMode, output) => {477+ const {stdout} = await execa('noop.js', {stdout: {transform: noYieldGenerator, objectMode}});478+ t.deepEqual(stdout, output);479+};480 481+test('Generator can filter by not calling yield', testNoYield, false, '');482+test('Generator can filter by not calling yield, objectMode', testNoYield, true, []);483+484 const prefix = '> ';485 const suffix = ' <';486 487 const multipleYieldGenerator = async function * (lines) {99 unmodified lines587 const maxBuffer = 10;588 589 test('Generators take "maxBuffer" into account', async t => {590 const bigString = '.'.repeat(maxBuffer);380- const {stdout} = await execa('noop.js', {maxBuffer, stdout: outputGenerator.bind(undefined, bigString)});591+ const {stdout} = await execa('noop.js', {maxBuffer, stdout: getOutputGenerator(bigString, false)});592 t.is(stdout, bigString);593 383- await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: outputGenerator.bind(undefined, `${bigString}.`)}));594+ await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputGenerator(`${bigString}.`, false)}));595 });596 597+test('Generators take "maxBuffer" into account, objectMode', async t => {598+ const bigArray = Array.from({length: maxBuffer});599+ const {stdout} = await execa('noop.js', {maxBuffer, stdout: getOutputsGenerator(bigArray, true)});600+ t.is(stdout.length, maxBuffer);601+602+ await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputsGenerator([...bigArray, ''], true)}));603+});604+605 const timeoutGenerator = async function * (timeout, lines) {606 for await (const line of lines) {607 await setTimeout(timeout);608 yield line;45 unmodified linesmodified:test/stdio/input.js+11 added-18 removed
1-import {Buffer} from 'node:buffer';1 import {Writable} from 'node:stream';2 import test from 'ava';3 import {execa, execaSync} from '../../index.js';4 import {setFixtureDir} from '../helpers/fixtures-dir.js';5 import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';6+import {foobarUint8Array, foobarBuffer, foobarArrayBuffer, foobarUint16Array, foobarDataView} from '../helpers/input.js';7 8 setFixtureDir();9 10-const textEncoder = new TextEncoder();11-const binaryFoobar = textEncoder.encode('foobar');12-const bufferFoobar = Buffer.from(binaryFoobar);13-const arrayBufferFoobar = binaryFoobar.buffer;14-const dataViewFoobar = new DataView(arrayBufferFoobar);15-const uint16ArrayFoobar = new Uint16Array(arrayBufferFoobar);16-10 const testInput = async (t, input, execaMethod) => {11 const {stdout} = await execaMethod('stdin.js', {input});12 t.is(stdout, 'foobar');13 };14 15 test('input option can be a String', testInput, 'foobar', runExeca);23-test('input option can be a Uint8Array', testInput, binaryFoobar, runExeca);16+test('input option can be a Uint8Array', testInput, foobarUint8Array, runExeca);17 test('input option can be a String - sync', testInput, 'foobar', runExecaSync);25-test('input option can be a Uint8Array - sync', testInput, binaryFoobar, runExecaSync);18+test('input option can be a Uint8Array - sync', testInput, foobarUint8Array, runExecaSync);19 test('input option can be used with $', testInput, 'foobar', runScript);20 test('input option can be used with $.sync', testInput, 'foobar', runScriptSync);21 22 const testInvalidInput = async (t, input, execaMethod) => {1 unmodified line24 execaMethod('empty.js', {input});25 }, {message: /a string, a Uint8Array/});26 };27 35-test('input option cannot be a Buffer', testInvalidInput, bufferFoobar, execa);36-test('input option cannot be an ArrayBuffer', testInvalidInput, arrayBufferFoobar, execa);37-test('input option cannot be a DataView', testInvalidInput, dataViewFoobar, execa);38-test('input option cannot be a Uint16Array', testInvalidInput, uint16ArrayFoobar, execa);28+test('input option cannot be a Buffer', testInvalidInput, foobarBuffer, execa);29+test('input option cannot be an ArrayBuffer', testInvalidInput, foobarArrayBuffer, execa);30+test('input option cannot be a DataView', testInvalidInput, foobarDataView, execa);31+test('input option cannot be a Uint16Array', testInvalidInput, foobarUint16Array, execa);32 test('input option cannot be 0', testInvalidInput, 0, execa);33 test('input option cannot be false', testInvalidInput, false, execa);34 test('input option cannot be null', testInvalidInput, null, execa);35 test('input option cannot be a non-Readable stream', testInvalidInput, new Writable(), execa);43-test('input option cannot be a Buffer - sync', testInvalidInput, bufferFoobar, execaSync);44-test('input option cannot be an ArrayBuffer - sync', testInvalidInput, arrayBufferFoobar, execaSync);45-test('input option cannot be a DataView - sync', testInvalidInput, dataViewFoobar, execaSync);46-test('input option cannot be a Uint16Array - sync', testInvalidInput, uint16ArrayFoobar, execaSync);36+test('input option cannot be a Buffer - sync', testInvalidInput, foobarBuffer, execaSync);37+test('input option cannot be an ArrayBuffer - sync', testInvalidInput, foobarArrayBuffer, execaSync);38+test('input option cannot be a DataView - sync', testInvalidInput, foobarDataView, execaSync);39+test('input option cannot be a Uint16Array - sync', testInvalidInput, foobarUint16Array, execaSync);40 test('input option cannot be 0 - sync', testInvalidInput, 0, execaSync);41 test('input option cannot be false - sync', testInvalidInput, false, execaSync);42 test('input option cannot be null - sync', testInvalidInput, null, execaSync);43 test('input option cannot be a non-Readable stream - sync', testInvalidInput, new Writable(), execaSync);modified:test/stdio/iterable.js+75 added-7 removed
1 import {once} from 'node:events';2+import {setTimeout} from 'node:timers/promises';3 import test from 'ava';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDir} from '../helpers/fixtures-dir.js';6 import {getStdio} from '../helpers/stdio.js';6-import {stringGenerator, binaryGenerator, asyncGenerator, throwingGenerator, infiniteGenerator} from '../helpers/generator.js';7+import {foobarObject, foobarObjectString} from '../helpers/input.js';8+import {serializeGenerator} from '../helpers/generator.js';9 10+const stringArray = ['foo', 'bar'];11+12+const stringGenerator = function * () {13+ yield * stringArray;14+};15+16+const textEncoder = new TextEncoder();17+const binaryFoo = textEncoder.encode('foo');18+const binaryBar = textEncoder.encode('bar');19+const binaryArray = [binaryFoo, binaryBar];20+21+const binaryGenerator = function * () {22+ yield * binaryArray;23+};24+25+const asyncGenerator = async function * () {26+ await setTimeout(0);27+ yield * stringArray;28+};29+30 setFixtureDir();31 32 const testIterable = async (t, stdioOption, index) => {33 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, stdioOption));34 t.is(stdout, 'foobar');35 };36 37+test('stdin option can be an array of strings', testIterable, [stringArray], 0);38+test('stdio[*] option can be an array of strings', testIterable, [stringArray], 3);39+test('stdin option can be an array of Uint8Arrays', testIterable, [binaryArray], 0);40+test('stdio[*] option can be an array of Uint8Arrays', testIterable, [binaryArray], 3);41 test('stdin option can be an iterable of strings', testIterable, stringGenerator(), 0);42 test('stdio[*] option can be an iterable of strings', testIterable, stringGenerator(), 3);43 test('stdin option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 0);44 test('stdio[*] option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 3);45 test('stdin option can be an async iterable', testIterable, asyncGenerator(), 0);46 test('stdio[*] option can be an async iterable', testIterable, asyncGenerator(), 3);47 48+const foobarObjectGenerator = function * () {49+ yield foobarObject;50+};51+52+const foobarAsyncObjectGenerator = function * () {53+ yield foobarObject;54+};55+56+const testObjectIterable = async (t, stdioOption, index) => {57+ const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [stdioOption, serializeGenerator]));58+ t.is(stdout, foobarObjectString);59+};60+61+test('stdin option can be an array of objects', testObjectIterable, [foobarObject], 0);62+test('stdio[*] option can be an array of objects', testObjectIterable, [foobarObject], 3);63+test('stdin option can be an iterable of objects', testObjectIterable, foobarObjectGenerator(), 0);64+test('stdio[*] option can be an iterable of objects', testObjectIterable, foobarObjectGenerator(), 3);65+test('stdin option can be an async iterable of objects', testObjectIterable, foobarAsyncObjectGenerator(), 0);66+test('stdio[*] option can be an async iterable of objects', testObjectIterable, foobarAsyncObjectGenerator(), 3);67+68 const testIterableSync = (t, stdioOption, index) => {69 t.throws(() => {70 execaSync('empty.js', getStdio(index, stdioOption));71 }, {message: /an iterable in sync mode/});72 };73 74+test('stdin option cannot be an array of strings - sync', testIterableSync, [stringArray], 0);75+test('stdio[*] option cannot be an array of strings - sync', testIterableSync, [stringArray], 3);76 test('stdin option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 0);77 test('stdio[*] option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 3);78 test('stdin option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 0);79 test('stdio[*] option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 3);80 81+// eslint-disable-next-line require-yield82+const throwingGenerator = function * () {83+ throw new Error('generator error');84+};85+86 const testIterableError = async (t, index) => {87 const {originalMessage} = await t.throwsAsync(execa('stdin-fd.js', [`${index}`], getStdio(index, throwingGenerator())));88 t.is(originalMessage, 'generator error');89 };90 91 test('stdin option handles errors in iterables', testIterableError, 0);92 test('stdio[*] option handles errors in iterables', testIterableError, 3);93 41-const testNoIterableOutput = (t, index, execaMethod) => {94+const testNoIterableOutput = (t, stdioOption, index, execaMethod) => {95 t.throws(() => {43- execaMethod('empty.js', getStdio(index, stringGenerator()));96+ execaMethod('empty.js', getStdio(index, stdioOption));97 }, {message: /cannot be an iterable/});98 };99 47-test('stdout option cannot be an iterable', testNoIterableOutput, 1, execa);48-test('stderr option cannot be an iterable', testNoIterableOutput, 2, execa);49-test('stdout option cannot be an iterable - sync', testNoIterableOutput, 1, execaSync);50-test('stderr option cannot be an iterable - sync', testNoIterableOutput, 2, execaSync);100+test('stdout option cannot be an array of strings', testNoIterableOutput, [stringArray], 1, execa);101+test('stderr option cannot be an array of strings', testNoIterableOutput, [stringArray], 2, execa);102+test('stdout option cannot be an array of strings - sync', testNoIterableOutput, [stringArray], 1, execaSync);103+test('stderr option cannot be an array of strings - sync', testNoIterableOutput, [stringArray], 2, execaSync);104+test('stdout option cannot be an iterable', testNoIterableOutput, stringGenerator(), 1, execa);105+test('stderr option cannot be an iterable', testNoIterableOutput, stringGenerator(), 2, execa);106+test('stdout option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 1, execaSync);107+test('stderr option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 2, execaSync);108 109+const infiniteGenerator = () => {110+ const controller = new AbortController();111+112+ const generator = async function * () {113+ yield 'foo';114+ await setTimeout(1e7, undefined, {signal: controller.signal});115+ };116+117+ return {iterable: generator(), abort: controller.abort.bind(controller)};118+};119+120 test('stdin option can be an infinite iterable', async t => {121 const {iterable, abort} = infiniteGenerator();122 try {123 const childProcess = execa('stdin.js', getStdio(0, iterable));16 unmodified linesmodified:test/stdio/lines.js+75 added-38 removed
31 unmodified lines32 33 const stringsToUint8Arrays = (strings, isUint8Array) => isUint8Array34 ? strings.map(string => textEncoder.encode(string))35 : strings;36-const uint8ArrayToString = (result, isUint8Array) => isUint8Array ? textDecoder.decode(result) : result;36 37+const serializeResult = (result, isUint8Array, objectMode) => objectMode38+ ? result.map(resultItem => serializeResultItem(resultItem, isUint8Array)).join('')39+ : serializeResultItem(result, isUint8Array);40+41+const serializeResultItem = (resultItem, isUint8Array) => isUint8Array42+ ? textDecoder.decode(resultItem)43+ : resultItem;44+45 // eslint-disable-next-line max-params39-const testLines = async (t, index, input, expectedLines, isUint8Array) => {46+const testLines = async (t, index, input, expectedLines, isUint8Array, objectMode) => {47 const lines = [];48 const {stdio} = await execa('noop-fd.js', [`${index}`], {49 ...getStdio(index, [43- inputGenerator.bind(undefined, stringsToUint8Arrays(input, isUint8Array)),44- resultGenerator.bind(undefined, lines),50+ {transform: inputGenerator.bind(undefined, stringsToUint8Arrays(input, isUint8Array)), objectMode},51+ {transform: resultGenerator.bind(undefined, lines), objectMode},52 ]),53 encoding: isUint8Array ? 'buffer' : 'utf8',54 stripFinalNewline: false,55 });49- t.is(uint8ArrayToString(stdio[index], isUint8Array), input.join(''));56+ t.is(input.join(''), serializeResult(stdio[index], isUint8Array, objectMode));57 t.deepEqual(lines, stringsToUint8Arrays(expectedLines, isUint8Array));58 };59 53-test('Split string stdout - n newlines, 1 chunk', testLines, 1, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false);54-test('Split string stderr - n newlines, 1 chunk', testLines, 2, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false);55-test('Split string stdio[*] - n newlines, 1 chunk', testLines, 3, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false);56-test('Split string stdout - no newline, n chunks', testLines, 1, ['aaa', 'bbb', 'ccc'], ['aaabbbccc'], false);57-test('Split string stdout - 0 newlines, 1 chunk', testLines, 1, ['aaa'], ['aaa'], false);58-test('Split string stdout - Windows newlines', testLines, 1, ['aaa\r\nbbb\r\nccc'], ['aaa\r\n', 'bbb\r\n', 'ccc'], false);59-test('Split string stdout - chunk ends with newline', testLines, 1, ['aaa\nbbb\nccc\n'], ['aaa\n', 'bbb\n', 'ccc\n'], false);60-test('Split string stdout - single newline', testLines, 1, ['\n'], ['\n'], false);61-test('Split string stdout - only newlines', testLines, 1, ['\n\n\n'], ['\n', '\n', '\n'], false);62-test('Split string stdout - only Windows newlines', testLines, 1, ['\r\n\r\n\r\n'], ['\r\n', '\r\n', '\r\n'], false);63-test('Split string stdout - line split over multiple chunks', testLines, 1, ['aaa\nb', 'b', 'b\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false);64-test('Split string stdout - 0 newlines, big line', testLines, 1, [bigLine], [bigLine], false);65-test('Split string stdout - 0 newlines, many chunks', testLines, 1, manyChunks, [manyChunks.join('')], false);66-test('Split Uint8Array stdout - n newlines, 1 chunk', testLines, 1, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true);67-test('Split Uint8Array stderr - n newlines, 1 chunk', testLines, 2, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true);68-test('Split Uint8Array stdio[*] - n newlines, 1 chunk', testLines, 3, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true);69-test('Split Uint8Array stdout - no newline, n chunks', testLines, 1, ['aaa', 'bbb', 'ccc'], ['aaabbbccc'], true);70-test('Split Uint8Array stdout - 0 newlines, 1 chunk', testLines, 1, ['aaa'], ['aaa'], true);71-test('Split Uint8Array stdout - Windows newlines', testLines, 1, ['aaa\r\nbbb\r\nccc'], ['aaa\r\n', 'bbb\r\n', 'ccc'], true);72-test('Split Uint8Array stdout - chunk ends with newline', testLines, 1, ['aaa\nbbb\nccc\n'], ['aaa\n', 'bbb\n', 'ccc\n'], true);73-test('Split Uint8Array stdout - single newline', testLines, 1, ['\n'], ['\n'], true);74-test('Split Uint8Array stdout - only newlines', testLines, 1, ['\n\n\n'], ['\n', '\n', '\n'], true);75-test('Split Uint8Array stdout - only Windows newlines', testLines, 1, ['\r\n\r\n\r\n'], ['\r\n', '\r\n', '\r\n'], true);76-test('Split Uint8Array stdout - line split over multiple chunks', testLines, 1, ['aaa\nb', 'b', 'b\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true);77-test('Split Uint8Array stdout - 0 newlines, big line', testLines, 1, [bigLine], [bigLine], true);78-test('Split Uint8Array stdout - 0 newlines, many chunks', testLines, 1, manyChunks, [manyChunks.join('')], true);60+test('Split string stdout - n newlines, 1 chunk', testLines, 1, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, false);61+test('Split string stderr - n newlines, 1 chunk', testLines, 2, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, false);62+test('Split string stdio[*] - n newlines, 1 chunk', testLines, 3, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, false);63+test('Split string stdout - no newline, n chunks', testLines, 1, ['aaa', 'bbb', 'ccc'], ['aaabbbccc'], false, false);64+test('Split string stdout - 0 newlines, 1 chunk', testLines, 1, ['aaa'], ['aaa'], false, false);65+test('Split string stdout - Windows newlines', testLines, 1, ['aaa\r\nbbb\r\nccc'], ['aaa\r\n', 'bbb\r\n', 'ccc'], false, false);66+test('Split string stdout - chunk ends with newline', testLines, 1, ['aaa\nbbb\nccc\n'], ['aaa\n', 'bbb\n', 'ccc\n'], false, false);67+test('Split string stdout - single newline', testLines, 1, ['\n'], ['\n'], false, false);68+test('Split string stdout - only newlines', testLines, 1, ['\n\n\n'], ['\n', '\n', '\n'], false, false);69+test('Split string stdout - only Windows newlines', testLines, 1, ['\r\n\r\n\r\n'], ['\r\n', '\r\n', '\r\n'], false, false);70+test('Split string stdout - line split over multiple chunks', testLines, 1, ['aaa\nb', 'b', 'b\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, false);71+test('Split string stdout - 0 newlines, big line', testLines, 1, [bigLine], [bigLine], false, false);72+test('Split string stdout - 0 newlines, many chunks', testLines, 1, manyChunks, [manyChunks.join('')], false, false);73+test('Split Uint8Array stdout - n newlines, 1 chunk', testLines, 1, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, false);74+test('Split Uint8Array stderr - n newlines, 1 chunk', testLines, 2, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, false);75+test('Split Uint8Array stdio[*] - n newlines, 1 chunk', testLines, 3, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, false);76+test('Split Uint8Array stdout - no newline, n chunks', testLines, 1, ['aaa', 'bbb', 'ccc'], ['aaabbbccc'], true, false);77+test('Split Uint8Array stdout - 0 newlines, 1 chunk', testLines, 1, ['aaa'], ['aaa'], true, false);78+test('Split Uint8Array stdout - Windows newlines', testLines, 1, ['aaa\r\nbbb\r\nccc'], ['aaa\r\n', 'bbb\r\n', 'ccc'], true, false);79+test('Split Uint8Array stdout - chunk ends with newline', testLines, 1, ['aaa\nbbb\nccc\n'], ['aaa\n', 'bbb\n', 'ccc\n'], true, false);80+test('Split Uint8Array stdout - single newline', testLines, 1, ['\n'], ['\n'], true, false);81+test('Split Uint8Array stdout - only newlines', testLines, 1, ['\n\n\n'], ['\n', '\n', '\n'], true, false);82+test('Split Uint8Array stdout - only Windows newlines', testLines, 1, ['\r\n\r\n\r\n'], ['\r\n', '\r\n', '\r\n'], true, false);83+test('Split Uint8Array stdout - line split over multiple chunks', testLines, 1, ['aaa\nb', 'b', 'b\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, false);84+test('Split Uint8Array stdout - 0 newlines, big line', testLines, 1, [bigLine], [bigLine], true, false);85+test('Split Uint8Array stdout - 0 newlines, many chunks', testLines, 1, manyChunks, [manyChunks.join('')], true, false);86+test('Split string stdout - n newlines, 1 chunk, objectMode', testLines, 1, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, true);87+test('Split string stderr - n newlines, 1 chunk, objectMode', testLines, 2, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, true);88+test('Split string stdio[*] - n newlines, 1 chunk, objectMode', testLines, 3, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, true);89+test('Split string stdout - no newline, n chunks, objectMode', testLines, 1, ['aaa', 'bbb', 'ccc'], ['aaabbbccc'], false, true);90+test('Split string stdout - 0 newlines, 1 chunk, objectMode', testLines, 1, ['aaa'], ['aaa'], false, true);91+test('Split string stdout - Windows newlines, objectMode', testLines, 1, ['aaa\r\nbbb\r\nccc'], ['aaa\r\n', 'bbb\r\n', 'ccc'], false, true);92+test('Split string stdout - chunk ends with newline, objectMode', testLines, 1, ['aaa\nbbb\nccc\n'], ['aaa\n', 'bbb\n', 'ccc\n'], false, true);93+test('Split string stdout - single newline, objectMode', testLines, 1, ['\n'], ['\n'], false, true);94+test('Split string stdout - only newlines, objectMode', testLines, 1, ['\n\n\n'], ['\n', '\n', '\n'], false, true);95+test('Split string stdout - only Windows newlines, objectMode', testLines, 1, ['\r\n\r\n\r\n'], ['\r\n', '\r\n', '\r\n'], false, true);96+test('Split string stdout - line split over multiple chunks, objectMode', testLines, 1, ['aaa\nb', 'b', 'b\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, true);97+test('Split string stdout - 0 newlines, big line, objectMode', testLines, 1, [bigLine], [bigLine], false, true);98+test('Split string stdout - 0 newlines, many chunks, objectMode', testLines, 1, manyChunks, [manyChunks.join('')], false, true);99+test('Split Uint8Array stdout - n newlines, 1 chunk, objectMode', testLines, 1, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, true);100+test('Split Uint8Array stderr - n newlines, 1 chunk, objectMode', testLines, 2, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, true);101+test('Split Uint8Array stdio[*] - n newlines, 1 chunk, objectMode', testLines, 3, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, true);102+test('Split Uint8Array stdout - no newline, n chunks, objectMode', testLines, 1, ['aaa', 'bbb', 'ccc'], ['aaabbbccc'], true, true);103+test('Split Uint8Array stdout - 0 newlines, 1 chunk, objectMode', testLines, 1, ['aaa'], ['aaa'], true, true);104+test('Split Uint8Array stdout - Windows newlines, objectMode', testLines, 1, ['aaa\r\nbbb\r\nccc'], ['aaa\r\n', 'bbb\r\n', 'ccc'], true, true);105+test('Split Uint8Array stdout - chunk ends with newline, objectMode', testLines, 1, ['aaa\nbbb\nccc\n'], ['aaa\n', 'bbb\n', 'ccc\n'], true, true);106+test('Split Uint8Array stdout - single newline, objectMode', testLines, 1, ['\n'], ['\n'], true, true);107+test('Split Uint8Array stdout - only newlines, objectMode', testLines, 1, ['\n\n\n'], ['\n', '\n', '\n'], true, true);108+test('Split Uint8Array stdout - only Windows newlines, objectMode', testLines, 1, ['\r\n\r\n\r\n'], ['\r\n', '\r\n', '\r\n'], true, true);109+test('Split Uint8Array stdout - line split over multiple chunks, objectMode', testLines, 1, ['aaa\nb', 'b', 'b\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, true);110+test('Split Uint8Array stdout - 0 newlines, big line, objectMode', testLines, 1, [bigLine], [bigLine], true, true);111+test('Split Uint8Array stdout - 0 newlines, many chunks, objectMode', testLines, 1, manyChunks, [manyChunks.join('')], true, true);112 113+// eslint-disable-next-line max-params80-const testBinaryOption = async (t, binary, input, expectedLines) => {114+const testBinaryOption = async (t, binary, input, expectedLines, objectMode) => {115 const lines = [];116 const {stdout} = await execa('noop-fd.js', ['1'], {117 stdout: [84- inputGenerator.bind(undefined, input),85- {transform: resultGenerator.bind(undefined, lines), binary},118+ {transform: inputGenerator.bind(undefined, input), objectMode},119+ {transform: resultGenerator.bind(undefined, lines), objectMode, binary},120 ],121 });88- t.is(stdout, input.join(''));122+ t.is(input.join(''), objectMode ? stdout.join('') : stdout);123 t.deepEqual(lines, expectedLines);124 };125 92-test('Does not split lines when "binary" is true', testBinaryOption, true, ['aaa\nbbb\nccc'], ['aaa\nbbb\nccc']);93-test('Splits lines when "binary" is false', testBinaryOption, false, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc']);94-test('Splits lines when "binary" is undefined', testBinaryOption, undefined, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc']);126+test('Does not split lines when "binary" is true', testBinaryOption, true, ['aaa\nbbb\nccc'], ['aaa\nbbb\nccc'], false);127+test('Splits lines when "binary" is false', testBinaryOption, false, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false);128+test('Splits lines when "binary" is undefined', testBinaryOption, undefined, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false);129+test('Does not split lines when "binary" is true, objectMode', testBinaryOption, true, ['aaa\nbbb\nccc'], ['aaa\nbbb\nccc'], true);130+test('Splits lines when "binary" is false, objectMode', testBinaryOption, false, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true);131+test('Splits lines when "binary" is undefined, objectMode', testBinaryOption, undefined, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true);modified:test/stdio/typed-array.js+3 added-4 removed
1 import test from 'ava';2 import {execa, execaSync} from '../../index.js';3 import {setFixtureDir} from '../helpers/fixtures-dir.js';4 import {getStdio} from '../helpers/stdio.js';5+import {foobarUint8Array} from '../helpers/input.js';6 7 setFixtureDir();8 8-const uint8ArrayFoobar = new TextEncoder().encode('foobar');9-9 const testUint8Array = async (t, index) => {11- const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, uint8ArrayFoobar));10+ const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, foobarUint8Array));11 t.is(stdout, 'foobar');12 };13 14 test('stdin option can be a Uint8Array', testUint8Array, 0);2 unmodified lines17 test('stdio[*] option can be a Uint8Array - sync', testUint8Array, 3);18 19 const testNoUint8ArrayOutput = (t, index, execaMethod) => {20 t.throws(() => {22- execaMethod('empty.js', getStdio(index, uint8ArrayFoobar));21+ execaMethod('empty.js', getStdio(index, foobarUint8Array));22 }, {message: /cannot be a Uint8Array/});23 };24 25 test('stdout option cannot be a Uint8Array', testNoUint8ArrayOutput, 1, execa);3 unmodified linesmodified:test/error.js+13 added-6 removed
1 unmodified line2 import test from 'ava';3 import {execa, execaSync} from '../index.js';4 import {FIXTURES_DIR, setFixtureDir} from './helpers/fixtures-dir.js';5 import {fullStdio, getStdio} from './helpers/stdio.js';6+import {noopGenerator, outputObjectGenerator} from './helpers/generator.js';7 8 const isWindows = process.platform === 'win32';9 10 setFixtureDir();87 unmodified lines98 test('error.message contains the command', async t => {99 await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});100 });101 101-const testStdioMessage = async (t, encoding, all) => {102- const {message} = await t.throwsAsync(execa('echo-fail.js', {...fullStdio, encoding, all}));102+const testStdioMessage = async (t, encoding, all, objectMode) => {103+ const {message} = await t.throwsAsync(execa('echo-fail.js', {...getStdio(1, noopGenerator(objectMode), 4), encoding, all}));104 const output = all ? 'stdout\nstderr' : 'stderr\n\nstdout';105 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));106 };107 107-test('error.message contains stdout/stderr/stdio if available', testStdioMessage, 'utf8', false);108-test('error.message contains stdout/stderr/stdio even with encoding "buffer"', testStdioMessage, 'buffer', false);109-test('error.message contains all if available', testStdioMessage, 'utf8', true);110-test('error.message contains all even with encoding "buffer"', testStdioMessage, 'buffer', true);108+test('error.message contains stdout/stderr/stdio if available', testStdioMessage, 'utf8', false, false);109+test('error.message contains stdout/stderr/stdio even with encoding "buffer"', testStdioMessage, 'buffer', false, false);110+test('error.message contains all if available', testStdioMessage, 'utf8', true, false);111+test('error.message contains all even with encoding "buffer"', testStdioMessage, 'buffer', true, false);112+test('error.message contains stdout/stderr/stdio if available, objectMode', testStdioMessage, 'utf8', false, true);113+test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode', testStdioMessage, 'buffer', false, true);114+test('error.message contains all if available, objectMode', testStdioMessage, 'utf8', true, true);115+test('error.message contains all even with encoding "buffer", objectMode', testStdioMessage, 'buffer', true, true);116 117 const testPartialIgnoreMessage = async (t, index, stdioOption, output) => {118 const {message} = await t.throwsAsync(execa('echo-fail.js', getStdio(index, stdioOption, 4)));119 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));120 };121 122 test('error.message does not contain stdout if not available', testPartialIgnoreMessage, 1, 'ignore', 'stderr');123 test('error.message does not contain stderr if not available', testPartialIgnoreMessage, 2, 'ignore', 'stdout');124+test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator, 'stderr');125+test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator, 'stdout');126 127 const testFullIgnoreMessage = async (t, options, resultProperty) => {128 const {[resultProperty]: message} = await t.throwsAsync(execa('echo-fail.js', options));129 t.false(message.includes('stderr'));158 unmodified linesmodified:test/test.js+8 added-3 removed
5 unmodified lines6 import getNode from 'get-node';7 import which from 'which';8 import {execa, execaSync, execaNode, $} from '../index.js';9 import {setFixtureDir, PATH_KEY, FIXTURES_DIR_URL} from './helpers/fixtures-dir.js';10-import {identity, fullStdio} from './helpers/stdio.js';11-import {stringGenerator} from './helpers/generator.js';10+import {identity, fullStdio, getStdio} from './helpers/stdio.js';11+import {noopGenerator} from './helpers/generator.js';12 13 setFixtureDir();14 process.env.FOO = 'foo';15 25 unmodified lines41 test('cannot return stdin', testNoStdin, execa);42 test('cannot return stdin - sync', testNoStdin, execaSync);43 44 test('cannot return input stdio[*]', async t => {45- const {stdio} = await execa('stdin-fd.js', ['3'], {stdio: ['pipe', 'pipe', 'pipe', stringGenerator()]});45+ const {stdio} = await execa('stdin-fd.js', ['3'], getStdio(3, [['foobar']]));46 t.is(stdio[3], undefined);47 });48 49 if (process.platform === 'win32') {41 unmodified lines91 test('stripFinalNewline: false with stderr - sync', testStripFinalNewline, 2, false, execaSync);92 test('stripFinalNewline: true with stdio[*] - sync', testStripFinalNewline, 3, undefined, execaSync);93 test('stripFinalNewline: false with stdio[*] - sync', testStripFinalNewline, 3, false, execaSync);94 95+test('stripFinalNewline is not used in objectMode', async t => {96+ const {stdout} = await execa('noop-fd.js', ['1', 'foobar\n'], {stripFinalNewline: true, stdout: noopGenerator(true)});97+ t.deepEqual(stdout, ['foobar\n']);98+});99+100 const getPathWithoutLocalDir = () => {101 const newPath = process.env[PATH_KEY].split(path.delimiter).filter(pathDir => !BIN_DIR_REGEXP.test(pathDir)).join(path.delimiter);102 return {[PATH_KEY]: newPath};103 };207 unmodified linesmodified:index.d.ts+84 added-27 removed
16 unmodified lines17 | 'overlapped'18 | 'ignore'19 | 'inherit';20 21-// @todo Use either `Iterable<string>` or `Iterable<Uint8Array>` based on whether `encoding: 'buffer'` is used.21+// @todo Use `string`, `Uint8Array` or `unknown` for both the argument and the return type, based on whether `encoding: 'buffer'` and `objectMode: true` are used.22 // See https://github.com/sindresorhus/execa/issues/69423-type StdioTransform = ((chunks: Iterable<string | Uint8Array>) => AsyncGenerator<string | Uint8Array, void, void>);23+type StdioTransform = ((chunks: Iterable<unknown>) => AsyncGenerator<unknown, void, void>);24 25+type StdioTransformFull = {26+ transform: StdioTransform;27+ binary?: boolean;28+ objectMode?: boolean;29+};30+31 type CommonStdioOption<IsSync extends boolean = boolean> =32 | BaseStdioOption33 | 'ipc'34 | number1 unmodified line36 | URL37 | {file: string}38 | IfAsync<IsSync,39 | StdioTransform34- | {35- transform: StdioTransform;36- binary?: boolean;37- }>;40+ | StdioTransformFull>;41 42 type InputStdioOption<IsSync extends boolean = boolean> =43 | Uint8Array44 | Readable45 | IfAsync<IsSync,43- | Iterable<string | Uint8Array>44- | AsyncIterable<string | Uint8Array>46+ | Iterable<unknown>47+ | AsyncIterable<unknown>48 | ReadableStream>;49 50 type OutputStdioOption<IsSync extends boolean = boolean> =51 | Writable46 unmodified lines98 | undefined;99 type DefaultEncodingOption = 'utf8';100 type BufferEncodingOption = 'buffer';101 102+// Whether `result.stdout|stderr|all` is an array of values due to `objectMode: true`103+type IsObjectStream<104+ StreamIndex extends string,105+ OptionsType extends CommonOptions = CommonOptions,106+> = IsObjectNormalStream<StreamIndex, OptionsType> extends true107+ ? true108+ : IsObjectStdioStream<StreamIndex, OptionsType['stdio']>;109+110+type IsObjectNormalStream<111+ StreamIndex extends string,112+ OptionsType extends CommonOptions = CommonOptions,113+> = IsObjectOutputOptions<StreamOption<StreamIndex, OptionsType>>;114+115+type IsObjectStdioStream<116+ StreamIndex extends string,117+ StdioOptionType extends StdioOptions | undefined,118+> = StdioOptionType extends StdioOptionsArray119+ ? StreamIndex extends keyof StdioOptionType120+ ? StdioOptionType[StreamIndex] extends StdioOption121+ ? IsObjectOutputOptions<StdioOptionType[StreamIndex]>122+ : false123+ : false124+ : false;125+126+type IsObjectOutputOptions<OutputOptions extends StdioOption> = IsObjectOutputOption<OutputOptions extends StdioSingleOption[]127+ ? OutputOptions[number]128+ : OutputOptions129+>;130+131+type IsObjectOutputOption<OutputOption extends StdioSingleOption> = OutputOption extends StdioTransformFull132+ ? BooleanObjectMode<OutputOption['objectMode']>133+ : false;134+135+type BooleanObjectMode<ObjectModeOption extends StdioTransformFull['objectMode']> = ObjectModeOption extends true ? true : false;136+137 // Whether `result.stdout|stderr|all` is `undefined`, excluding the `buffer` option138 type IgnoresStreamResult<139 StreamIndex extends string,140 OptionsType extends CommonOptions = CommonOptions,141 > = IgnoresNormalPropertyResult<StreamIndex, OptionsType> extends true142 ? true143 : IgnoresStdioPropertyResult<StreamIndex, OptionsType['stdio']>;144 145+// `result.stdin` is always `undefined`146+// When using `stdout: 'inherit'`, or `'ignore'`, etc. , `result.stdout` is `undefined`147+// Same with `stderr`148 type IgnoresNormalPropertyResult<149 StreamIndex extends string,150 OptionsType extends CommonOptions = CommonOptions,110- // `result.stdin` is always `undefined`111-> = StreamIndex extends '0' ? true112- // When using `stdout: 'inherit'`, or `'ignore'`, etc. , `result.stdout` is `undefined`113- : StreamIndex extends '1' ? OptionsType['stdout'] extends NoOutputStdioOption ? true : false114- // Same with `stderr`115- : StreamIndex extends '2' ? OptionsType['stderr'] extends NoOutputStdioOption ? true : false116- // Otherwise117- : false;151+> = StreamIndex extends '0'152+ ? true153+ : IgnoresNormalProperty<StreamOption<StreamIndex, OptionsType>>;154 155+type StreamOption<156+ StreamIndex extends string,157+ OptionsType extends CommonOptions = CommonOptions,158+> = StreamIndex extends '0' ? OptionsType['stdin']159+ : StreamIndex extends '1' ? OptionsType['stdout']160+ : StreamIndex extends '2' ? OptionsType['stderr']161+ : undefined;162+163+type IgnoresNormalProperty<OutputOptions extends StdioOption> = OutputOptions extends NoOutputStdioOption ? true : false;164+165 type IgnoresStdioPropertyResult<166 StreamIndex extends string,167 StdioOptionType extends StdioOptions | undefined,168 // Same but with `stdio: 'ignore'`30 unmodified lines199 // Type of `result.stdout|stderr`200 type StdioOutput<201 StreamIndex extends string,202 OptionsType extends CommonOptions = CommonOptions,157-> = StdioOutputResult<IgnoresStreamOutput<StreamIndex, OptionsType>, OptionsType>;203+> = StdioOutputResult<StreamIndex, IgnoresStreamOutput<StreamIndex, OptionsType>, OptionsType>;204 205 type StdioOutputResult<206+ StreamIndex extends string,207 StreamOutputIgnored extends boolean,208 OptionsType extends CommonOptions = CommonOptions,209 > = StreamOutputIgnored extends true210 ? undefined164- : StreamResult<OptionsType>;211+ : StreamEncoding<IsObjectStream<StreamIndex, OptionsType>, OptionsType['encoding']>;212 166-type StreamResult<OptionsType extends CommonOptions = CommonOptions> = StreamEncoding<OptionsType['encoding']>;213+type StreamEncoding<214+ IsObjectResult extends boolean,215+ Encoding extends CommonOptions['encoding'],216+> = IsObjectResult extends true ? unknown[]217+ : Encoding extends 'buffer' ? Uint8Array : string;218 168-type StreamEncoding<Encoding extends CommonOptions['encoding']> = Encoding extends 'buffer' ? Uint8Array : string;169-219 // Type of `result.all`220 type AllOutput<OptionsType extends Options = Options> = AllOutputProperty<OptionsType['all'], OptionsType>;221 222 type AllOutputProperty<223 AllOption extends Options['all'] = Options['all'],224 OptionsType extends Options = Options,225 > = AllOption extends true177- ? IgnoresStreamOutput<'1', OptionsType> extends true178- ? StdioOutput<'2', OptionsType>179- : StdioOutput<'1', OptionsType>226+ ? StdioOutput<AllUsesStdout<OptionsType> extends true ? '1' : '2', OptionsType>227 : undefined;228 229+type AllUsesStdout<OptionsType extends Options = Options> = IgnoresStreamOutput<'1', OptionsType> extends true230+ ? false231+ : IgnoresStreamOutput<'2', OptionsType> extends true232+ ? true233+ : IsObjectStream<'2', OptionsType> extends true234+ ? false235+ : IsObjectStream<'1', OptionsType>;236+237 // Type of `result.stdio`238 type StdioArrayOutput<OptionsType extends CommonOptions = CommonOptions> = MapStdioOptions<239 OptionsType['stdio'] extends StdioOptionsArray ? OptionsType['stdio'] : ['pipe', 'pipe', 'pipe'],240 OptionsType371 unmodified lines612 613 /**614 The output of the process on `stdout`.615 561- This is `undefined` if the `stdout` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).616+ This is `undefined` if the `stdout` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `stdout` option is a transform in object mode.617 */618 stdout: StdioOutput<'1', OptionsType>;619 620 /**621 The output of the process on `stderr`.622 568- This is `undefined` if the `stderr` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).623+ This is `undefined` if the `stderr` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `stderr` option is a transform in object mode.624 */625 stderr: StdioOutput<'2', OptionsType>;626 627 /**628 The output of the process on `stdin`, `stdout`, `stderr` and other file descriptors.629 575- Items are `undefined` when their corresponding `stdio` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).630+ Items are `undefined` when their corresponding `stdio` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). Items are arrays when their corresponding `stdio` option is a transform in object mode.631 */632 stdio: StdioArrayOutput<OptionsType>;633 634 /**46 unmodified lines681 682 This is `undefined` if either:683 - the `all` option is `false` (default value)684 - both `stdout` and `stderr` options are set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)685+686+ This is an array if either the `stdout` or `stderr` option is a transform in object mode.687 */688 all: IfAsync<IsSync, AllOutput<OptionsType>>;689 // Workaround for a TypeScript bug: https://github.com/microsoft/TypeScript/issues/57062690 } & {};606 unmodified linesmodified:index.js+4 added
83 unmodified lines84 if (value === undefined || value === null) {85 return;86 }87 88+ if (Array.isArray(value)) {89+ return value;90+ }91+92 if (Buffer.isBuffer(value)) {93 value = bufferToUint8Array(value);94 }95 225 unmodified linesmodified:index.test-d.ts+204 added-96 removed
19 unmodified lines20 type ExecaSyncReturnValue,21 type ExecaSyncError,22 } from './index.js';23 24+type AnySyncChunk = string | Uint8Array | undefined;25+type AnyChunk = AnySyncChunk | unknown[];26 expectType<Readable | null>({} as ExecaChildProcess['stdout']);27 expectType<Readable | null>({} as ExecaChildProcess['stderr']);28 expectType<Readable | undefined>({} as ExecaChildProcess['all']);27-expectType<string | Uint8Array | undefined>({} as ExecaReturnValue['stdout']);28-expectType<string | Uint8Array | undefined>({} as ExecaReturnValue['stderr']);29-expectType<string | Uint8Array | undefined>({} as ExecaReturnValue['all']);30-expectType<[undefined, string | Uint8Array | undefined, string | Uint8Array | undefined]>({} as ExecaReturnValue['stdio']);31-expectType<string | Uint8Array | undefined>({} as ExecaSyncReturnValue['stdout']);32-expectType<string | Uint8Array | undefined>({} as ExecaSyncReturnValue['stderr']);33-expectType<[undefined, string | Uint8Array | undefined, string | Uint8Array | undefined]>({} as ExecaSyncReturnValue['stdio']);29+expectType<AnyChunk>({} as ExecaReturnValue['stdout']);30+expectType<AnyChunk>({} as ExecaReturnValue['stderr']);31+expectType<AnyChunk>({} as ExecaReturnValue['all']);32+expectType<[undefined, AnyChunk, AnyChunk]>({} as ExecaReturnValue['stdio']);33+expectType<AnySyncChunk>({} as ExecaSyncReturnValue['stdout']);34+expectType<AnySyncChunk>({} as ExecaSyncReturnValue['stderr']);35+expectType<[undefined, AnySyncChunk, AnySyncChunk]>({} as ExecaSyncReturnValue['stdio']);36 37+const objectGenerator = async function * (lines: Iterable<unknown>) {38+ for await (const line of lines) {39+ yield JSON.parse(line as string) as object;40+ }41+};42+43+const unknownArrayGenerator = async function * (lines: Iterable<unknown>) {44+ for await (const line of lines) {45+ yield line;46+ }47+};48+49+const booleanGenerator = async function * (lines: Iterable<boolean>) {50+ for await (const line of lines) {51+ yield line;52+ }53+};54+55+const arrayGenerator = async function * (lines: string[]) {56+ for await (const line of lines) {57+ yield line;58+ }59+};60+61+const invalidReturnGenerator = async function * (lines: Iterable<string>) {62+ for await (const line of lines) {63+ yield line;64+ }65+66+ return false;67+};68+69+const syncGenerator = function * (lines: Iterable<string>) {70+ for (const line of lines) {71+ yield line;72+ }73+74+ return false;75+};76+77 try {78 const execaPromise = execa('unicorns', {all: true});79 execaPromise.cancel();80 245 unmodified lines326 expectType<undefined>(noBufferFd3Result.stdio[3]);327 328 const ignoreFd3Result = await execa('unicorns', {stdio: ['pipe', 'pipe', 'pipe', 'ignore']});329 expectType<undefined>(ignoreFd3Result.stdio[3]);330+331+ const objectTransformStdoutResult = await execa('unicorns', {stdout: {transform: objectGenerator, objectMode: true}});332+ expectType<unknown[]>(objectTransformStdoutResult.stdout);333+ expectType<[undefined, unknown[], string]>(objectTransformStdoutResult.stdio);334+335+ const objectTransformStderrResult = await execa('unicorns', {stderr: {transform: objectGenerator, objectMode: true}});336+ expectType<unknown[]>(objectTransformStderrResult.stderr);337+ expectType<[undefined, string, unknown[]]>(objectTransformStderrResult.stdio);338+339+ const objectTransformStdioResult = await execa('unicorns', {stdio: ['pipe', 'pipe', {transform: objectGenerator, objectMode: true}]});340+ expectType<unknown[]>(objectTransformStdioResult.stderr);341+ expectType<[undefined, string, unknown[]]>(objectTransformStdioResult.stdio);342+343+ const singleObjectTransformStdoutResult = await execa('unicorns', {stdout: [{transform: objectGenerator, objectMode: true}]});344+ expectType<unknown[]>(singleObjectTransformStdoutResult.stdout);345+ expectType<[undefined, unknown[], string]>(singleObjectTransformStdoutResult.stdio);346+347+ const manyObjectTransformStdoutResult = await execa('unicorns', {stdout: [{transform: objectGenerator, objectMode: true}, {transform: objectGenerator, objectMode: true}]});348+ expectType<unknown[]>(manyObjectTransformStdoutResult.stdout);349+ expectType<[undefined, unknown[], string]>(manyObjectTransformStdoutResult.stdio);350+351+ const falseObjectTransformStdoutResult = await execa('unicorns', {stdout: {transform: objectGenerator, objectMode: false}});352+ expectType<string>(falseObjectTransformStdoutResult.stdout);353+ expectType<[undefined, string, string]>(falseObjectTransformStdoutResult.stdio);354+355+ const falseObjectTransformStderrResult = await execa('unicorns', {stderr: {transform: objectGenerator, objectMode: false}});356+ expectType<string>(falseObjectTransformStderrResult.stderr);357+ expectType<[undefined, string, string]>(falseObjectTransformStderrResult.stdio);358+359+ const falseObjectTransformStdioResult = await execa('unicorns', {stdio: ['pipe', 'pipe', {transform: objectGenerator, objectMode: false}]});360+ expectType<string>(falseObjectTransformStdioResult.stderr);361+ expectType<[undefined, string, string]>(falseObjectTransformStdioResult.stdio);362+363+ const undefinedObjectTransformStdoutResult = await execa('unicorns', {stdout: {transform: objectGenerator}});364+ expectType<string>(undefinedObjectTransformStdoutResult.stdout);365+ expectType<[undefined, string, string]>(undefinedObjectTransformStdoutResult.stdio);366+367+ const noObjectTransformStdoutResult = await execa('unicorns', {stdout: objectGenerator});368+ expectType<string>(noObjectTransformStdoutResult.stdout);369+ expectType<[undefined, string, string]>(noObjectTransformStdoutResult.stdio);370+371+ const trueTrueObjectTransformResult = await execa('unicorns', {stdout: {transform: objectGenerator, objectMode: true}, stderr: {transform: objectGenerator, objectMode: true}, all: true});372+ expectType<unknown[]>(trueTrueObjectTransformResult.stdout);373+ expectType<unknown[]>(trueTrueObjectTransformResult.stderr);374+ expectType<unknown[]>(trueTrueObjectTransformResult.all);375+ expectType<[undefined, unknown[], unknown[]]>(trueTrueObjectTransformResult.stdio);376+377+ const trueFalseObjectTransformResult = await execa('unicorns', {stdout: {transform: objectGenerator, objectMode: true}, stderr: {transform: objectGenerator, objectMode: false}, all: true});378+ expectType<unknown[]>(trueFalseObjectTransformResult.stdout);379+ expectType<string>(trueFalseObjectTransformResult.stderr);380+ expectType<unknown[]>(trueFalseObjectTransformResult.all);381+ expectType<[undefined, unknown[], string]>(trueFalseObjectTransformResult.stdio);382+383+ const falseTrueObjectTransformResult = await execa('unicorns', {stdout: {transform: objectGenerator, objectMode: false}, stderr: {transform: objectGenerator, objectMode: true}, all: true});384+ expectType<string>(falseTrueObjectTransformResult.stdout);385+ expectType<unknown[]>(falseTrueObjectTransformResult.stderr);386+ expectType<unknown[]>(falseTrueObjectTransformResult.all);387+ expectType<[undefined, string, unknown[]]>(falseTrueObjectTransformResult.stdio);388+389+ const falseFalseObjectTransformResult = await execa('unicorns', {stdout: {transform: objectGenerator, objectMode: false}, stderr: {transform: objectGenerator, objectMode: false}, all: true});390+ expectType<string>(falseFalseObjectTransformResult.stdout);391+ expectType<string>(falseFalseObjectTransformResult.stderr);392+ expectType<string>(falseFalseObjectTransformResult.all);393+ expectType<[undefined, string, string]>(falseFalseObjectTransformResult.stdio);394 } catch (error: unknown) {395 const execaError = error as ExecaError;396 397 expectType<string>(execaError.message);84 unmodified lines482 const streamStderrError = error as ExecaError<{stderr: typeof process.stdout; all: true}>;483 expectType<string>(streamStderrError.stdout);484 expectType<undefined>(streamStderrError.stderr);485 expectType<string>(streamStderrError.all);486+487+ const objectTransformStdoutError = error as ExecaError<{stdout: {transform: typeof objectGenerator; objectMode: true}}>;488+ expectType<unknown[]>(objectTransformStdoutError.stdout);489+ expectType<[undefined, unknown[], string]>(objectTransformStdoutError.stdio);490+491+ const objectTransformStderrError = error as ExecaError<{stderr: {transform: typeof objectGenerator; objectMode: true}}>;492+ expectType<unknown[]>(objectTransformStderrError.stderr);493+ expectType<[undefined, string, unknown[]]>(objectTransformStderrError.stdio);494+495+ const objectTransformStdioError = error as ExecaError<{stdio: ['pipe', 'pipe', {transform: typeof objectGenerator; objectMode: true}]}>;496+ expectType<unknown[]>(objectTransformStdioError.stderr);497+ expectType<[undefined, string, unknown[]]>(objectTransformStdioError.stdio);498+499+ const falseObjectTransformStdoutError = error as ExecaError<{stdout: {transform: typeof objectGenerator; objectMode: false}}>;500+ expectType<string>(falseObjectTransformStdoutError.stdout);501+ expectType<[undefined, string, string]>(falseObjectTransformStdoutError.stdio);502+503+ const falseObjectTransformStderrError = error as ExecaError<{stderr: {transform: typeof objectGenerator; objectMode: false}}>;504+ expectType<string>(falseObjectTransformStderrError.stderr);505+ expectType<[undefined, string, string]>(falseObjectTransformStderrError.stdio);506+507+ const falseObjectTransformStdioError = error as ExecaError<{stdio: ['pipe', 'pipe', {transform: typeof objectGenerator; objectMode: false}]}>;508+ expectType<string>(falseObjectTransformStdioError.stderr);509+ expectType<[undefined, string, string]>(falseObjectTransformStdioError.stdio);510 }511 512 const rejectsResult = await execa('unicorns');513 expectError(rejectsResult.stack);174 unmodified lines688 const binaryGenerator = function * () {689 yield new Uint8Array(0);690 };691 562-const numberGenerator = function * () {563- yield 0;564-};565-692 const asyncStringGenerator = async function * () {693 yield '';694 };695 696 const fileUrl = new URL('file:///test');697 572-const stringOrUint8ArrayGenerator = async function * (lines: Iterable<string | Uint8Array>) {573- for await (const line of lines) {574- yield line;575- }576-};577-578-const booleanGenerator = async function * (lines: Iterable<boolean>) {579- for await (const line of lines) {580- yield line;581- }582-};583-584-const arrayGenerator = async function * (lines: string[]) {585- for await (const line of lines) {586- yield line;587- }588-};589-590-const invalidReturnGenerator = async function * (lines: Iterable<string>) {591- for await (const line of lines) {592- yield line;593- }594-595- return false;596-};597-598-const syncGenerator = function * (lines: Iterable<string>) {599- for (const line of lines) {600- yield line;601- }602-603- return false;604-};605-698 expectAssignable<Options>({cleanup: false});699 expectNotAssignable<SyncOptions>({cleanup: false});700 expectAssignable<SyncOptions>({preferLocal: false});701 53 unmodified lines755 execa('unicorns', {stdin: [new Readable()]});756 execaSync('unicorns', {stdin: [new Readable()]});757 expectError(execa('unicorns', {stdin: new Writable()}));758 expectError(execaSync('unicorns', {stdin: new Writable()}));667-expectError(execa('unicorns', {stdin: [new Writable()]}));759 expectError(execaSync('unicorns', {stdin: [new Writable()]}));760 execa('unicorns', {stdin: new ReadableStream()});761 expectError(execaSync('unicorns', {stdin: new ReadableStream()}));762 execa('unicorns', {stdin: [new ReadableStream()]});763 expectError(execaSync('unicorns', {stdin: [new ReadableStream()]}));764 expectError(execa('unicorns', {stdin: new WritableStream()}));765 expectError(execaSync('unicorns', {stdin: new WritableStream()}));675-expectError(execa('unicorns', {stdin: [new WritableStream()]}));766 expectError(execaSync('unicorns', {stdin: [new WritableStream()]}));767 execa('unicorns', {stdin: new Uint8Array()});768 execaSync('unicorns', {stdin: new Uint8Array()});769+execa('unicorns', {stdin: [['foo', 'bar']]});770+expectError(execaSync('unicorns', {stdin: [['foo', 'bar']]}));771+execa('unicorns', {stdin: [[new Uint8Array(), new Uint8Array()]]});772+expectError(execaSync('unicorns', {stdin: [[new Uint8Array(), new Uint8Array()]]}));773+execa('unicorns', {stdin: [[{}, {}]]});774+expectError(execaSync('unicorns', {stdin: [[{}, {}]]}));775 execa('unicorns', {stdin: emptyStringGenerator()});776 expectError(execaSync('unicorns', {stdin: emptyStringGenerator()}));777 execa('unicorns', {stdin: [emptyStringGenerator()]});778 expectError(execaSync('unicorns', {stdin: [emptyStringGenerator()]}));4 unmodified lines783 execa('unicorns', {stdin: asyncStringGenerator()});784 expectError(execaSync('unicorns', {stdin: asyncStringGenerator()}));785 execa('unicorns', {stdin: [asyncStringGenerator()]});786 expectError(execaSync('unicorns', {stdin: [asyncStringGenerator()]}));691-expectError(execa('unicorns', {stdin: numberGenerator()}));692-expectError(execaSync('unicorns', {stdin: numberGenerator()}));693-expectError(execa('unicorns', {stdin: [numberGenerator()]}));694-expectError(execaSync('unicorns', {stdin: [numberGenerator()]}));787 execa('unicorns', {stdin: fileUrl});788 execaSync('unicorns', {stdin: fileUrl});789 execa('unicorns', {stdin: [fileUrl]});790 execaSync('unicorns', {stdin: [fileUrl]});4 unmodified lines795 execa('unicorns', {stdin: 1});796 execaSync('unicorns', {stdin: 1});797 execa('unicorns', {stdin: [1]});798 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]}));799+execa('unicorns', {stdin: unknownArrayGenerator});800+expectError(execaSync('unicorns', {stdin: unknownArrayGenerator}));801+execa('unicorns', {stdin: [unknownArrayGenerator]});802+expectError(execaSync('unicorns', {stdin: [unknownArrayGenerator]}));803 expectError(execa('unicorns', {stdin: booleanGenerator}));804 expectError(execa('unicorns', {stdin: arrayGenerator}));805 expectError(execa('unicorns', {stdin: invalidReturnGenerator}));806 expectError(execa('unicorns', {stdin: syncGenerator}));715-execa('unicorns', {stdin: {transform: stringOrUint8ArrayGenerator}});716-expectError(execaSync('unicorns', {stdin: {transform: stringOrUint8ArrayGenerator}}));717-execa('unicorns', {stdin: [{transform: stringOrUint8ArrayGenerator}]});718-expectError(execaSync('unicorns', {stdin: [{transform: stringOrUint8ArrayGenerator}]}));807+execa('unicorns', {stdin: {transform: unknownArrayGenerator}});808+expectError(execaSync('unicorns', {stdin: {transform: unknownArrayGenerator}}));809+execa('unicorns', {stdin: [{transform: unknownArrayGenerator}]});810+expectError(execaSync('unicorns', {stdin: [{transform: unknownArrayGenerator}]}));811 expectError(execa('unicorns', {stdin: {transform: booleanGenerator}}));812 expectError(execa('unicorns', {stdin: {transform: arrayGenerator}}));813 expectError(execa('unicorns', {stdin: {transform: invalidReturnGenerator}}));814 expectError(execa('unicorns', {stdin: {transform: syncGenerator}}));815 expectError(execa('unicorns', {stdin: {}}));816 expectError(execa('unicorns', {stdin: {binary: true}}));817+expectError(execa('unicorns', {stdin: {objectMode: true}}));725-execa('unicorns', {stdin: {transform: stringOrUint8ArrayGenerator, binary: true}});726-expectError(execa('unicorns', {stdin: {transform: stringOrUint8ArrayGenerator, binary: 'true'}}));818+execa('unicorns', {stdin: {transform: unknownArrayGenerator, binary: true}});819+expectError(execa('unicorns', {stdin: {transform: unknownArrayGenerator, binary: 'true'}}));820+execa('unicorns', {stdin: {transform: unknownArrayGenerator, objectMode: true}});821+expectError(execa('unicorns', {stdin: {transform: unknownArrayGenerator, objectMode: 'true'}}));822 execa('unicorns', {stdin: undefined});823 execaSync('unicorns', {stdin: undefined});824 execa('unicorns', {stdin: [undefined]});825 execaSync('unicorns', {stdin: [undefined]});50 unmodified lines876 execa('unicorns', {stdout: 1});877 execaSync('unicorns', {stdout: 1});878 execa('unicorns', {stdout: [1]});879 execaSync('unicorns', {stdout: [1]});785-execa('unicorns', {stdout: stringOrUint8ArrayGenerator});786-expectError(execaSync('unicorns', {stdout: stringOrUint8ArrayGenerator}));787-execa('unicorns', {stdout: [stringOrUint8ArrayGenerator]});788-expectError(execaSync('unicorns', {stdout: [stringOrUint8ArrayGenerator]}));880+execa('unicorns', {stdout: unknownArrayGenerator});881+expectError(execaSync('unicorns', {stdout: unknownArrayGenerator}));882+execa('unicorns', {stdout: [unknownArrayGenerator]});883+expectError(execaSync('unicorns', {stdout: [unknownArrayGenerator]}));884 expectError(execa('unicorns', {stdout: booleanGenerator}));885 expectError(execa('unicorns', {stdout: arrayGenerator}));886 expectError(execa('unicorns', {stdout: invalidReturnGenerator}));887 expectError(execa('unicorns', {stdout: syncGenerator}));793-execa('unicorns', {stdout: {transform: stringOrUint8ArrayGenerator}});794-expectError(execaSync('unicorns', {stdout: {transform: stringOrUint8ArrayGenerator}}));795-execa('unicorns', {stdout: [{transform: stringOrUint8ArrayGenerator}]});796-expectError(execaSync('unicorns', {stdout: [{transform: stringOrUint8ArrayGenerator}]}));888+execa('unicorns', {stdout: {transform: unknownArrayGenerator}});889+expectError(execaSync('unicorns', {stdout: {transform: unknownArrayGenerator}}));890+execa('unicorns', {stdout: [{transform: unknownArrayGenerator}]});891+expectError(execaSync('unicorns', {stdout: [{transform: unknownArrayGenerator}]}));892 expectError(execa('unicorns', {stdout: {transform: booleanGenerator}}));893 expectError(execa('unicorns', {stdout: {transform: arrayGenerator}}));894 expectError(execa('unicorns', {stdout: {transform: invalidReturnGenerator}}));895 expectError(execa('unicorns', {stdout: {transform: syncGenerator}}));896 expectError(execa('unicorns', {stdout: {}}));897 expectError(execa('unicorns', {stdout: {binary: true}}));898+expectError(execa('unicorns', {stdout: {objectMode: true}}));803-execa('unicorns', {stdout: {transform: stringOrUint8ArrayGenerator, binary: true}});804-expectError(execa('unicorns', {stdout: {transform: stringOrUint8ArrayGenerator, binary: 'true'}}));899+execa('unicorns', {stdout: {transform: unknownArrayGenerator, binary: true}});900+expectError(execa('unicorns', {stdout: {transform: unknownArrayGenerator, binary: 'true'}}));901+execa('unicorns', {stdout: {transform: unknownArrayGenerator, objectMode: true}});902+expectError(execa('unicorns', {stdout: {transform: unknownArrayGenerator, objectMode: 'true'}}));903 execa('unicorns', {stdout: undefined});904 execaSync('unicorns', {stdout: undefined});905 execa('unicorns', {stdout: [undefined]});906 execaSync('unicorns', {stdout: [undefined]});50 unmodified lines957 execa('unicorns', {stderr: 1});958 execaSync('unicorns', {stderr: 1});959 execa('unicorns', {stderr: [1]});960 execaSync('unicorns', {stderr: [1]});863-execa('unicorns', {stderr: stringOrUint8ArrayGenerator});864-expectError(execaSync('unicorns', {stderr: stringOrUint8ArrayGenerator}));865-execa('unicorns', {stderr: [stringOrUint8ArrayGenerator]});866-expectError(execaSync('unicorns', {stderr: [stringOrUint8ArrayGenerator]}));961+execa('unicorns', {stderr: unknownArrayGenerator});962+expectError(execaSync('unicorns', {stderr: unknownArrayGenerator}));963+execa('unicorns', {stderr: [unknownArrayGenerator]});964+expectError(execaSync('unicorns', {stderr: [unknownArrayGenerator]}));965 expectError(execa('unicorns', {stderr: booleanGenerator}));966 expectError(execa('unicorns', {stderr: arrayGenerator}));967 expectError(execa('unicorns', {stderr: invalidReturnGenerator}));968 expectError(execa('unicorns', {stderr: syncGenerator}));871-execa('unicorns', {stderr: {transform: stringOrUint8ArrayGenerator}});872-expectError(execaSync('unicorns', {stderr: {transform: stringOrUint8ArrayGenerator}}));873-execa('unicorns', {stderr: [{transform: stringOrUint8ArrayGenerator}]});874-expectError(execaSync('unicorns', {stderr: [{transform: stringOrUint8ArrayGenerator}]}));969+execa('unicorns', {stderr: {transform: unknownArrayGenerator}});970+expectError(execaSync('unicorns', {stderr: {transform: unknownArrayGenerator}}));971+execa('unicorns', {stderr: [{transform: unknownArrayGenerator}]});972+expectError(execaSync('unicorns', {stderr: [{transform: unknownArrayGenerator}]}));973 expectError(execa('unicorns', {stderr: {transform: booleanGenerator}}));974 expectError(execa('unicorns', {stderr: {transform: arrayGenerator}}));975 expectError(execa('unicorns', {stderr: {transform: invalidReturnGenerator}}));976 expectError(execa('unicorns', {stderr: {transform: syncGenerator}}));977 expectError(execa('unicorns', {stderr: {}}));978 expectError(execa('unicorns', {stderr: {binary: true}}));979+expectError(execa('unicorns', {stderr: {objectMode: true}}));881-execa('unicorns', {stderr: {transform: stringOrUint8ArrayGenerator, binary: true}});882-expectError(execa('unicorns', {stderr: {transform: stringOrUint8ArrayGenerator, binary: 'true'}}));980+execa('unicorns', {stderr: {transform: unknownArrayGenerator, binary: true}});981+expectError(execa('unicorns', {stderr: {transform: unknownArrayGenerator, binary: 'true'}}));982+execa('unicorns', {stderr: {transform: unknownArrayGenerator, objectMode: true}});983+expectError(execa('unicorns', {stderr: {transform: unknownArrayGenerator, objectMode: 'true'}}));984 execa('unicorns', {stderr: undefined});985 execaSync('unicorns', {stderr: undefined});986 execa('unicorns', {stderr: [undefined]});987 execaSync('unicorns', {stderr: [undefined]});28 unmodified lines1016 expectError(execa('unicorns', {stdio: 'ipc'}));1017 expectError(execaSync('unicorns', {stdio: 'ipc'}));1018 expectError(execa('unicorns', {stdio: 1}));1019 expectError(execaSync('unicorns', {stdio: 1}));919-expectError(execa('unicorns', {stdio: stringOrUint8ArrayGenerator}));920-expectError(execaSync('unicorns', {stdio: stringOrUint8ArrayGenerator}));921-expectError(execa('unicorns', {stdio: {transform: stringOrUint8ArrayGenerator}}));922-expectError(execaSync('unicorns', {stdio: {transform: stringOrUint8ArrayGenerator}}));1020+expectError(execa('unicorns', {stdio: unknownArrayGenerator}));1021+expectError(execaSync('unicorns', {stdio: unknownArrayGenerator}));1022+expectError(execa('unicorns', {stdio: {transform: unknownArrayGenerator}}));1023+expectError(execaSync('unicorns', {stdio: {transform: unknownArrayGenerator}}));1024 expectError(execa('unicorns', {stdio: fileUrl}));1025 expectError(execaSync('unicorns', {stdio: fileUrl}));1026 expectError(execa('unicorns', {stdio: {file: './test'}}));1027 expectError(execaSync('unicorns', {stdio: {file: './test'}}));24 unmodified lines1052 execa('unicorns', {stdio: [['pipe'], ['pipe'], [new Writable()]]});1053 execaSync('unicorns', {stdio: [['pipe'], ['pipe'], [new Writable()]]});1054 expectError(execa('unicorns', {stdio: [new Writable(), 'pipe', 'pipe']}));1055 expectError(execaSync('unicorns', {stdio: [new Writable(), 'pipe', 'pipe']}));955-expectError(execa('unicorns', {stdio: [[new Writable()], ['pipe'], ['pipe']]}));1056 expectError(execaSync('unicorns', {stdio: [[new Writable()], ['pipe'], ['pipe']]}));1057 expectError(execa('unicorns', {stdio: ['pipe', new Readable(), 'pipe']}));1058 expectError(execaSync('unicorns', {stdio: ['pipe', new Readable(), 'pipe']}));1059 expectError(execa('unicorns', {stdio: [['pipe'], [new Readable()], ['pipe']]}));10 unmodified lines1070 'ignore',1071 'inherit',1072 process.stdin,1073 1,974- stringOrUint8ArrayGenerator,975- {transform: stringOrUint8ArrayGenerator},976- {transform: stringOrUint8ArrayGenerator, binary: true},1074+ unknownArrayGenerator,1075+ {transform: unknownArrayGenerator},1076+ {transform: unknownArrayGenerator, binary: true},1077+ {transform: unknownArrayGenerator, objectMode: true},1078 undefined,1079 fileUrl,1080 {file: './test'},1081 new Writable(),21 unmodified lines1103 new Readable(),1104 new Uint8Array(),1105 ],1106 });1006-expectError(execaSync('unicorns', {stdio: [stringOrUint8ArrayGenerator]}));1007-expectError(execaSync('unicorns', {stdio: [{transform: stringOrUint8ArrayGenerator}]}));1107+expectError(execaSync('unicorns', {stdio: [unknownArrayGenerator]}));1108+expectError(execaSync('unicorns', {stdio: [{transform: unknownArrayGenerator}]}));1109 expectError(execaSync('unicorns', {stdio: [new WritableStream()]}));1110 expectError(execaSync('unicorns', {stdio: [new ReadableStream()]}));1111 expectError(execaSync('unicorns', {stdio: [emptyStringGenerator()]}));1112 expectError(execaSync('unicorns', {stdio: [asyncStringGenerator()]}));6 unmodified lines1119 ['ignore'],1120 ['inherit'],1121 [process.stdin],1122 [1],1022- [stringOrUint8ArrayGenerator],1023- [{transform: stringOrUint8ArrayGenerator}],1024- [{transform: stringOrUint8ArrayGenerator, binary: true}],1123+ [unknownArrayGenerator],1124+ [{transform: unknownArrayGenerator}],1125+ [{transform: unknownArrayGenerator, binary: true}],1126+ [{transform: unknownArrayGenerator, objectMode: true}],1127 [undefined],1128 [fileUrl],1129 [{file: './test'}],1130 [new Writable()],1131 [new Readable()],1132 [new WritableStream()],1133 [new ReadableStream()],1134 [new Uint8Array()],1135+ [['foo', 'bar']],1136+ [[new Uint8Array(), new Uint8Array()]],1137+ [[{}, {}]],1138 [emptyStringGenerator()],1139 [asyncStringGenerator()],1140 ],1141 });14 unmodified lines1156 [new Readable()],1157 [new Uint8Array()],1158 ],1159 });1055-expectError(execaSync('unicorns', {stdio: [[stringOrUint8ArrayGenerator]]}));1056-expectError(execaSync('unicorns', {stdio: [[{transform: stringOrUint8ArrayGenerator}]]}));1160+expectError(execaSync('unicorns', {stdio: [[unknownArrayGenerator]]}));1161+expectError(execaSync('unicorns', {stdio: [[{transform: unknownArrayGenerator}]]}));1162 expectError(execaSync('unicorns', {stdio: [[new WritableStream()]]}));1163 expectError(execaSync('unicorns', {stdio: [[new ReadableStream()]]}));1164+expectError(execaSync('unicorns', {stdio: [[['foo', 'bar']]]}));1165+expectError(execaSync('unicorns', {stdio: [[[new Uint8Array(), new Uint8Array()]]]}));1166+expectError(execaSync('unicorns', {stdio: [[[{}, {}]]]}));1167 expectError(execaSync('unicorns', {stdio: [[emptyStringGenerator()]]}));1168 expectError(execaSync('unicorns', {stdio: [[asyncStringGenerator()]]}));1169 execa('unicorns', {serialization: 'advanced'});1170 expectError(execaSync('unicorns', {serialization: 'advanced'}));139 unmodified linesmodified:readme.md+10 added-8 removed
45 unmodified lines46 - [Scripts interface](#scripts-interface), like `zx`.47 - Improved [Windows support](https://github.com/IndigoUnited/node-cross-spawn#why), including [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries.48 - Executes [locally installed binaries](#preferlocal) without `npx`.49 - [Cleans up](#cleanup) child processes when the parent process ends.50-- Redirect [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1) to files, streams, iterables, strings or `Uint8Array`.50+- Redirect [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1) from/to files, streams, iterables, strings, `Uint8Array` or [objects](docs/transform.md#object-mode).51 - [Transform](docs/transform.md) `stdin`/`stdout`/`stderr` with simple functions.52 - Iterate over [each text line](docs/transform.md#binary-data) output by the process.53 - [Graceful termination](#optionsforcekillaftertimeout).54 - Get [interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal.355 unmodified lines410 This is `undefined` when the process could not be spawned or was terminated by a [signal](#signal-1).411 412 #### stdout413 414-Type: `string | Uint8Array | undefined`414+Type: `string | Uint8Array | unknown[] | undefined`415 416 The output of the process on `stdout`.417 418-This is `undefined` if the [`stdout`](#stdout-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).418+This is `undefined` if the [`stdout`](#stdout-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `stdout` option is a [transform in object mode](docs/transform.md#object-mode).419 420 #### stderr421 422-Type: `string | Uint8Array | undefined`422+Type: `string | Uint8Array | unknown[] | undefined`423 424 The output of the process on `stderr`.425 426-This is `undefined` if the [`stderr`](#stderr-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).426+This is `undefined` if the [`stderr`](#stderr-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `stderr` option is a [transform in object mode](docs/transform.md#object-mode).427 428 #### all429 430-Type: `string | Uint8Array | undefined`430+Type: `string | Uint8Array | unknown[] | undefined`431 432 The output of the process with `stdout` and `stderr` [interleaved](#ensuring-all-output-is-interleaved).433 434 This is `undefined` if either:435 - the [`all` option](#all-2) is `false` (the default value)436 - both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)437 438+This is an array if either the `stdout` or `stderr` option is a [transform in object mode](docs/transform.md#object-mode).439+440 #### stdio441 440-Type: `Array<string | Uint8Array | undefined>`442+Type: `Array<string | Uint8Array | unknown[] | undefined>`443 444 The output of the process on [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1) and [other file descriptors](#stdio-1).445 444-Items are `undefined` when their corresponding [`stdio`](#stdio-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).446+Items are `undefined` when their corresponding [`stdio`](#stdio-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). Items are arrays when their corresponding `stdio` option is a [transform in object mode](docs/transform.md#object-mode).447 448 #### failed449 450 Type: `boolean`498 unmodified lines