Refactor tests (#934)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 8074d85 · Browse files · 26 files·+262 added−263 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
26 files+262 added−263 removed
- tests:+193 added−198 removed
- other:+69 added−65 removed
Provenance
- Commit
52c4bde- Tree
187e40a- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
8074d85
26 files changed+262 added−263 removed
modified:lib/stdio/async.js+12 added-10 removed
4 unmodified lines56789910111213141516171819202122232425202627222829243031322833343135363337383539404139424344453 unmodified lines4950515251535455565749 unmodified lines4 unmodified linesimport {isStandardStream, incrementMaxListeners} from '../utils.js';import {handleInput} from './handle.js';import {pipeStreams} from './pipeline.js';import {TYPE_TO_MESSAGE} from './type.js';import {generatorToDuplexStream, pipeGenerator} from './generator.js';import {generatorToDuplexStream, pipeTransform} from './generator.js';
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async modeexport const handleInputAsync = (options, verboseInfo) => handleInput(addPropertiesAsync, options, verboseInfo, false);
const forbiddenIfAsync = ({type, optionName}) => { throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);};
const addProperties = { generator: generatorToDuplexStream, nodeStream: ({value}) => ({stream: value}), native() {},};
const addPropertiesAsync = { input: { generator: generatorToDuplexStream, ...addProperties, fileUrl: ({value}) => ({stream: createReadStream(value)}), filePath: ({value}) => ({stream: createReadStream(value.file)}), filePath: ({value: {file}}) => ({stream: createReadStream(file)}), webStream: ({value}) => ({stream: Readable.fromWeb(value)}), nodeStream: ({value}) => ({stream: value}), iterable: ({value}) => ({stream: Readable.from(value)}), string: ({value}) => ({stream: Readable.from(value)}), uint8Array: ({value}) => ({stream: Readable.from(Buffer.from(value))}), native() {}, }, output: { generator: generatorToDuplexStream, ...addProperties, fileUrl: ({value}) => ({stream: createWriteStream(value)}), filePath: ({value}) => ({stream: createWriteStream(value.file)}), filePath: ({value: {file}}) => ({stream: createWriteStream(file)}), webStream: ({value}) => ({stream: Writable.fromWeb(value)}), nodeStream: ({value}) => ({stream: value}), iterable: forbiddenIfAsync, string: forbiddenIfAsync, uint8Array: forbiddenIfAsync, native() {}, },};
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in async mode3 unmodified lines const inputStreamsGroups = {};
for (const {stdioItems, direction, fdNumber} of fileDescriptors) { for (const {stream} of stdioItems.filter(({type}) => type === 'generator')) { pipeGenerator(subprocess, stream, direction, fdNumber); pipeTransform(subprocess, stream, direction, fdNumber); }
for (const {stream} of stdioItems.filter(({type}) => type !== 'generator')) { pipeStdioItem({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller});49 unmodified linesmodified:lib/stdio/generator.js+28 added-25 removed
1+import isPlainObj from 'is-plain-obj';2 import {BINARY_ENCODINGS} from '../arguments/encoding.js';3 import {generatorsToTransform} from './transform.js';4 import {getEncodingTransformGenerator} from './encoding-transform.js';5 import {getSplitLinesGenerator, getAppendNewlineGenerator} from './split.js';6 import {pipeStreams} from './pipeline.js';6-import {isGeneratorOptions, isAsyncGenerator} from './type.js';7+import {isAsyncGenerator} from './type.js';8 import {getValidateTransformReturn} from './validate.js';9 10 export const getObjectMode = (stdioItems, direction, options) => {10- const generators = getGenerators(stdioItems, direction, options);11- if (generators.length === 0) {11+ const transforms = getTransforms(stdioItems, direction, options);12+ if (transforms.length === 0) {13 return false;14 }15 15- const {value: {readableObjectMode, writableObjectMode}} = generators.at(-1);16+ const {value: {readableObjectMode, writableObjectMode}} = transforms.at(-1);17 return direction === 'input' ? writableObjectMode : readableObjectMode;18 };19 19-export const normalizeGenerators = (stdioItems, direction, options) => [20+export const normalizeTransforms = (stdioItems, direction, options) => [21 ...stdioItems.filter(({type}) => type !== 'generator'),21- ...getGenerators(stdioItems, direction, options),22+ ...getTransforms(stdioItems, direction, options),23 ];24 24-const getGenerators = (stdioItems, direction, {encoding}) => {25- const generators = stdioItems.filter(({type}) => type === 'generator');26- const newGenerators = Array.from({length: generators.length});25+const getTransforms = (stdioItems, direction, {encoding}) => {26+ const transforms = stdioItems.filter(({type}) => type === 'generator');27+ const newTransforms = Array.from({length: transforms.length});28 28- for (const [index, stdioItem] of Object.entries(generators)) {29- newGenerators[index] = normalizeGenerator({stdioItem, index: Number(index), newGenerators, direction, encoding});29+ for (const [index, stdioItem] of Object.entries(transforms)) {30+ newTransforms[index] = normalizeTransform({stdioItem, index: Number(index), newTransforms, direction, encoding});31 }32 32- return sortGenerators(newGenerators, direction);33+ return sortTransforms(newTransforms, direction);34 };35 35-const normalizeGenerator = ({stdioItem, stdioItem: {value}, index, newGenerators, direction, encoding}) => {36+const normalizeTransform = ({stdioItem, stdioItem: {value}, index, newTransforms, direction, encoding}) => {37 const {38 transform,39 final,40 binary: binaryOption = false,41 preserveNewlines = false,42 objectMode,42- } = isGeneratorOptions(value) ? value : {transform: value};43+ } = isPlainObj(value) ? value : {transform: value};44 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);44- const objectModes = direction === 'output'45- ? getOutputObjectModes(objectMode, index, newGenerators)46- : getInputObjectModes(objectMode, index, newGenerators);47- return {...stdioItem, value: {transform, final, binary, preserveNewlines, ...objectModes}};45+ const {writableObjectMode, readableObjectMode} = getObjectModes(objectMode, index, newTransforms, direction);46+ return {...stdioItem, value: {transform, final, binary, preserveNewlines, writableObjectMode, readableObjectMode}};47 };48 49 /*50 `objectMode` determines the return value's type, i.e. the `readableObjectMode`.3 unmodified lines54 - can only be strings, Buffers and Uint8Arrays.55 Therefore its `readableObjectMode` must be `false`.56 The same applies to the first output's generator's `writableObjectMode`.57 */58+const getObjectModes = (objectMode, index, newTransforms, direction) => direction === 'output'59+ ? getOutputObjectModes(objectMode, index, newTransforms)60+ : getInputObjectModes(objectMode, index, newTransforms);61+59-const getOutputObjectModes = (objectMode, index, newGenerators) => {60- const writableObjectMode = index !== 0 && newGenerators[index - 1].value.readableObjectMode;62+const getOutputObjectModes = (objectMode, index, newTransforms) => {63+ const writableObjectMode = index !== 0 && newTransforms[index - 1].value.readableObjectMode;64 const readableObjectMode = objectMode ?? writableObjectMode;65 return {writableObjectMode, readableObjectMode};66 };67 65-const getInputObjectModes = (objectMode, index, newGenerators) => {68+const getInputObjectModes = (objectMode, index, newTransforms) => {69 const writableObjectMode = index === 070 ? objectMode === true68- : newGenerators[index - 1].value.readableObjectMode;69- const readableObjectMode = index !== newGenerators.length - 1 && (objectMode ?? writableObjectMode);71+ : newTransforms[index - 1].value.readableObjectMode;72+ const readableObjectMode = index !== newTransforms.length - 1 && (objectMode ?? writableObjectMode);73 return {writableObjectMode, readableObjectMode};74 };75 73-const sortGenerators = (newGenerators, direction) => direction === 'input' ? newGenerators.reverse() : newGenerators;76+const sortTransforms = (newTransforms, direction) => direction === 'input' ? newTransforms.reverse() : newTransforms;77 78 /*79 Generators can be used to transform/filter standard streams.80 29 unmodified lines110 return {stream};111 };112 113 // `subprocess.stdin|stdout|stderr|stdio` is directly mutated.111-export const pipeGenerator = (subprocess, stream, direction, fdNumber) => {114+export const pipeTransform = (subprocess, stream, direction, fdNumber) => {115 if (direction === 'output') {116 pipeStreams(subprocess.stdio[fdNumber], stream);117 } else {118 pipeStreams(stream, subprocess.stdio[fdNumber]);11 unmodified linesmodified:lib/stdio/handle.js+2 added-2 removed
4 unmodified lines5 import {handleNativeStream} from './native.js';6 import {handleInputOptions} from './input.js';7 import {handleStreamsLines} from './lines.js';8 import {handleStreamsEncoding} from './encoding-final.js';9-import {normalizeGenerators, getObjectMode} from './generator.js';9+import {normalizeTransforms, getObjectMode} from './generator.js';10 import {forwardStdio, willPipeFileDescriptor} from './forward.js';11 12 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode13 export const handleInput = (addProperties, options, verboseInfo, isSync) => {82 unmodified lines96 };97 98 const normalizeStdioItems = ({stdioItems, fdNumber, optionName, addProperties, options, isSync, direction, stdioState, verboseInfo, outputLines}) => {99 const allStdioItems = addInternalStdioItems({stdioItems, fdNumber, optionName, options, isSync, direction, stdioState, verboseInfo, outputLines});100- const normalizedStdioItems = normalizeGenerators(allStdioItems, direction, options);100+ const normalizedStdioItems = normalizeTransforms(allStdioItems, direction, options);101 return normalizedStdioItems.map(stdioItem => addStreamProperties(stdioItem, addProperties, direction));102 };103 104 const addInternalStdioItems = ({stdioItems, fdNumber, optionName, options, isSync, direction, stdioState, verboseInfo, outputLines}) => {20 unmodified linesmodified:lib/stdio/sync.js+10 added-10 removed
12 unmodified lines1314151617181920212223242526192728292223243031273233303435363334353738383940414238 unmodified lines12 unmodified linesconst forbiddenIfSync = ({type, optionName}) => { throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]} in sync mode.`);};
const addProperties = { generator: forbiddenIfSync, webStream: forbiddenIfSync, nodeStream: forbiddenIfSync, iterable: forbiddenIfSync, native() {},};
const addPropertiesSync = { input: { generator: forbiddenIfSync, ...addProperties, fileUrl: ({value}) => ({contents: bufferToUint8Array(readFileSync(value))}), filePath: ({value: {file}}) => ({contents: bufferToUint8Array(readFileSync(file))}), webStream: forbiddenIfSync, nodeStream: forbiddenIfSync, iterable: forbiddenIfSync, string: ({value}) => ({contents: value}), uint8Array: ({value}) => ({contents: value}), native() {}, }, output: { generator: forbiddenIfSync, ...addProperties, fileUrl: ({value}) => ({path: value}), filePath: ({value: {file}}) => ({path: file}), webStream: forbiddenIfSync, nodeStream: forbiddenIfSync, iterable: forbiddenIfSync, string: forbiddenIfSync, uint8Array: forbiddenIfSync, native() {}, },};
const addInputOptionSync = (fileDescriptors, options) => {38 unmodified linesmodified:lib/stdio/type.js+6 added-7 removed
1 import {isStream as isNodeStream} from 'is-stream';2+import isPlainObj from 'is-plain-obj';3 import {isUint8Array} from '../utils.js';4 5 // The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.6 export const getStdioItemType = (value, optionName) => {24 unmodified lines31 if (isIterableObject(value)) {32 return 'iterable';33 }34 34- if (isGeneratorOptions(value)) {35- return getGeneratorObjectType(value, optionName);35+ if (isTransformOptions(value)) {36+ return getTransformObjectType(value, optionName);37 }38 39 return 'native';40 };41 41-const getGeneratorObjectType = ({transform, final, binary, objectMode}, optionName) => {42+const getTransformObjectType = ({transform, final, binary, objectMode}, optionName) => {43 if (transform !== undefined && !isGenerator(transform)) {44 throw new TypeError(`The \`${optionName}.transform\` option must be a generator.`);45 }46 15 unmodified lines62 63 const isGenerator = value => isAsyncGenerator(value) || isSyncGenerator(value);64 export const isAsyncGenerator = value => Object.prototype.toString.call(value) === '[object AsyncGeneratorFunction]';65 const isSyncGenerator = value => Object.prototype.toString.call(value) === '[object GeneratorFunction]';65-export const isGeneratorOptions = value => typeof value === 'object'66- && value !== null66+const isTransformOptions = value => isPlainObj(value)67 && (value.transform !== undefined || value.final !== undefined);68 69 export const isUrl = value => Object.prototype.toString.call(value) === '[object URL]';70 export const isRegularUrl = value => isUrl(value) && value.protocol !== 'file:';71 72-const isFilePathObject = value => typeof value === 'object'73- && value !== null72+const isFilePathObject = value => isPlainObj(value)73 && Object.keys(value).length === 174 && isFilePathString(value.file);75 export const isFilePathString = file => typeof file === 'string';76 25 unmodified linesmodified:test/convert/loop.js+7 added-7 removed
133 unmodified lines134 135 test('.iterable() uses Uint8Arrays with "binary: true"', testObjectMode, simpleChunksUint8Array, 'iterable', null, false, false, true);136 test('.iterable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'iterable', 'utf8', false, false, true);137 test('.iterable() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'iterable', 'utf8', false, false, true, {encoding: 'buffer'});138-test('.iterable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator});138+test('.iterable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator()});139 test('.iterable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'iterable', null, false, true, false);140 test('.iterable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'iterable', 'utf8', false, true, false);141 test('.iterable() uses strings in objectMode with "binary: false" and "encoding: buffer"', testObjectMode, simpleChunks, 'iterable', 'utf8', false, true, false, {encoding: 'buffer'});142-test('.iterable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator});142+test('.iterable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator()});143 test('.readable() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'readable', null, false, false, true);144 test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true);145 test('.readable() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'});146-test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator});146+test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator()});147 test('.readable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'readable', null, false, true, false);148 test('.readable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'readable', 'utf8', false, true, false);149 test('.readable() uses strings in objectMode with "binary: false" and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, false, {encoding: 'buffer'});150-test('.readable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator});150+test('.readable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator()});151 test('.duplex() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'duplex', null, false, false, true);152 test('.duplex() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true);153 test('.duplex() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true, {encoding: 'buffer'});154-test('.duplex() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator});154+test('.duplex() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator()});155 test('.duplex() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'duplex', null, false, true, false);156 test('.duplex() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'duplex', 'utf8', false, true, false);157 test('.duplex() uses strings in objectMode with "binary: false" and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, false, {encoding: 'buffer'});158-test('.duplex() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator});158+test('.duplex() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator()});159 160 const testObjectSplit = async (t, methodName) => {161- const subprocess = getSubprocess(methodName, foobarString, {stdout: getOutputGenerator(simpleFull, true)});161+ const subprocess = getSubprocess(methodName, foobarString, {stdout: getOutputGenerator(simpleFull)(true)});162 const stream = subprocess[methodName]({binary: false});163 await assertChunks(t, stream, [simpleFull], methodName);164 await subprocess;165 };18 unmodified linesmodified:test/convert/readable.js+4 added-4 removed
23 unmodified lines24 } from '../helpers/convert.js';25 import {foobarString, foobarBuffer, foobarObject} from '../helpers/input.js';26 import {simpleFull} from '../helpers/lines.js';27 import {prematureClose, fullStdio} from '../helpers/stdio.js';28-import {outputObjectGenerator, getChunksGenerator} from '../helpers/generator.js';28+import {outputObjectGenerator, getOutputsAsyncGenerator} from '../helpers/generator.js';29 import {defaultHighWaterMark, defaultObjectHighWaterMark} from '../helpers/stream.js';30 31 setFixtureDir();32 209 unmodified lines242 await assertSubprocessOutput(t, subprocess);243 });244 245 test('.readable() works with objectMode', async t => {246- const subprocess = execa('noop.js', {stdout: outputObjectGenerator});246+ const subprocess = execa('noop.js', {stdout: outputObjectGenerator()});247 const stream = subprocess.readable();248 t.true(stream.readableObjectMode);249 t.is(stream.readableHighWaterMark, defaultObjectHighWaterMark);250 1 unmodified line252 await assertSubprocessOutput(t, subprocess, [foobarObject]);253 });254 255 test('.duplex() works with objectMode and reads', async t => {256- const subprocess = getReadWriteSubprocess({stdout: outputObjectGenerator});256+ const subprocess = getReadWriteSubprocess({stdout: outputObjectGenerator()});257 const stream = subprocess.duplex();258 t.true(stream.readableObjectMode);259 t.is(stream.readableHighWaterMark, defaultObjectHighWaterMark);260 t.false(stream.writableObjectMode);63 unmodified lines324 await assertSubprocessOutput(t, subprocess, simpleFull);325 });326 327 test('.readable() can wait for data', async t => {328- const subprocess = execa('noop.js', {stdout: getChunksGenerator([foobarString, foobarString], false, true)});328+ const subprocess = execa('noop.js', {stdout: getOutputsAsyncGenerator([foobarString, foobarString])(false, true)});329 const stream = subprocess.readable();330 331 t.is(stream.read(), null);332 await once(stream, 'readable');122 unmodified linesmodified:test/convert/writable.js+1 added-1 removed
336 unmodified lines337 await assertSubprocessOutput(t, subprocess, expectedOutput);338 });339 340 const testPropagateError = async (t, methodName) => {341- const subprocess = getReadWriteSubprocess({stdin: throwingGenerator});341+ const subprocess = getReadWriteSubprocess({stdin: throwingGenerator()});342 const stream = subprocess[methodName]();343 stream.end('.');344 await t.throwsAsync(finishedStream(stream), {message: GENERATOR_ERROR_REGEXP});345 };44 unmodified linesmodified:test/fixtures/nested-big-array.js+1 added-1 removed
3 unmodified lines4 import {getOutputGenerator} from '../helpers/generator.js';5 6 const bigArray = Array.from({length: 100}, (_, index) => index);7 const [options, file, ...args] = process.argv.slice(2);8-await execa(file, args, {stdout: getOutputGenerator(bigArray, true), ...JSON.parse(options)});8+await execa(file, args, {stdout: getOutputGenerator(bigArray)(true), ...JSON.parse(options)});modified:test/fixtures/nested-object.js+1 added-1 removed
2 unmodified lines3 import {execa} from '../../index.js';4 import {outputObjectGenerator} from '../helpers/generator.js';5 6 const [options, file, ...args] = process.argv.slice(2);7-await execa(file, args, {stdout: outputObjectGenerator, ...JSON.parse(options)});7+await execa(file, args, {stdout: outputObjectGenerator(), ...JSON.parse(options)});modified:test/helpers/generator.js+67 added-60 removed
1-import {setImmediate, setInterval} from 'node:timers/promises';2-import {foobarObject} from './input.js';1+import {setImmediate, setInterval, setTimeout, scheduler} from 'node:timers/promises';2+import {foobarObject, foobarString} from './input.js';3 4-export const noopAsyncGenerator = (objectMode, binary) => ({5- async * transform(line) {6- yield line;7- },4+const getGenerator = transform => (objectMode, binary, preserveNewlines) => ({5+ transform,6 objectMode,7 binary,8+ preserveNewlines,9 });10 12-export const addNoopGenerator = (transform, addNoopTransform) => addNoopTransform13- ? [transform, noopGenerator(undefined, true)]11+export const addNoopGenerator = (transform, addNoopTransform, objectMode, binary) => addNoopTransform12+ ? [transform, noopGenerator(objectMode, binary)]13 : [transform];14 16-export const noopGenerator = (objectMode, binary, preserveNewlines) => ({17- * transform(line) {18- yield line;19- },20- objectMode,21- binary,22- preserveNewlines,15+export const noopGenerator = getGenerator(function * (value) {16+ yield value;17 });18 25-export const serializeGenerator = (objectMode, binary) => ({26- * transform(object) {27- yield JSON.stringify(object);28- },29- objectMode,30- binary,19+export const noopAsyncGenerator = getGenerator(async function * (value) {20+ yield value;21 });22 33-export const getOutputsGenerator = (inputs, objectMode) => ({34- * transform() {35- yield * inputs;36- },37- objectMode,23+export const serializeGenerator = getGenerator(function * (object) {24+ yield JSON.stringify(object);25 });26 40-export const identityGenerator = input => function * () {27+export const getOutputGenerator = input => getGenerator(function * () {28 yield input;42-};29+});30 44-export const identityAsyncGenerator = input => async function * () {31+export const outputObjectGenerator = () => getOutputGenerator(foobarObject)(true);32+33+export const getOutputAsyncGenerator = input => getGenerator(async function * () {34 yield input;46-};35+});36 48-export const getOutputGenerator = (input, objectMode, binary) => ({49- transform: identityGenerator(input),50- objectMode,51- binary,37+export const getOutputsGenerator = inputs => getGenerator(function * () {38+ yield * inputs;39 });40 54-export const outputObjectGenerator = getOutputGenerator(foobarObject, true);55-56-export const getChunksGenerator = (chunks, objectMode, binary) => ({57- async * transform() {58- for (const chunk of chunks) {59- yield chunk;60- // eslint-disable-next-line no-await-in-loop61- await setImmediate();62- }41+export const getOutputsAsyncGenerator = inputs => getGenerator(async function * () {42+ for (const input of inputs) {43+ yield input;44+ // eslint-disable-next-line no-await-in-loop45+ await setImmediate();46+ }63- },64- objectMode,65- binary,47 });48 49 const noYieldTransform = function * () {};50 70-export const noYieldGenerator = objectMode => ({71- transform: noYieldTransform,72- objectMode,51+export const noYieldGenerator = getGenerator(noYieldTransform);52+53+export const prefix = '> ';54+export const suffix = ' <';55+56+export const multipleYieldGenerator = getGenerator(async function * (line = foobarString) {57+ yield prefix;58+ await scheduler.yield();59+ yield line;60+ await scheduler.yield();61+ yield suffix;62 });63 64 export const convertTransformToFinal = (transform, final) => {65 if (!final) {3 unmodified lines69 const generatorOptions = typeof transform === 'function' ? {transform} : transform;70 return ({...generatorOptions, transform: noYieldTransform, final: generatorOptions.transform});71 };72 84-export const infiniteGenerator = async function * () {85- for await (const value of setInterval(100, 'foo')) {73+export const infiniteGenerator = getGenerator(async function * () {74+ for await (const value of setInterval(100, foobarString)) {75 yield value;76 }88-};77+});78 90-export const uppercaseGenerator = (objectMode, binary) => ({91- * transform(line) {92- yield line.toUpperCase();93- },94- objectMode,95- binary,79+const textDecoder = new TextDecoder();80+81+export const uppercaseBufferGenerator = getGenerator(function * (buffer) {82+ yield textDecoder.decode(buffer).toUpperCase();83 });84 85+export const uppercaseGenerator = getGenerator(function * (string) {86+ yield string.toUpperCase();87+});88+89 // eslint-disable-next-line require-yield99-export const throwingGenerator = function * () {90+export const throwingGenerator = getGenerator(function * () {91 throw new Error('Generator error');101-};92+});93 94 export const GENERATOR_ERROR_REGEXP = /Generator error/;95+96+export const appendGenerator = getGenerator(function * (string) {97+ yield `${string}${casedSuffix}`;98+});99+100+export const casedSuffix = 'k';101+102+export const resultGenerator = inputs => getGenerator(function * (input) {103+ inputs.push(input);104+ yield input;105+});106+107+export const timeoutGenerator = timeout => getGenerator(async function * () {108+ await setTimeout(timeout);109+ yield foobarString;110+});modified:test/helpers/input.js+2 added
11 unmodified lines12 export const foobarBuffer = Buffer.from(foobarString);13 const foobarUtf16Buffer = Buffer.from(foobarString, 'utf16le');14 export const foobarUtf16Uint8Array = bufferToUint8Array(foobarUtf16Buffer);15 export const foobarDataView = new DataView(foobarArrayBuffer);16+export const foobarHex = foobarBuffer.toString('hex');17+export const foobarUppercase = foobarString.toUpperCase();18 export const foobarObject = {foo: 'bar'};19 export const foobarObjectString = JSON.stringify(foobarObject);modified:test/return/duration.js-1 removed
6 unmodified lines7 8 const assertDurationMs = (t, durationMs) => {9 t.is(typeof durationMs, 'number');10 t.true(Number.isFinite(durationMs));11- t.false(Number.isInteger(durationMs));11 t.not(durationMs, 0);12 t.true(durationMs > 0);13 };14 47 unmodified linesmodified:test/return/error.js+2 added-2 removed
96 unmodified lines97 };98 99 test('error.message does not contain stdout if not available', testPartialIgnoreMessage, 1, 'ignore', 'stderr');100 test('error.message does not contain stderr if not available', testPartialIgnoreMessage, 2, 'ignore', 'stdout');101-test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator, 'stderr');102-test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator, 'stdout');101+test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator(), 'stderr');102+test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator(), 'stdout');103 104 const testFullIgnoreMessage = async (t, options, resultProperty) => {105 const {[resultProperty]: message} = await t.throwsAsync(execa('echo-fail.js', options));106 t.false(message.includes('stderr'));99 unmodified linesmodified:test/stdio/encoding-final.js+3 added-3 removed
5 unmodified lines6 import getStream, {getStreamAsBuffer} from 'get-stream';7 import {execa, execaSync} from '../../index.js';8 import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';9 import {fullStdio} from '../helpers/stdio.js';10-import {outputObjectGenerator, getChunksGenerator, addNoopGenerator} from '../helpers/generator.js';10+import {outputObjectGenerator, getOutputsGenerator, addNoopGenerator} from '../helpers/generator.js';11 import {foobarObject} from '../helpers/input.js';12 13 const pExec = promisify(exec);14 84 unmodified lines99 const foobarArray = ['fo', 'ob', 'ar', '..'];100 101 const testMultibyteCharacters = async (t, objectMode, addNoopTransform) => {102 const {stdout} = await execa('noop.js', {103- stdout: addNoopGenerator(getChunksGenerator(foobarArray, objectMode, true), addNoopTransform),103+ stdout: addNoopGenerator(getOutputsGenerator(foobarArray)(objectMode, true), addNoopTransform, objectMode),104 encoding: 'base64',105 });106 if (objectMode) {107 t.deepEqual(stdout, foobarArray);7 unmodified lines115 test('Handle multibyte characters, with objectMode', testMultibyteCharacters, true, false);116 test('Handle multibyte characters, with objectMode, noop transform', testMultibyteCharacters, true, true);117 118 const testObjectMode = async (t, addNoopTransform) => {119- const {stdout} = await execa('noop.js', {stdout: addNoopGenerator(outputObjectGenerator, addNoopTransform), encoding: 'base64'});119+ const {stdout} = await execa('noop.js', {stdout: addNoopGenerator(outputObjectGenerator(), addNoopTransform, true), encoding: 'base64'});120 t.deepEqual(stdout, [foobarObject]);121 };122 123 test('Other encodings work with transforms that return objects', testObjectMode, false);45 unmodified linesmodified:test/stdio/encoding-transform.js+2 added-2 removed
64 unmodified lines65 // eslint-disable-next-line max-params66 const testGeneratorNextEncoding = async (t, input, encoding, firstObjectMode, secondObjectMode, expectedType) => {67 const {stdout} = await execa('noop.js', ['other'], {68 stdout: [69- getOutputGenerator(input, firstObjectMode),69+ getOutputGenerator(input)(firstObjectMode),70 getTypeofGenerator(secondObjectMode),71 ],72 encoding,73 });30 unmodified lines104 // eslint-disable-next-line max-params105 const testGeneratorReturnType = async (t, input, encoding, reject, objectMode, final) => {106 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';107 const {stdout} = await execa(fixtureName, ['1', foobarString], {108- stdout: convertTransformToFinal(getOutputGenerator(input, objectMode, true), final),108+ stdout: convertTransformToFinal(getOutputGenerator(input)(objectMode, true), final),109 encoding,110 reject,111 });112 const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;77 unmodified linesmodified:test/stdio/generator.js+46 added-35 removed
5 unmodified lines6 import tempfile from 'tempfile';7 import {execa} from '../../index.js';8 import {setFixtureDir} from '../helpers/fixtures-dir.js';9 import {getStdio} from '../helpers/stdio.js';10-import {foobarString, foobarUint8Array, foobarBuffer, foobarObject, foobarObjectString} from '../helpers/input.js';11-import {serializeGenerator, outputObjectGenerator, addNoopGenerator, uppercaseGenerator} from '../helpers/generator.js';10+import {11+ foobarString,12+ foobarUppercase,13+ foobarHex,14+ foobarUint8Array,15+ foobarBuffer,16+ foobarObject,17+ foobarObjectString,18+} from '../helpers/input.js';19+import {20+ addNoopGenerator,21+ serializeGenerator,22+ outputObjectGenerator,23+ uppercaseGenerator,24+ uppercaseBufferGenerator,25+ appendGenerator,26+ casedSuffix,27+} from '../helpers/generator.js';28 29 setFixtureDir();30 31 const textEncoder = new TextEncoder();16-const textDecoder = new TextDecoder();32 18-const foobarUppercase = foobarString.toUpperCase();19-const foobarHex = foobarBuffer.toString('hex');20-21-const uppercaseBufferGenerator = {22- * transform(line) {23- yield textDecoder.decode(line).toUpperCase();24- },25- binary: true,26-};27-33 const getInputObjectMode = (objectMode, addNoopTransform) => objectMode34 ? {35 input: [foobarObject],31- generators: addNoopGenerator(serializeGenerator(true), addNoopTransform),36+ generators: addNoopGenerator(serializeGenerator(objectMode), addNoopTransform, objectMode),37 output: foobarObjectString,38 }39 : {40 input: foobarUint8Array,36- generators: addNoopGenerator(uppercaseGenerator(), addNoopTransform),41+ generators: addNoopGenerator(uppercaseGenerator(objectMode), addNoopTransform, objectMode),42 output: foobarUppercase,43 };44 40-const getOutputObjectMode = (objectMode, addNoopTransform) => objectMode45+const getOutputObjectMode = (objectMode, addNoopTransform, binary) => objectMode46 ? {42- generators: addNoopGenerator(outputObjectGenerator, addNoopTransform),47+ generators: addNoopGenerator(outputObjectGenerator(), addNoopTransform, objectMode, binary),48 output: [foobarObject],49 getStreamMethod: getStreamAsArray,50 }51 : {47- generators: addNoopGenerator(uppercaseBufferGenerator, addNoopTransform),52+ generators: addNoopGenerator(uppercaseBufferGenerator(objectMode, true), addNoopTransform, objectMode, binary),53 output: foobarUppercase,54 getStreamMethod: getStream,55 };56 103 unmodified lines160 test('Can use generators with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true);161 162 // eslint-disable-next-line max-params163 const testGeneratorOutputPipe = async (t, fdNumber, useShortcutProperty, objectMode, addNoopTransform) => {159- const {generators, output, getStreamMethod} = getOutputObjectMode(objectMode, addNoopTransform);164+ const {generators, output, getStreamMethod} = getOutputObjectMode(objectMode, addNoopTransform, true);165 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, generators));166 const stream = useShortcutProperty ? [subprocess.stdout, subprocess.stderr][fdNumber - 1] : subprocess.stdio[fdNumber];167 const [result] = await Promise.all([getStreamMethod(stream), subprocess]);168 t.deepEqual(result, output);25 unmodified lines194 return 'pipe';195 }196 197 if (objectMode) {193- return outputObjectGenerator;198+ return outputObjectGenerator();199 }200 196- return encoding === 'utf8' ? uppercaseGenerator() : uppercaseBufferGenerator;201+ return encoding === 'utf8' ? uppercaseGenerator() : uppercaseBufferGenerator();202 };203 204 const getStdoutStderrOutput = (output, stdioOption, encoding, objectMode) => {205 if (objectMode && !stdioOption) {96 unmodified lines302 test('Can use generators with inputFile option', testInputFile, filePath => ({inputFile: filePath, stdin: uppercaseGenerator()}), false);303 304 const testOutputFile = async (t, reversed) => {305 const filePath = tempfile();301- const stdoutOption = [uppercaseBufferGenerator, {file: filePath}];306+ const stdoutOption = [uppercaseBufferGenerator(false, true), {file: filePath}];307 const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;308 const {stdout} = await execa('noop-fd.js', ['1'], {stdout: reversedStdoutOption});309 t.is(stdout, foobarUppercase);310 t.is(await readFile(filePath, 'utf8'), foobarUppercase);5 unmodified lines316 317 test('Can use generators to a Writable stream', async t => {318 const passThrough = new PassThrough();319 const [{stdout}, streamOutput] = await Promise.all([315- execa('noop-fd.js', ['1', foobarString], {stdout: [uppercaseBufferGenerator, passThrough]}),320+ execa('noop-fd.js', ['1', foobarString], {stdout: [uppercaseBufferGenerator(false, true), passThrough]}),321 getStream(passThrough),322 ]);323 t.is(stdout, foobarUppercase);324 t.is(streamOutput, foobarUppercase);11 unmodified lines336 const {stdout} = await execa('nested-inherit.js');337 t.is(stdout, foobarUppercase);338 });339 335-const casedSuffix = 'k';336-337-const appendGenerator = function * (line) {338- yield `${line}${casedSuffix}`;339-};340-340 const testAppendInput = async (t, reversed) => {342- const stdin = [foobarUint8Array, uppercaseGenerator(), appendGenerator];341+ const stdin = [foobarUint8Array, uppercaseGenerator(), appendGenerator()];342 const reversedStdin = reversed ? stdin.reverse() : stdin;343 const {stdout} = await execa('stdin-fd.js', ['0'], {stdin: reversedStdin});344 const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;345 t.is(stdout, `${foobarUppercase}${reversedSuffix}`);2 unmodified lines348 test('Can use multiple generators as input', testAppendInput, false);349 test('Can use multiple generators as input, reversed', testAppendInput, true);350 351 const testAppendOutput = async (t, reversed) => {353- const stdoutOption = [uppercaseGenerator(), appendGenerator];352+ const stdoutOption = [uppercaseGenerator(), appendGenerator()];353 const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;354 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: reversedStdoutOption});355 const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;356 t.is(stdout, `${foobarUppercase}${reversedSuffix}`);1 unmodified line358 359 test('Can use multiple generators as output', testAppendOutput, false);360 test('Can use multiple generators as output, reversed', testAppendOutput, true);361 363-test('Can use multiple identical generators', async t => {364- const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: [appendGenerator, appendGenerator]});365- t.is(stdout, `${foobarString}${casedSuffix}${casedSuffix}`);366-});362+const testTwoGenerators = async (t, producesTwo, firstGenerator, secondGenerator = firstGenerator) => {363+ const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: [firstGenerator, secondGenerator]});364+ const expectedSuffix = producesTwo ? `${casedSuffix}${casedSuffix}` : casedSuffix;365+ t.is(stdout, `${foobarString}${expectedSuffix}`);366+};367+368+test('Can use multiple identical generators', testTwoGenerators, true, appendGenerator().transform);369+test('Can use multiple identical generators, options object', testTwoGenerators, true, appendGenerator());370+371+const testGeneratorSyntax = async (t, generator) => {372+ const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: generator});373+ t.is(stdout, foobarUppercase);374+};375+376+test('Can pass generators with an options plain object', testGeneratorSyntax, uppercaseGenerator());377+test('Can pass generators without an options plain object', testGeneratorSyntax, uppercaseGenerator().transform);modified:test/stdio/iterable.js+5 added-10 removed
3 unmodified lines4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDir} from '../helpers/fixtures-dir.js';6 import {getStdio} from '../helpers/stdio.js';7 import {foobarObject, foobarObjectString} from '../helpers/input.js';8-import {serializeGenerator, infiniteGenerator} from '../helpers/generator.js';8+import {serializeGenerator, infiniteGenerator, throwingGenerator} from '../helpers/generator.js';9 10 const stringArray = ['foo', 'bar'];11 12 const stringGenerator = function * () {64 unmodified lines77 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-81 const testIterableError = async (t, fdNumber) => {87- const {originalMessage} = await t.throwsAsync(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, throwingGenerator())));88- t.is(originalMessage, 'generator error');82+ const {originalMessage} = await t.throwsAsync(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, throwingGenerator().transform())));83+ t.is(originalMessage, 'Generator error');84 };85 86 test('stdin option handles errors in iterables', testIterableError, 0);87 test('stdio[*] option handles errors in iterables', testIterableError, 3);13 unmodified lines101 test('stdout option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 1, execaSync);102 test('stderr option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 2, execaSync);103 104 test('stdin option can be an infinite iterable', async t => {110- const iterable = infiniteGenerator();105+ const iterable = infiniteGenerator().transform();106 const subprocess = execa('stdin.js', getStdio(0, iterable));107 await once(subprocess.stdout, 'data');108 subprocess.kill();109 const {stdout} = await t.throwsAsync(subprocess);9 unmodified lines119 test('stdin option can be multiple iterables', testMultipleIterable, 0);120 test('stdio[*] option can be multiple iterables', testMultipleIterable, 3);121 122 test('stdin option iterable is canceled on subprocess error', async t => {128- const iterable = infiniteGenerator();123+ const iterable = infiniteGenerator().transform();124 await t.throwsAsync(execa('stdin.js', {stdin: iterable, timeout: 1}), {message: /timed out/});125 // eslint-disable-next-line no-unused-vars, no-empty126 for await (const _ of iterable) {}127 });modified:test/stdio/lines.js+3 added-3 removed
4 unmodified lines5 import {MaxBufferError} from 'get-stream';6 import {execa, execaSync} from '../../index.js';7 import {setFixtureDir} from '../helpers/fixtures-dir.js';8 import {fullStdio} from '../helpers/stdio.js';9-import {getChunksGenerator} from '../helpers/generator.js';9+import {getOutputsGenerator} from '../helpers/generator.js';10 import {foobarString, foobarObject} from '../helpers/input.js';11 import {assertStreamOutput, assertIterableChunks} from '../helpers/convert.js';12 import {13 simpleFull,43 unmodified lines57 58 // eslint-disable-next-line max-params59 const testStreamLinesGenerator = async (t, input, expectedLines, objectMode, binary) => {60 const {stdout} = await execa('noop.js', {61- stdout: getChunksGenerator(input, objectMode, binary),61+ stdout: getOutputsGenerator(input)(objectMode, binary),62 lines: true,63 stripFinalNewline: false,64 });65 t.deepEqual(stdout, expectedLines);9 unmodified lines75 test('"lines: true" is a noop big strings generators without newlines, objectMode', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlines], true, false);76 77 test('"lines: true" is a noop with objects generators, objectMode', async t => {78 const {stdout} = await execa('noop.js', {79- stdout: getChunksGenerator([foobarObject], true),79+ stdout: getOutputsGenerator([foobarObject])(true),80 lines: true,81 });82 t.deepEqual(stdout, [foobarObject]);83 });105 unmodified linesmodified:test/stdio/split.js+9 added-14 removed
1 unmodified line2 import {execa} from '../../index.js';3 import {setFixtureDir} from '../helpers/fixtures-dir.js';4 import {getStdio} from '../helpers/stdio.js';5 import {6- getChunksGenerator,6 getOutputsGenerator,7 noopGenerator,8 noopAsyncGenerator,9+ resultGenerator,10 } from '../helpers/generator.js';11 import {foobarString, foobarUint8Array, foobarObject, foobarObjectString} from '../helpers/input.js';12 import {13 simpleFull,42 unmodified lines56 const manyFullEnd = `${manyFull}\n`;57 const manyLines = [manyFull];58 const mixedNewlines = '.\n.\r\n.\n.\r\n.\n';59 60-const resultGenerator = function * (lines, chunk) {61- lines.push(chunk);62- yield chunk;63-};64-60 // eslint-disable-next-line max-params61 const testLines = async (t, fdNumber, input, expectedLines, expectedOutput, objectMode, preserveNewlines) => {62 const lines = [];63 const {stdio} = await execa('noop-fd.js', [`${fdNumber}`], {64 ...getStdio(fdNumber, [70- getChunksGenerator(input, false, true),71- {transform: resultGenerator.bind(undefined, lines), preserveNewlines, objectMode},65+ getOutputsGenerator(input)(false, true),66+ resultGenerator(lines)(objectMode, false, preserveNewlines),67 ]),68 stripFinalNewline: false,69 });70 t.deepEqual(lines, expectedLines);61 unmodified lines132 const testBinaryOption = async (t, binary, input, expectedLines, expectedOutput, objectMode, preserveNewlines, encoding) => {133 const lines = [];134 const {stdout} = await execa('noop.js', {135 stdout: [141- getChunksGenerator(input, false, true),142- {transform: resultGenerator.bind(undefined, lines), binary, preserveNewlines, objectMode},136+ getOutputsGenerator(input)(false, true),137+ resultGenerator(lines)(objectMode, binary, preserveNewlines),138 ],139 stripFinalNewline: false,140 encoding,141 });47 unmodified lines189 test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines', testStringToUint8Array, [foobarUint8Array], true, false);190 191 const testStripNewline = async (t, input, expectedOutput) => {192 const {stdout} = await execa('noop.js', {198- stdout: getChunksGenerator([input]),193+ stdout: getOutputsGenerator([input])(),194 stripFinalNewline: false,195 });196 t.is(stdout, expectedOutput);197 };21 unmodified lines219 const testUnsetObjectMode = async (t, expectedOutput, preserveNewlines) => {220 const lines = [];221 const {stdout} = await execa('noop.js', {222 stdout: [228- getChunksGenerator([foobarObject], true),223+ getOutputsGenerator([foobarObject])(true),224 {transform: serializeResultGenerator.bind(undefined, lines), preserveNewlines, objectMode: false},225 ],226 stripFinalNewline: false,227 });7 unmodified lines235 const testYieldArray = async (t, input, expectedLines, expectedOutput) => {236 const lines = [];237 const {stdout} = await execa('noop.js', {238 stdout: [244- getOutputsGenerator(input),245- resultGenerator.bind(undefined, lines),239+ getOutputsGenerator(input)(),240+ resultGenerator(lines)(),241 ],242 stripFinalNewline: false,243 });244 t.deepEqual(lines, expectedLines);5 unmodified linesmodified:test/stdio/transform.js+30 added-44 removed
1 import {Buffer} from 'node:buffer';2 import {once} from 'node:events';3-import {setTimeout, scheduler} from 'node:timers/promises';3+import {scheduler} from 'node:timers/promises';4 import test from 'ava';5 import {getStreamAsArray} from 'get-stream';6 import {execa} from '../../index.js';7 import {foobarString} from '../helpers/input.js';8 import {9 noopGenerator,10- identityGenerator,11- identityAsyncGenerator,12- getOutputsGenerator,10+ getOutputAsyncGenerator,11 getOutputGenerator,12+ getOutputsGenerator,13 infiniteGenerator,14 outputObjectGenerator,16- convertTransformToFinal,15 noYieldGenerator,16+ multipleYieldGenerator,17+ convertTransformToFinal,18+ prefix,19+ suffix,20 throwingGenerator,21 GENERATOR_ERROR_REGEXP,22+ timeoutGenerator,23 } from '../helpers/generator.js';24 import {defaultHighWaterMark} from '../helpers/stream.js';25 import {setFixtureDir} from '../helpers/fixtures-dir.js';26 27 setFixtureDir();28 29 const testGeneratorFinal = async (t, fixtureName) => {27- const {stdout} = await execa(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString), true)});30+ const {stdout} = await execa(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString)(), true)});31 t.is(stdout, foobarString);32 };33 34 test('Generators "final" can be used', testGeneratorFinal, 'noop.js');35 test('Generators "final" is used even on empty streams', testGeneratorFinal, 'empty.js');36 37 const testFinalAlone = async (t, final) => {35- const {stdout} = await execa('noop-fd.js', ['1', '.'], {stdout: {final: final(foobarString), binary: true}});38+ const {stdout} = await execa('noop-fd.js', ['1', '.'], {stdout: {final: final(foobarString)().transform, binary: true}});39 t.is(stdout, `.${foobarString}`);40 };41 39-test('Generators "final" can be used without "transform"', testFinalAlone, identityGenerator);40-test('Generators "final" can be used without "transform", async', testFinalAlone, identityAsyncGenerator);42+test('Generators "final" can be used without "transform"', testFinalAlone, getOutputGenerator);43+test('Generators "final" can be used without "transform", async', testFinalAlone, getOutputAsyncGenerator);44 45 const testFinalNoOutput = async (t, final) => {43- const {stdout} = await execa('empty.js', {stdout: {final: final(foobarString)}});46+ const {stdout} = await execa('empty.js', {stdout: {final: final(foobarString)().transform}});47 t.is(stdout, foobarString);48 };49 47-test('Generators "final" can be used without "transform" nor output', testFinalNoOutput, identityGenerator);48-test('Generators "final" can be used without "transform" nor output, async', testFinalNoOutput, identityAsyncGenerator);50+test('Generators "final" can be used without "transform" nor output', testFinalNoOutput, getOutputGenerator);51+test('Generators "final" can be used without "transform" nor output, async', testFinalNoOutput, getOutputAsyncGenerator);52 53 const repeatCount = defaultHighWaterMark * 3;54 55 const writerGenerator = function * () {9 unmodified lines65 66 const testHighWaterMark = async (t, passThrough, binary, objectMode) => {67 const {stdout} = await execa('noop.js', {68 stdout: [66- ...(objectMode ? [outputObjectGenerator] : []),69+ ...(objectMode ? [outputObjectGenerator()] : []),70 writerGenerator,71 ...(passThrough ? [noopGenerator(false, binary)] : []),72 {transform: getLengthGenerator.bind(undefined, t), preserveNewlines: true, objectMode: true},73 ],13 unmodified lines87 };88 89 test('Generator can filter "transform" by not calling yield', testNoYield, false, false, '');90 test('Generator can filter "transform" by not calling yield, objectMode', testNoYield, true, false, []);88-test('Generator can filter "final" by not calling yield', testNoYield, false, false, '');89-test('Generator can filter "final" by not calling yield, objectMode', testNoYield, true, false, []);91+test('Generator can filter "final" by not calling yield', testNoYield, false, true, '');92+test('Generator can filter "final" by not calling yield, objectMode', testNoYield, true, true, []);93 91-const prefix = '> ';92-const suffix = ' <';93-94-const multipleYieldGenerator = async function * (line = foobarString) {95- yield prefix;96- await scheduler.yield();97- yield line;98- await scheduler.yield();99- yield suffix;100-};101-94 const testMultipleYields = async (t, final) => {103- const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(multipleYieldGenerator, final)});95+ const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(multipleYieldGenerator(), final)});96 t.is(stdout, `${prefix}\n${foobarString}\n${suffix}`);97 };98 99 test('Generator can yield "transform" multiple times at different moments', testMultipleYields, false);32 unmodified lines132 test('Generators take "maxBuffer" into account', async t => {133 const bigString = '.'.repeat(maxBuffer);134 const {stdout} = await execa('noop.js', {135 maxBuffer,144- stdout: getOutputGenerator(bigString, false, true),136+ stdout: getOutputGenerator(bigString)(false, true),137 });138 t.is(stdout, bigString);139 148- await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputGenerator(`${bigString}.`, false)}));140+ await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputGenerator(`${bigString}.`)(false)}));141 });142 143 test('Generators take "maxBuffer" into account, objectMode', async t => {144 const bigArray = Array.from({length: maxBuffer}).fill('.');145 const {stdout} = await execa('noop.js', {146 maxBuffer,155- stdout: getOutputsGenerator(bigArray, true, true),147+ stdout: getOutputsGenerator(bigArray)(true, true),148 });149 t.is(stdout.length, maxBuffer);150 159- await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputsGenerator([...bigArray, ''], true)}));151+ await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputsGenerator([...bigArray, ''])(true)}));152 });153 162-const timeoutGenerator = async function * (timeout) {163- await setTimeout(timeout);164- yield foobarString;165-};166-154 const testAsyncGenerators = async (t, final) => {155 const {stdout} = await execa('noop.js', {169- maxBuffer,170- stdout: convertTransformToFinal(timeoutGenerator.bind(undefined, 1e2), final),156+ stdout: convertTransformToFinal(timeoutGenerator(1e2)(), final),157 });158 t.is(stdout, foobarString);159 };160 1 unmodified line162 test('Generators "final" is awaited on success', testAsyncGenerators, true);163 164 const testThrowingGenerator = async (t, final) => {165 await t.throwsAsync(180- execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(throwingGenerator, final)}),166+ execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(throwingGenerator(), final)}),167 {message: GENERATOR_ERROR_REGEXP},168 );169 };170 1 unmodified line172 test('Generators "final" errors make subprocess fail', testThrowingGenerator, true);173 174 test('Generators errors make subprocess fail even when other output generators do not throw', async t => {175 await t.throwsAsync(190- execa('noop-fd.js', ['1', foobarString], {stdout: [noopGenerator(false), throwingGenerator, noopGenerator(false)]}),176+ execa('noop-fd.js', ['1', foobarString], {stdout: [noopGenerator(false), throwingGenerator(), noopGenerator(false)]}),177 {message: GENERATOR_ERROR_REGEXP},178 );179 });180 181 test('Generators errors make subprocess fail even when other input generators do not throw', async t => {196- const subprocess = execa('stdin-fd.js', ['0'], {stdin: [noopGenerator(false), throwingGenerator, noopGenerator(false)]});182+ const subprocess = execa('stdin-fd.js', ['0'], {stdin: [noopGenerator(false), throwingGenerator(), noopGenerator(false)]});183 subprocess.stdin.write('foobar\n');184 await t.throwsAsync(subprocess, {message: GENERATOR_ERROR_REGEXP});185 });186 187 const testGeneratorCancel = async (t, error) => {202- const subprocess = execa('noop.js', {stdout: infiniteGenerator});188+ const subprocess = execa('noop.js', {stdout: infiniteGenerator()});189 await once(subprocess.stdout, 'data');190 subprocess.stdout.destroy(error);191 await (error === undefined ? t.notThrowsAsync(subprocess) : t.throwsAsync(subprocess));192 };9 unmodified lines202 t.like(await t.throwsAsync(subprocess), {cause});203 };204 205 test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));220-test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator);206+test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator());207 208 test('Generators are destroyed on early subprocess exit', async t => {223- await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator, uid: -1}));209+ await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator(), uid: -1}));210 });modified:test/stdio/type.js+5 added-5 removed
34 unmodified lines35 test('Cannot use invalid "objectMode" with stdout', testInvalidBinary, 1, 'objectMode');36 test('Cannot use invalid "objectMode" with stderr', testInvalidBinary, 2, 'objectMode');37 test('Cannot use invalid "objectMode" with stdio[*]', testInvalidBinary, 3, 'objectMode');38 39-const testSyncMethods = (t, fdNumber) => {39+const testSyncMethodsGenerator = (t, fdNumber) => {40 t.throws(() => {41 execaSync('empty.js', getStdio(fdNumber, uppercaseGenerator()));42 }, {message: /cannot be a generator/});43 };44 45-test('Cannot use generators with sync methods and stdin', testSyncMethods, 0);46-test('Cannot use generators with sync methods and stdout', testSyncMethods, 1);47-test('Cannot use generators with sync methods and stderr', testSyncMethods, 2);48-test('Cannot use generators with sync methods and stdio[*]', testSyncMethods, 3);45+test('Cannot use generators with sync methods and stdin', testSyncMethodsGenerator, 0);46+test('Cannot use generators with sync methods and stdout', testSyncMethodsGenerator, 1);47+test('Cannot use generators with sync methods and stderr', testSyncMethodsGenerator, 2);48+test('Cannot use generators with sync methods and stdio[*]', testSyncMethodsGenerator, 3);modified:test/stdio/validate.js+4 added-4 removed
9 unmodified lines10 11 // eslint-disable-next-line max-params12 const testGeneratorReturn = async (t, fdNumber, generator, input, objectMode, isInput) => {13 const fixtureName = isInput ? 'stdin-fd.js' : 'noop-fd.js';14- const subprocess = execa(fixtureName, [`${fdNumber}`], getStdio(fdNumber, generator(input, objectMode)));14+ const subprocess = execa(fixtureName, [`${fdNumber}`], getStdio(fdNumber, generator(input)(objectMode)));15 const {message} = await t.throwsAsync(subprocess);16 t.true(message.includes(getMessage(input)));17 };18 8 unmodified lines27 28 return 'a string or an Uint8Array';29 };30 31-const lastInputGenerator = (input, objectMode) => [foobarUint8Array, getOutputGenerator(input, objectMode)];32-const inputGenerator = (input, objectMode) => [...lastInputGenerator(input, objectMode), serializeGenerator(true)];31+const lastInputGenerator = input => objectMode => [foobarUint8Array, getOutputGenerator(input)(objectMode)];32+const inputGenerator = input => objectMode => [...lastInputGenerator(input)(objectMode), serializeGenerator(true)];33 34 test('Generators with result.stdin cannot return an object if not in objectMode', testGeneratorReturn, 0, inputGenerator, foobarObject, false, true);35 test('Generators with result.stdio[*] as input cannot return an object if not in objectMode', testGeneratorReturn, 3, inputGenerator, foobarObject, false, true);36 test('The last generator with result.stdin cannot return an object even in objectMode', testGeneratorReturn, 0, lastInputGenerator, foobarObject, true, true);17 unmodified lines54 test('Generators with result.stdout cannot return undefined if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, undefined, false, false);55 test('Generators with result.stdout cannot return undefined if in objectMode', testGeneratorReturn, 1, getOutputGenerator, undefined, true, false);56 57 test('Generators "final" return value is validated', async t => {58- const subprocess = execa('noop.js', {stdout: convertTransformToFinal(getOutputGenerator(null, true), true)});58+ const subprocess = execa('noop.js', {stdout: convertTransformToFinal(getOutputGenerator(null)(true), true)});59 await t.throwsAsync(subprocess, {message: /not be called at all/});60 });modified:test/stream/subprocess.js+1 added-1 removed
6 unmodified lines7 8 setFixtureDir();9 10 const getStreamInputSubprocess = fdNumber => execa('stdin-fd.js', [`${fdNumber}`], fdNumber === 311- ? getStdio(3, [new Uint8Array(), infiniteGenerator])11+ ? getStdio(3, [new Uint8Array(), infiniteGenerator()])12 : {});13 const getStreamOutputSubprocess = fdNumber => execa('noop-repeat.js', [`${fdNumber}`], fdNumber === 3 ? fullStdio : {});14 15 const assertStreamInputError = (t, {exitCode, signal, isTerminated, failed}) => {102 unmodified linesmodified:index.d.ts+10 added-10 removed
19 unmodified lines20 | 'inherit';21 22 // @todo Use `string`, `Uint8Array` or `unknown` for both the argument and the return type, based on whether `encoding: 'buffer'` and `objectMode: true` are used.23 // See https://github.com/sindresorhus/execa/issues/69424-type StdioTransform = (chunk: unknown) => AsyncGenerator<unknown, void, void> | Generator<unknown, void, void>;25-type StdioFinal = () => AsyncGenerator<unknown, void, void> | Generator<unknown, void, void>;24+type GeneratorTransform = (chunk: unknown) => AsyncGenerator<unknown, void, void> | Generator<unknown, void, void>;25+type GeneratorFinal = () => AsyncGenerator<unknown, void, void> | Generator<unknown, void, void>;26 27-type StdioTransformFull = {28- transform: StdioTransform;29- final?: StdioFinal;27+type GeneratorTransformFull = {28+ transform: GeneratorTransform;29+ final?: GeneratorFinal;30 binary?: boolean;31 preserveNewlines?: boolean;32 objectMode?: boolean;33 };5 unmodified lines39 | undefined40 | URL41 | {file: string}42 | IfAsync<IsSync,43- | StdioTransform44- | StdioTransformFull>;43+ | GeneratorTransform44+ | GeneratorTransformFull>;45 46 type InputStdioOption<IsSync extends boolean = boolean> =47 | Uint8Array48 | Readable70 unmodified lines119 ? OutputOptions[number]120 : OutputOptions121 >;122 123-type IsObjectOutputOption<OutputOption extends StdioSingleOption> = OutputOption extends StdioTransformFull123+type IsObjectOutputOption<OutputOption extends StdioSingleOption> = OutputOption extends GeneratorTransformFull124 ? BooleanObjectMode<OutputOption['objectMode']>125 : false;126 127-type BooleanObjectMode<ObjectModeOption extends StdioTransformFull['objectMode']> = ObjectModeOption extends true ? true : false;127+type BooleanObjectMode<ObjectModeOption extends GeneratorTransformFull['objectMode']> = ObjectModeOption extends true ? true : false;128 129 // Whether `result.stdout|stderr|all` is `undefined`, excluding the `buffer` option130 type IgnoresStreamResult<131 FdNumber extends string,1044 unmodified lines1176 1177 ```1178 import {execa} from 'execa';1179 1180-const arg = 'unicorns'1180+const arg = 'unicorns';1181 const {stdout} = await execa`echo ${arg} & rainbows!`;1182 console.log(stdout);1183 //=> 'unicorns & rainbows!'1184 ```399 unmodified linesmodified:readme.md+1 added-1 removed
97 unmodified lines98 99 ```js100 import {execa} from 'execa';101 102-const arg = 'unicorns'102+const arg = 'unicorns';103 const {stdout} = await execa`echo ${arg} & rainbows!`;104 console.log(stdout);105 //=> 'unicorns & rainbows!'106 ```1119 unmodified lines