Allow setting different `maxBuffer` values for `stdout`/`stderr` (#966)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent c631751 · Browse files · 19 files·+280 added−49 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
19 files+280 added−49 removed
- tests:+98 added−1 removed
- other:+182 added−48 removed
Provenance
- Commit
fdffcb6- Tree
9495eb5- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
c631751
19 files changed+280 added−49 removed
modified:lib/arguments/create.js+1 added-1 removed
58 unmodified lines59606162636358 unmodified lines
return optionValue;};
const DEEP_OPTIONS = new Set(['env']);const DEEP_OPTIONS = new Set(['env', 'maxBuffer']);modified:lib/arguments/options.js+3 added-5 removed
9 unmodified lines1011121314151617187 unmodified lines26272829293031323334358 unmodified lines44454647464849505111 unmodified lines63646566666768697010 unmodified lines818283848586858687885 unmodified lines9 unmodified linesimport {validateEncoding, BINARY_ENCODINGS} from './encoding.js';import {handleNodeOption} from './node.js';import {joinCommand} from './escape.js';import {normalizeCwd, normalizeFileUrl} from './cwd.js';import {normalizeFdSpecificOptions} from './specific.js';
export const handleCommand = (filePath, rawArgs, rawOptions) => { const startTime = getStartTime(); const {command, escapedCommand} = joinCommand(filePath, rawArgs);7 unmodified lines const [processedFile, processedArgs, processedOptions] = handleNodeOption(filePath, rawArgs, rawOptions);
const {command: file, args, options: initialOptions} = crossSpawn._parse(processedFile, processedArgs, processedOptions);
const options = addDefaultOptions(initialOptions); const fdOptions = normalizeFdSpecificOptions(initialOptions); const options = addDefaultOptions(fdOptions); validateTimeout(options); validateEncoding(options); options.shell = normalizeFileUrl(options.shell); options.env = getEnv(options);8 unmodified lines return {file, args, options};};
const addDefaultOptions = ({ maxBuffer = DEFAULT_MAX_BUFFER, buffer = true, stripFinalNewline = true, extendEnv = true, preferLocal = false,11 unmodified lines serialization = 'advanced', ...options}) => ({ ...options, maxBuffer, buffer, stripFinalNewline, extendEnv, preferLocal,10 unmodified lines ipc, serialization,});
const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
const getEnv = ({env: envOption, extendEnv, preferLocal, node, localDir, nodePath}) => { const env = extendEnv ? {...process.env, ...envOption} : envOption;
if (preferLocal || node) {5 unmodified linesadded:lib/arguments/specific.js+74 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import isPlainObject from 'is-plain-obj';import {STANDARD_STREAMS_ALIASES} from '../utils.js';
export const normalizeFdSpecificOptions = options => { const optionBaseArray = Array.from({length: getStdioLength(options)});
const optionsCopy = {...options}; for (const optionName of FD_SPECIFIC_OPTIONS) { const optionArray = normalizeFdSpecificOption(options[optionName], [...optionBaseArray], optionName); optionsCopy[optionName] = addDefaultValue(optionArray, optionName); }
return optionsCopy;};
const getStdioLength = ({stdio}) => Array.isArray(stdio) ? Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length) : STANDARD_STREAMS_ALIASES.length;
const FD_SPECIFIC_OPTIONS = ['maxBuffer'];
const normalizeFdSpecificOption = (optionValue, optionArray, optionName) => isPlainObject(optionValue) ? normalizeOptionObject(optionValue, optionArray, optionName) : optionArray.fill(optionValue);
const normalizeOptionObject = (optionValue, optionArray, optionName) => { for (const [fdName, fdValue] of Object.entries(optionValue)) { for (const fdNumber of parseFdName(fdName, optionName, optionArray)) { optionArray[fdNumber] = fdValue; } }
return optionArray;};
const parseFdName = (fdName, optionName, optionArray) => { const fdNumber = parseFd(fdName); if (fdNumber === undefined || fdNumber === 0) { throw new TypeError(`"${optionName}.${fdName}" is invalid.It must be "${optionName}.stdout", "${optionName}.stderr", "${optionName}.all", or "${optionName}.fd3", "${optionName}.fd4" (and so on).`); }
if (fdNumber >= optionArray.length) { throw new TypeError(`"${optionName}.${fdName}" is invalid: that file descriptor does not exist.Please set the "stdio" option to ensure that file descriptor exists.`); }
return fdNumber === 'all' ? [1, 2] : [fdNumber];};
export const parseFd = fdName => { if (fdName === 'all') { return fdName; }
if (STANDARD_STREAMS_ALIASES.includes(fdName)) { return STANDARD_STREAMS_ALIASES.indexOf(fdName); }
const regexpResult = FD_REGEXP.exec(fdName); if (regexpResult !== null) { return Number(regexpResult[1]); }};
const FD_REGEXP = /^fd(\d+)$/;
const addDefaultValue = (optionArray, optionName) => optionArray.map(optionValue => optionValue === undefined ? DEFAULT_OPTIONS[optionName] : optionValue);
const DEFAULT_OPTIONS = { maxBuffer: 1000 * 1000 * 100,};modified:lib/exit/code.js+2 added-3 removed
1 import {DiscardedError} from '../return/cause.js';2+import {isMaxBufferSync} from '../stream/max-buffer.js';3 4 export const waitForSuccessfulExit = async exitPromise => {5 const [exitCode, signal] = await exitPromise;6 6 unmodified lines13 14 export const getSyncExitResult = ({error, status: exitCode, signal, output}, {maxBuffer}) => {15 const resultError = getResultError(error, exitCode, signal);16 const timedOut = resultError?.code === 'ETIMEDOUT';16- const isMaxBuffer = resultError?.code === 'ENOBUFS'17- && output !== null18- && output.some(result => result !== null && result.length > maxBuffer);17+ const isMaxBuffer = isMaxBufferSync(resultError, output, maxBuffer);18 return {resultError, exitCode, signal, timedOut, isMaxBuffer};19 };20 21 const getResultError = (error, exitCode, signal) => {9 unmodified linesmodified:lib/pipe/validate.js+4 added-14 removed
1 import {normalizeArguments} from '../arguments/normalize.js';2-import {STANDARD_STREAMS_ALIASES} from '../utils.js';2 import {getStartTime} from '../return/duration.js';3 import {serializeOptionValue} from '../stdio/native.js';4+import {parseFd} from '../arguments/specific.js';5 6 export const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...args) => {7 const startTime = getStartTime();8 const {104 unmodified lines113 return fdNumber;114 };115 116 const parseFdNumber = (fdName, isWritable) => {117- if (fdName === 'all') {118- return fdName;117+ const fdNumber = parseFd(fdName);118+ if (fdNumber !== undefined) {119+ return fdNumber;120 }121 121- if (STANDARD_STREAMS_ALIASES.includes(fdName)) {122- return STANDARD_STREAMS_ALIASES.indexOf(fdName);123- }124-125- const regexpResult = FD_REGEXP.exec(fdName);126- if (regexpResult !== null) {127- return Number(regexpResult[1]);128- }129-122 const {validOptions, defaultValue} = isWritable123 ? {validOptions: '"stdin"', defaultValue: 'stdin'}124 : {validOptions: '"stdout", "stderr", "all"', defaultValue: 'stdout'};125 throw new TypeError(`"${getOptionName(isWritable)}" must not be "${fdName}".126 It must be ${validOptions} or "fd3", "fd4" (and so on).127 It is optional and defaults to "${defaultValue}".`);128 };129 138-const FD_REGEXP = /^fd(\d+)$/;139-130 const validateFdNumber = (fdNumber, fdName, isWritable, fileDescriptors) => {131 const fileDescriptor = fileDescriptors[getUsedDescriptor(fdNumber)];132 if (fileDescriptor === undefined) {133 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. That file descriptor does not exist.43 unmodified linesmodified:lib/stdio/handle.js+3 added-5 removed
1+import {getStreamName} from '../utils.js';2 import {getStdioItemType, isRegularUrl, isUnknownStdioString, FILE_TYPES} from './type.js';3 import {getStreamDirection} from './direction.js';4 import {normalizeStdio} from './option.js';5 import {handleNativeStream} from './native.js';12 unmodified lines18 // We make sure passing an array with a single item behaves the same as passing that item without an array.19 // This is what users would expect.20 // For example, `stdout: ['ignore']` behaves the same as `stdout: 'ignore'`.21 const getFileDescriptor = ({stdioOption, fdNumber, addProperties, options, isSync}) => {21- const optionName = getOptionName(fdNumber);22+ const optionName = getStreamName(fdNumber);23 const {stdioItems: initialStdioItems, isStdioArray} = initializeStdioItems({stdioOption, fdNumber, options, optionName});24 const direction = getStreamDirection(initialStdioItems, fdNumber, optionName);25 const stdioItems = initialStdioItems.map(stdioItem => handleNativeStream({stdioItem, isStdioArray, fdNumber, direction, isSync}));26 const normalizedStdioItems = normalizeTransforms(stdioItems, optionName, direction, options);27 const objectMode = getObjectMode(normalizedStdioItems, direction);28 validateFileObjectMode(normalizedStdioItems, objectMode);29 const finalStdioItems = normalizedStdioItems.map(stdioItem => addStreamProperties(stdioItem, addProperties, direction, options));29- return {streamName: optionName, direction, objectMode, stdioItems: finalStdioItems};30+ return {direction, objectMode, stdioItems: finalStdioItems};31 };32 32-const getOptionName = fdNumber => KNOWN_OPTION_NAMES[fdNumber] ?? `stdio[${fdNumber}]`;33-const KNOWN_OPTION_NAMES = ['stdin', 'stdout', 'stderr'];34-33 const initializeStdioItems = ({stdioOption, fdNumber, options, optionName}) => {34 const values = Array.isArray(stdioOption) ? stdioOption : [stdioOption];35 const initialStdioItems = [36 ...values.map(value => initializeStdioItem(value, optionName)),89 unmodified linesmodified:lib/stdio/output-sync.js+2 added-1 removed
1 import {writeFileSync} from 'node:fs';2 import {shouldLogOutput, logLinesSync} from '../verbose/output.js';3+import {getMaxBufferSync} from '../stream/max-buffer.js';4 import {joinToString, joinToUint8Array, bufferToUint8Array, isUint8Array, concatUint8Arrays} from './uint-array.js';5 import {getGenerators, runGeneratorsSync} from './generator.js';6 import {splitLinesSync} from './split.js';7 import {FILE_TYPES} from './type.js';14 unmodified lines22 if (result === null) {23 return;24 }25 25- const truncatedResult = truncateResult(result, isMaxBuffer, maxBuffer);26+ const truncatedResult = truncateResult(result, isMaxBuffer, getMaxBufferSync(maxBuffer));27 const uint8ArrayResult = bufferToUint8Array(truncatedResult);28 const {stdioItems, objectMode} = fileDescriptors[fdNumber];29 const generators = getGenerators(stdioItems);30 const chunks = runOutputGeneratorsSync([uint8ArrayResult], generators, encoding, state);89 unmodified linesmodified:lib/stream/all.js+1 added-1 removed
10 unmodified lines11 stream: subprocess.all,12 fdNumber: 1,13 encoding,14 buffer,15- maxBuffer: maxBuffer * 2,15+ maxBuffer: maxBuffer[1] + maxBuffer[2],16 lines,17 isAll: true,18 allMixed: getAllMixed(subprocess),19 stripFinalNewline,12 unmodified linesmodified:lib/stream/max-buffer.js+22 added-9 removed
1 import {MaxBufferError} from 'get-stream';2+import {getStreamName} from '../utils.js';3 3-export const handleMaxBuffer = ({error, stream, readableObjectMode, lines, encoding, streamName}) => {4+export const handleMaxBuffer = ({error, stream, readableObjectMode, lines, encoding, fdNumber, isAll}) => {5 if (!(error instanceof MaxBufferError)) {5- return;6+ throw error;7 }8 9+ if (isAll) {10+ return error;11+ }12+13 const unit = getMaxBufferUnit(readableObjectMode, lines, encoding);9- error.maxBufferInfo = {unit, streamName};14+ error.maxBufferInfo = {fdNumber, unit};15 stream.destroy();16+ throw error;17 };18 19 const getMaxBufferUnit = (readableObjectMode, lines, encoding) => {20 if (readableObjectMode) {11 unmodified lines32 return 'characters';33 };34 35 export const getMaxBufferMessage = (error, maxBuffer) => {30- const {unit, streamName} = getMaxBufferInfo(error);31- return `Command's ${streamName} was larger than ${maxBuffer} ${unit}`;36+ const {streamName, threshold, unit} = getMaxBufferInfo(error, maxBuffer);37+ return `Command's ${streamName} was larger than ${threshold} ${unit}`;38 };39 34-const getMaxBufferInfo = error => {40+const getMaxBufferInfo = (error, maxBuffer) => {41 if (error?.maxBufferInfo === undefined) {36- return {unit: 'bytes', streamName: 'output'};42+ return {streamName: 'output', threshold: maxBuffer[1], unit: 'bytes'};43 }44 39- const {maxBufferInfo} = error;45+ const {maxBufferInfo: {fdNumber, unit}} = error;46 delete error.maxBufferInfo;41- return maxBufferInfo;47+ return {streamName: getStreamName(fdNumber), threshold: maxBuffer[fdNumber], unit};48 };49+50+export const isMaxBufferSync = (resultError, output, maxBuffer) => resultError?.code === 'ENOBUFS'51+ && output !== null52+ && output.some(result => result !== null && result.length > getMaxBufferSync(maxBuffer));53+54+// `spawnSync()` does not allow differentiating `maxBuffer` per file descriptor, so we always use `stdout`55+export const getMaxBufferSync = maxBuffer => maxBuffer[1];modified:lib/stream/resolve.js+1 added-1 removed
54 unmodified lines55 };56 57 // Read the contents of `subprocess.std*` and|or wait for its completion58 const waitForSubprocessStreams = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) =>59- subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({stream, fdNumber, encoding, buffer, maxBuffer, lines, isAll: false, allMixed: false, stripFinalNewline, verboseInfo, streamInfo}));59+ subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({stream, fdNumber, encoding, buffer, maxBuffer: maxBuffer[fdNumber], lines, isAll: false, allMixed: false, stripFinalNewline, verboseInfo, streamInfo}));60 61 // Transforms replace `subprocess.std*`, which means they are not exposed to users.62 // However, we still want to wait for their completion.63 const waitForOriginalStreams = (originalStreams, subprocess, streamInfo) =>23 unmodified linesmodified:lib/stream/subprocess.js+3 added-5 removed
33 unmodified lines34 return;35 }36 37 const iterable = iterateForResult({stream, onStreamEnd, lines, encoding, stripFinalNewline, allMixed});38- return getStreamContents({stream, iterable, fdNumber, encoding, maxBuffer, lines, streamInfo});38+ return getStreamContents({stream, iterable, fdNumber, encoding, maxBuffer, lines, isAll});39 };40 41 // When using `buffer: false`, users need to read `subprocess.stdout|stderr|all` right away42 // See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r14654963103 unmodified lines46 stream.resume();47 }48 };49 50-const getStreamContents = async ({stream, stream: {readableObjectMode}, iterable, fdNumber, encoding, maxBuffer, lines, streamInfo: {fileDescriptors}}) => {50+const getStreamContents = async ({stream, stream: {readableObjectMode}, iterable, fdNumber, encoding, maxBuffer, lines, isAll}) => {51 try {52 if (readableObjectMode || lines) {53 return await getStreamAsArray(iterable, {maxBuffer});54 }3 unmodified lines58 }59 60 return await getStream(iterable, {maxBuffer});61 } catch (error) {62- const {streamName} = fileDescriptors[fdNumber];63- handleMaxBuffer({error, stream, readableObjectMode, lines, encoding, maxBuffer, streamName});64- throw error;62+ return handleBufferedData(handleMaxBuffer({error, stream, readableObjectMode, lines, encoding, fdNumber, isAll}));63 }64 };65 66 // On failure, `result.stdout|stderr|all` should contain the currently buffered stream14 unmodified linesmodified:lib/sync.js+2 added-1 removed
5 unmodified lines6 import {addInputOptionsSync} from './stdio/input-sync.js';7 import {transformOutputSync, getAllSync} from './stdio/output-sync.js';8 import {logEarlyResult} from './verbose/complete.js';9 import {getSyncExitResult} from './exit/code.js';10+import {getMaxBufferSync} from './stream/max-buffer.js';11 12 export const execaCoreSync = (rawFile, rawArgs, rawOptions) => {13 const {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleSyncArguments(rawFile, rawArgs, rawOptions);14 const result = spawnSubprocessSync({file, args, options, command, escapedCommand, verboseInfo, fileDescriptors, startTime});57 unmodified lines72 return makeEarlyError({error, command, escapedCommand, fileDescriptors, options, startTime, isSync: true});73 }74 };75 75-const normalizeSpawnSyncOptions = ({encoding, ...options}) => ({...options, encoding: 'buffer'});76+const normalizeSpawnSyncOptions = ({encoding, maxBuffer, ...options}) => ({...options, encoding: 'buffer', maxBuffer: getMaxBufferSync(maxBuffer)});77 78 const getSyncResult = ({error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime}) => error === undefined79 ? makeSuccessResult({command, escapedCommand, stdio, all, options, startTime})80 : makeError({14 unmodified linesmodified:lib/utils.js+1 added
3 unmodified lines4 5 export const isStandardStream = stream => STANDARD_STREAMS.includes(stream);6 export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];7 export const STANDARD_STREAMS_ALIASES = ['stdin', 'stdout', 'stderr'];8+export const getStreamName = fdNumber => STANDARD_STREAMS_ALIASES[fdNumber] ?? `stdio[${fdNumber}]`;9 10 export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {11 const maxListeners = eventEmitter.getMaxListeners();12 if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {10 unmodified linesmodified:test/arguments/create.js+10 added
102 unmodified lines103 test('execaNode() bound options are merged multiple times', testMergeMultiple, execaNode);104 test('$ bound options are merged multiple times', testMergeMultiple, $);105 test('$.sync bound options are merged multiple times', testMergeMultiple, $.sync);106 107+const testMergeFdSpecific = async (t, execaMethod) => {108+ const {isMaxBuffer, shortMessage} = await t.throwsAsync(execaMethod({maxBuffer: {stdout: 1}})(NOOP_PATH, [foobarString], {maxBuffer: {stderr: 100}}));109+ t.true(isMaxBuffer);110+ t.true(shortMessage.includes('Command\'s stdout was larger than 1'));111+};112+113+test('execa() bound options merge fd-specific ones', testMergeFdSpecific, execa);114+test('execaNode() bound options merge fd-specific ones', testMergeFdSpecific, execaNode);115+test('$ bound options merge fd-specific ones', testMergeFdSpecific, $);116+117 const testMergeEnvUndefined = async (t, execaMethod) => {118 const {stdout} = await execaMethod({env: {FOO: 'foo'}})(PRINT_ENV_PATH, {env: {BAR: undefined}});119 t.is(stdout, 'foo\nundefined');120 };32 unmodified linesmodified:test/fixtures/noop-both.js+2 added-1 removed
1 unmodified line2 import process from 'node:process';3 import {foobarString} from '../helpers/input.js';4 5 const bytes = process.argv[2] || foobarString;6+const bytesStderr = process.argv[3] || bytes;7 console.log(bytes);7-console.error(bytes);8+console.error(bytesStderr);modified:test/stream/max-buffer.js+86 added
85 unmodified lines86 test('maxBuffer truncates stderr, sync', testMaxBufferLimit, execaSync, 2, false);87 test('maxBuffer truncates stdio[*], sync', testMaxBufferLimit, execaSync, 3, false);88 test('maxBuffer truncates all, sync', testMaxBufferLimit, execaSync, 1, true);89 90+const MAX_BUFFER_DEFAULT = 1e8;91+92+const testMaxBufferDefault = async (t, execaMethod, fdNumber, maxBuffer) => {93+ const length = MAX_BUFFER_DEFAULT;94+ const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {length: MAX_BUFFER_DEFAULT + 1, maxBuffer});95+ assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, length});96+ t.is(stdio[fdNumber], getExpectedOutput(length));97+};98+99+test('maxBuffer has a default value with stdout', testMaxBufferDefault, execa, 1, undefined);100+test('maxBuffer has a default value with stderr', testMaxBufferDefault, execa, 2, undefined);101+test('maxBuffer has a default value with stdio[*]', testMaxBufferDefault, execa, 3, undefined);102+test('maxBuffer has a default value with stdout, sync', testMaxBufferDefault, execaSync, 1, undefined);103+test('maxBuffer has a default value with stderr, sync', testMaxBufferDefault, execaSync, 2, undefined);104+test('maxBuffer has a default value with stdio[*], sync', testMaxBufferDefault, execaSync, 3, undefined);105+test('maxBuffer has a default value with stdout with fd-specific options', testMaxBufferDefault, execa, 1, {stderr: 1e9});106+test('maxBuffer has a default value with stderr with fd-specific options', testMaxBufferDefault, execa, 2, {stdout: 1e9});107+test('maxBuffer has a default value with stdio[*] with fd-specific options', testMaxBufferDefault, execa, 3, {stdout: 1e9});108+test('maxBuffer has a default value with stdout with empty fd-specific options', testMaxBufferDefault, execa, 1, {});109+110+const testFdSpecific = async (t, fdNumber, fdName, execaMethod) => {111+ const length = 1;112+ const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {maxBuffer: {[fdName]: length}});113+ assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, length});114+ t.is(stdio[fdNumber], getExpectedOutput(length));115+};116+117+test('maxBuffer truncates file descriptors with fd-specific options, stdout', testFdSpecific, 1, 'stdout', execa);118+test('maxBuffer truncates file descriptors with fd-specific options, fd1', testFdSpecific, 1, 'fd1', execa);119+test('maxBuffer truncates file descriptors with fd-specific options, stderr', testFdSpecific, 2, 'stderr', execa);120+test('maxBuffer truncates file descriptors with fd-specific options, fd2', testFdSpecific, 2, 'fd2', execa);121+test('maxBuffer truncates file descriptors with fd-specific options, stdout, all', testFdSpecific, 1, 'all', execa);122+test('maxBuffer truncates file descriptors with fd-specific options, stderr, all', testFdSpecific, 2, 'all', execa);123+test('maxBuffer truncates file descriptors with fd-specific options, fd3', testFdSpecific, 3, 'fd3', execa);124+test('maxBuffer.stdout is used for stdout with fd-specific options, stdout, sync', testFdSpecific, 1, 'stdout', execaSync);125+126+test('maxBuffer does not affect other file descriptors with fd-specific options', async t => {127+ const {isMaxBuffer} = await getMaxBufferSubprocess(execa, 2, {maxBuffer: {stdout: 1}});128+ t.false(isMaxBuffer);129+});130+131+test('maxBuffer.stdout is used for other file descriptors with fd-specific options, sync', async t => {132+ const length = 1;133+ const {shortMessage, stderr} = await runMaxBuffer(t, execaSync, 2, {maxBuffer: {stdout: length}});134+ assertErrorMessage(t, shortMessage, {execaMethod: execaSync, fdNumber: 2, length});135+ t.is(stderr, getExpectedOutput(length));136+});137+138+const testAll = async (t, shouldFail) => {139+ const difference = shouldFail ? 0 : 1;140+ const maxBufferStdout = 2;141+ const maxBufferStderr = 4 - difference;142+ const {isMaxBuffer, shortMessage, stdout, stderr, all} = await execa(143+ 'noop-both.js',144+ ['\n'.repeat(maxBufferStdout - 1), '\n'.repeat(maxBufferStderr - difference)],145+ {maxBuffer: {stdout: maxBufferStdout, stderr: maxBufferStderr}, all: true, stripFinalNewline: false, reject: false},146+ );147+ t.is(isMaxBuffer, shouldFail);148+ if (shouldFail) {149+ assertErrorMessage(t, shortMessage, {fdNumber: 2, length: maxBufferStderr});150+ }151+152+ t.is(stdout, '\n'.repeat(maxBufferStdout));153+ t.is(stderr, '\n'.repeat(maxBufferStderr));154+ t.is(all, '\n'.repeat(maxBufferStdout + maxBufferStderr));155+};156+157+test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, below threshold', testAll, false);158+test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, above threshold', testAll, true);159+160+const testInvalidFd = async (t, fdName, execaMethod) => {161+ const {message} = t.throws(() => {162+ execaMethod('empty.js', {maxBuffer: {[fdName]: 0}});163+ });164+ t.true(message.includes(`"maxBuffer.${fdName}" is invalid`));165+};166+167+test('maxBuffer.stdin is invalid', testInvalidFd, 'stdin', execa);168+test('maxBuffer.fd0 is invalid', testInvalidFd, 'fd0', execa);169+test('maxBuffer.other is invalid', testInvalidFd, 'other', execa);170+test('maxBuffer.fd10 is invalid', testInvalidFd, 'fd10', execa);171+test('maxBuffer.stdin is invalid, sync', testInvalidFd, 'stdin', execaSync);172+test('maxBuffer.fd0 is invalid, sync', testInvalidFd, 'fd0', execaSync);173+test('maxBuffer.other is invalid, sync', testInvalidFd, 'other', execaSync);174+test('maxBuffer.fd10 is invalid, sync', testInvalidFd, 'fd10', execaSync);175+176 const testMaxBufferEncoding = async (t, execaMethod, fdNumber) => {177 const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {encoding: 'buffer'});178 assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, unit: 'bytes'});179 const stream = stdio[fdNumber];81 unmodified linesmodified:index.d.ts+32 added-1 removed
354 unmodified lines355 WideOptions extends CommonOptions,356 StrictOptions extends CommonOptions,357 > = WideOptions extends StrictOptions ? WideOptions : StrictOptions;358 359+type FdGenericOption<OptionType> = OptionType | {360+ readonly [FdName in FromOption]?: OptionType361+};362+363 type CommonOptions<IsSync extends boolean = boolean> = {364 /**365 Prefer locally installed binaries when looking for a binary to execute.366 232 unmodified lines599 - If the `encoding` option is `'buffer'`: in bytes.600 - If the `lines` option is `true`: in lines.601 - If a transform in object mode is used: in objects.602 603+ By default, this applies to both `stdout` and `stderr`, but different values can also be passed.604+605 @default 100_000_000606 */601- readonly maxBuffer?: number;607+ readonly maxBuffer?: FdGenericOption<number>;608 609 /**610 Signal used to terminate the subprocess when:611 - using the `cancelSignal`, `timeout`, `maxBuffer` or `cleanup` option131 unmodified lines743 */744 readonly cancelSignal?: Unless<IsSync, AbortSignal>;745 };746 747+/**748+Subprocess options.749+750+Some options are related to the subprocess output: `maxBuffer`. By default, those options apply to all file descriptors (`stdout`, `stderr`, etc.). A plain object can be passed instead to apply them to only `stdout`, `stderr`, `fd3`, etc.751+752+@example753+754+```755+await execa('./run.js', {maxBuffer: 1e6}) // Same value for stdout and stderr756+await execa('./run.js', {maxBuffer: {stdout: 1e4, stderr: 1e6}}) // Different values757+```758+*/759 export type Options = CommonOptions<false>;760+761+/**762+Subprocess options, with synchronous methods.763+764+Some options are related to the subprocess output: `maxBuffer`. By default, those options apply to all file descriptors (`stdout`, `stderr`, etc.). A plain object can be passed instead to apply them to only `stdout`, `stderr`, `fd3`, etc.765+766+@example767+768+```769+execaSync('./run.js', {maxBuffer: 1e6}) // Same value for stdout and stderr770+execaSync('./run.js', {maxBuffer: {stdout: 1e4, stderr: 1e6}}) // Different values771+```772+*/773 export type SyncOptions = CommonOptions<true>;774 775 declare abstract class CommonResult<776 IsSync extends boolean = boolean,950 unmodified linesmodified:index.test-d.ts+21 added
1467 unmodified lines1468 execaSync('unicorns', {encoding: 'ascii'});1469 expectError(execa('unicorns', {encoding: 'unknownEncoding'}));1470 expectError(execaSync('unicorns', {encoding: 'unknownEncoding'}));1471 1472+execa('unicorns', {maxBuffer: {}});1473+expectError(execa('unicorns', {maxBuffer: []}));1474+execa('unicorns', {maxBuffer: {stdout: 0}});1475+execa('unicorns', {maxBuffer: {stderr: 0}});1476+execa('unicorns', {maxBuffer: {stdout: 0, stderr: 0} as const});1477+execa('unicorns', {maxBuffer: {all: 0}});1478+execa('unicorns', {maxBuffer: {fd1: 0}});1479+execa('unicorns', {maxBuffer: {fd2: 0}});1480+execa('unicorns', {maxBuffer: {fd3: 0}});1481+expectError(execa('unicorns', {maxBuffer: {stdout: '0'}}));1482+execaSync('unicorns', {maxBuffer: {}});1483+expectError(execaSync('unicorns', {maxBuffer: []}));1484+execaSync('unicorns', {maxBuffer: {stdout: 0}});1485+execaSync('unicorns', {maxBuffer: {stderr: 0}});1486+execaSync('unicorns', {maxBuffer: {stdout: 0, stderr: 0} as const});1487+execaSync('unicorns', {maxBuffer: {all: 0}});1488+execaSync('unicorns', {maxBuffer: {fd1: 0}});1489+execaSync('unicorns', {maxBuffer: {fd2: 0}});1490+execaSync('unicorns', {maxBuffer: {fd3: 0}});1491+expectError(execaSync('unicorns', {maxBuffer: {stdout: '0'}}));1492+1493 expectError(execa('unicorns', {stdio: []}));1494 expectError(execaSync('unicorns', {stdio: []}));1495 expectError(execa('unicorns', {stdio: ['pipe']}));1496 expectError(execaSync('unicorns', {stdio: ['pipe']}));2303 unmodified linesmodified:readme.md+10 added-1 removed
752 unmodified lines753 ### options754 755 Type: `object`756 757-This lists all Execa options, including some options which are the same as for [`child_process#spawn()`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options)/[`child_process#exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback).757+This lists all options for [`execa()`](#execafile-arguments-options) and the [other methods](#methods).758 759+Some options are related to the subprocess output: [`maxBuffer`](#maxbuffer). By default, those options apply to all file descriptors (`stdout`, `stderr`, etc.). A plain object can be passed instead to apply them to only `stdout`, `stderr`, `fd3`, etc.760+761+```js762+await execa('./run.js', {maxBuffer: 1e6}) // Same value for stdout and stderr763+await execa('./run.js', {maxBuffer: {stdout: 1e4, stderr: 1e6}}) // Different values764+```765+766 #### reject767 768 Type: `boolean`\769 Default: `true`246 unmodified lines1016 - If the [`encoding` option](#encoding) is `'buffer'`: in bytes.1017 - If the [`lines` option](#lines) is `true`: in lines.1018 - If a [transform in object mode](docs/transform.md#object-mode) is used: in objects.1019 1020+By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](#options).1021+1022 #### ipc1023 1024 Type: `boolean`\1025 Default: `true` if the [`node`](#node) option is enabled, `false` otherwise227 unmodified lines