Add `error.isMaxBuffer` (#963)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 58beaa6 · Browse files · 15 files·+195 added−67 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+195 added−67 removed
- tests:+100 added−53 removed
- other:+95 added−14 removed
Provenance
- Commit
9e6e19e- Tree
3fb63e2- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
58beaa6
15 files changed+195 added−67 removed
modified:docs/scripts.md+2 added
555 unmodified lines556 failed,557 timedOut,558 isCanceled,559 isTerminated,560+ isMaxBuffer,561 // and other error-related properties: code, etc.562 } = await $({timeout: 1})`sleep 2`;563 // ExecaError: Command timed out after 1 milliseconds: sleep 2564 // at file:///home/me/Desktop/example.js:2:207 unmodified lines572 // failed: true,573 // timedOut: true,574 // isCanceled: false,575 // isTerminated: true,576+// isMaxBuffer: false,577 // signal: 'SIGTERM',578 // signalDescription: 'Termination',579 // stdout: '',580 // stderr: '',268 unmodified linesmodified:lib/return/error.js+16 added-3 removed
1 unmodified line2 import stripFinalNewline from 'strip-final-newline';3 import {isUint8Array, uint8ArrayToString} from '../stdio/uint-array.js';4 import {fixCwdError} from '../arguments/cwd.js';5 import {escapeLines} from '../arguments/escape.js';6+import {getMaxBufferMessage} from '../stream/max-buffer.js';7 import {getDurationMs} from './duration.js';8 import {getFinalError, DiscardedError, isExecaError} from './cause.js';9 10 export const makeSuccessResult = ({11 unmodified lines22 failed: false,23 timedOut: false,24 isCanceled: false,25 isTerminated: false,26+ isMaxBuffer: false,27 exitCode: 0,28 stdout: stdio[1],29 stderr: stdio[2],30 all,15 unmodified lines46 escapedCommand,47 startTime,48 timedOut: false,49 isCanceled: false,50+ isMaxBuffer: false,51 stdio: Array.from({length: fileDescriptors.length}),52 options,53 isSync,54 });4 unmodified lines59 escapedCommand,60 startTime,61 timedOut,62 isCanceled,63+ isMaxBuffer,64 exitCode: rawExitCode,65 signal: rawSignal,66 stdio,67 all,64- options: {timeoutDuration, timeout = timeoutDuration, cwd},68+ options: {timeoutDuration, timeout = timeoutDuration, cwd, maxBuffer},69 isSync,70 }) => {71 const {exitCode, signal, signalDescription} = normalizeExitPayload(rawExitCode, rawSignal);72 const {originalMessage, shortMessage, message} = createMessages({5 unmodified lines78 exitCode,79 escapedCommand,80 timedOut,81 isCanceled,82+ isMaxBuffer,83+ maxBuffer,84 timeout,85 cwd,86 });87 const error = getFinalError(originalError, message, isSync);8 unmodified lines96 error.failed = true;97 error.timedOut = timedOut;98 error.isCanceled = isCanceled;99 error.isTerminated = signal !== undefined;100+ error.isMaxBuffer = isMaxBuffer;101 error.exitCode = exitCode;102 error.signal = signal;103 error.signalDescription = signalDescription;104 error.code = error.cause?.code;29 unmodified lines134 exitCode,135 escapedCommand,136 timedOut,137 isCanceled,138+ isMaxBuffer,139+ maxBuffer,140 timeout,141 cwd,142 }) => {143 const errorCode = originalError?.code;135- const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});144+ const prefix = getErrorPrefix({originalError, timedOut, timeout, isMaxBuffer, maxBuffer, errorCode, signal, signalDescription, exitCode, isCanceled});145 const originalMessage = getOriginalMessage(originalError, cwd);146 const newline = originalMessage === '' ? '' : '\n';147 const shortMessage = `${prefix}: ${escapedCommand}${newline}${originalMessage}`;148 const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all];3 unmodified lines152 .join('\n\n');153 return {originalMessage, shortMessage, message};154 };155 147-const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {156+const getErrorPrefix = ({originalError, timedOut, timeout, isMaxBuffer, maxBuffer, errorCode, signal, signalDescription, exitCode, isCanceled}) => {157 if (timedOut) {158 return `Command timed out after ${timeout} milliseconds`;159 }160 161 if (isCanceled) {162 return 'Command was canceled';163 }164 165+ if (isMaxBuffer) {166+ return getMaxBufferMessage(originalError, maxBuffer);167+ }168+169 if (errorCode !== undefined) {170 return `Command failed with ${errorCode}`;171 }172 37 unmodified linesmodified:lib/stdio/handle.js+1 added-1 removed
24 unmodified lines2526272829293031323394 unmodified lines24 unmodified lines const normalizedStdioItems = normalizeTransforms(stdioItems, optionName, direction, options); const objectMode = getObjectMode(normalizedStdioItems, direction); validateFileObjectMode(normalizedStdioItems, objectMode); const finalStdioItems = normalizedStdioItems.map(stdioItem => addStreamProperties(stdioItem, addProperties, direction, options)); return {direction, objectMode, stdioItems: finalStdioItems}; return {streamName: optionName, direction, objectMode, stdioItems: finalStdioItems};};
const getOptionName = fdNumber => KNOWN_OPTION_NAMES[fdNumber] ?? `stdio[${fdNumber}]`;const KNOWN_OPTION_NAMES = ['stdin', 'stdout', 'stderr'];94 unmodified linesadded:lib/stream/max-buffer.js+42 added
123456789101112131415161718192021222324252627282930313233343536373839404142import {MaxBufferError} from 'get-stream';
export const handleMaxBuffer = ({error, stream, readableObjectMode, lines, encoding, streamName}) => { if (!(error instanceof MaxBufferError)) { return; }
const unit = getMaxBufferUnit(readableObjectMode, lines, encoding); error.maxBufferInfo = {unit, streamName}; stream.destroy();};
const getMaxBufferUnit = (readableObjectMode, lines, encoding) => { if (readableObjectMode) { return 'objects'; }
if (lines) { return 'lines'; }
if (encoding === 'buffer') { return 'bytes'; }
return 'characters';};
export const getMaxBufferMessage = (error, maxBuffer) => { const {unit, streamName} = getMaxBufferInfo(error); return `Command's ${streamName} was larger than ${maxBuffer} ${unit}`;};
const getMaxBufferInfo = error => { if (error?.maxBufferInfo === undefined) { return {unit: 'bytes', streamName: 'output'}; }
const {maxBufferInfo} = error; delete error.maxBufferInfo; return maxBufferInfo;};modified:lib/stream/subprocess.js+7 added-8 removed
1 import {setImmediate} from 'node:timers/promises';2-import getStream, {getStreamAsArrayBuffer, getStreamAsArray, MaxBufferError} from 'get-stream';2+import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';3 import {iterateForResult} from '../convert/loop.js';4 import {isArrayBuffer} from '../stdio/uint-array.js';5 import {shouldLogOutput, logLines} from '../verbose/output.js';6+import {handleMaxBuffer} from './max-buffer.js';7 import {waitForStream, isInputFileDescriptor} from './wait.js';8 9 export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, isAll, allMixed, stripFinalNewline, verboseInfo, streamInfo}) => {10 if (!stream) {23 unmodified lines34 return;35 }36 37 const iterable = iterateForResult({stream, onStreamEnd, lines, encoding, stripFinalNewline, allMixed});37- return getStreamContents({stream, iterable, encoding, maxBuffer, lines});38+ return getStreamContents({stream, iterable, fdNumber, encoding, maxBuffer, lines, streamInfo});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 49-const getStreamContents = async ({stream, iterable, encoding, maxBuffer, lines}) => {50+const getStreamContents = async ({stream, stream: {readableObjectMode}, iterable, fdNumber, encoding, maxBuffer, lines, streamInfo: {fileDescriptors}}) => {51 try {51- if (stream.readableObjectMode || lines) {52+ if (readableObjectMode || lines) {53 return await getStreamAsArray(iterable, {maxBuffer});54 }55 56 if (encoding === 'buffer') {1 unmodified line58 }59 60 return await getStream(iterable, {maxBuffer});61 } catch (error) {61- if (error instanceof MaxBufferError) {62- stream.destroy();63- }64-62+ const {streamName} = fileDescriptors[fdNumber];63+ handleMaxBuffer({error, stream, readableObjectMode, lines, encoding, maxBuffer, streamName});64 throw error;65 }66 };67 15 unmodified linesmodified:lib/async.js+2 added
1 import {setMaxListeners} from 'node:events';2 import {spawn} from 'node:child_process';3+import {MaxBufferError} from 'get-stream';4 import {handleCommand, handleOptions} from './arguments/options.js';5 import {makeError, makeSuccessResult} from './return/error.js';6 import {stripNewline, handleResult} from './return/output.js';7 import {handleEarlyError} from './return/early-error.js';86 unmodified lines94 command,95 escapedCommand,96 timedOut: context.timedOut,97 isCanceled: options.signal?.aborted === true,98+ isMaxBuffer: errorInfo.error instanceof MaxBufferError,99 exitCode,100 signal,101 stdio,102 all,5 unmodified linesmodified:lib/sync.js+3 added-2 removed
57 unmodified lines58 const {resultError, exitCode, signal, timedOut, isMaxBuffer} = getSyncExitResult(syncResult, options);59 const {output, error = resultError} = transformOutputSync({fileDescriptors, syncResult, options, isMaxBuffer, verboseInfo});60 const stdio = output.map(stdioOutput => stripNewline(stdioOutput, options));61 const all = stripNewline(getAllSync(output, options), options);62- return getSyncResult({error, exitCode, signal, timedOut, stdio, all, options, command, escapedCommand, startTime});62+ return getSyncResult({error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime});63 };64 65 const runSubprocessSync = ({file, args, options, command, escapedCommand, fileDescriptors, startTime}) => {66 try {6 unmodified lines73 };74 75 const normalizeSpawnSyncOptions = ({encoding, ...options}) => ({...options, encoding: 'buffer'});76 77-const getSyncResult = ({error, exitCode, signal, timedOut, stdio, all, options, command, escapedCommand, startTime}) => error === undefined77+const getSyncResult = ({error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime}) => error === undefined78 ? makeSuccessResult({command, escapedCommand, stdio, all, options, startTime})79 : makeError({80 error,81 command,82 escapedCommand,83 timedOut,84 isCanceled: false,85+ isMaxBuffer,86 exitCode,87 signal,88 stdio,89 all,4 unmodified linesadded:test/helpers/max-buffer.js+12 added
123456789101112import {execa, execaSync} from '../../index.js';
export const maxBuffer = 10;
export const assertErrorMessage = (t, shortMessage, {execaMethod = execa, length = maxBuffer, fdNumber = 1, unit = 'characters'} = {}) => { const [expectedStreamName, expectedUnit] = execaMethod === execaSync ? ['output', 'bytes'] : [STREAM_NAMES[fdNumber], unit]; t.true(shortMessage.includes(`${expectedStreamName} was larger than ${length} ${expectedUnit}`));};
const STREAM_NAMES = ['stdin', 'stdout', 'stderr', 'stdio[3]'];modified:test/return/error.js+2 added
20 unmodified lines21 'failed',22 'timedOut',23 'isCanceled',24 'isTerminated',25+ 'isMaxBuffer',26 'exitCode',27 'stdout',28 'stderr',29 'all',20 unmodified lines50 'failed',51 'timedOut',52 'isCanceled',53 'isTerminated',54+ 'isMaxBuffer',55 'exitCode',56 'signal',57 'signalDescription',58 'code',172 unmodified linesmodified:test/stdio/lines.js+15 added-9 removed
1 import {Writable} from 'node:stream';2 import test from 'ava';3-import {MaxBufferError} from 'get-stream';3 import {execa, execaSync} from '../../index.js';4 import {setFixtureDir} from '../helpers/fixtures-dir.js';5 import {fullStdio} from '../helpers/stdio.js';6 import {getOutputsGenerator} from '../helpers/generator.js';8 unmodified lines15 simpleLines,16 simpleFullEndLines,17 noNewlinesChunks,18 } from '../helpers/lines.js';19+import {assertErrorMessage} from '../helpers/max-buffer.js';20 21 setFixtureDir();22 23 const getSimpleChunkSubprocessAsync = options => getSimpleChunkSubprocess(execa, options);99 unmodified lines123 124 test('"lines: true" is a noop with "buffer: false"', testLinesNoBuffer, execa);125 test('"lines: true" is a noop with "buffer: false", sync', testLinesNoBuffer, execaSync);126 127+const maxBuffer = simpleLines.length - 1;128+129 test('"lines: true" can be below "maxBuffer"', async t => {128- const maxBuffer = simpleLines.length;129- const {stdout} = await getSimpleChunkSubprocessAsync({maxBuffer});130+ const {isMaxBuffer, stdout} = await getSimpleChunkSubprocessAsync({maxBuffer: maxBuffer + 1});131+ t.false(isMaxBuffer);132 t.deepEqual(stdout, noNewlinesChunks);133 });134 135 test('"lines: true" can be above "maxBuffer"', async t => {134- const maxBuffer = simpleLines.length - 1;135- const {cause, stdout} = await t.throwsAsync(getSimpleChunkSubprocessAsync({maxBuffer}));136- t.true(cause instanceof MaxBufferError);136+ const {isMaxBuffer, shortMessage, stdout} = await t.throwsAsync(getSimpleChunkSubprocessAsync({maxBuffer}));137+ t.true(isMaxBuffer);138+ assertErrorMessage(t, shortMessage, {length: maxBuffer, unit: 'lines'});139 t.deepEqual(stdout, noNewlinesChunks.slice(0, maxBuffer));140 });141 142 test('"maxBuffer" is measured in lines with "lines: true"', async t => {141- const {stdout} = await t.throwsAsync(execa('noop-repeat.js', ['1', '...\n'], {lines: true, maxBuffer: 2}));143+ const {isMaxBuffer, shortMessage, stdout} = await t.throwsAsync(execa('noop-repeat.js', ['1', '...\n'], {lines: true, maxBuffer}));144+ t.true(isMaxBuffer);145+ assertErrorMessage(t, shortMessage, {length: maxBuffer, unit: 'lines'});146 t.deepEqual(stdout, ['...', '...']);147 });148 149 test('"maxBuffer" is measured in bytes with "lines: true", sync', t => {146- const {stdout} = t.throws(() => {147- execaSync('noop-repeat.js', ['1', '...\n'], {lines: true, maxBuffer: 2});150+ const {isMaxBuffer, shortMessage, stdout} = t.throws(() => {151+ execaSync('noop-repeat.js', ['1', '...\n'], {lines: true, maxBuffer});152 }, {code: 'ENOBUFS'});153+ t.true(isMaxBuffer);154+ assertErrorMessage(t, shortMessage, {execaMethod: execaSync, length: maxBuffer});155 t.deepEqual(stdout, ['..']);156 });157 158 test('"lines: true" stops on stream error', async t => {70 unmodified linesmodified:test/stdio/transform.js+11 added-6 removed
16 unmodified lines17 } from '../helpers/generator.js';18 import {generatorsMap} from '../helpers/map.js';19 import {defaultHighWaterMark} from '../helpers/stream.js';20 import {setFixtureDir} from '../helpers/fixtures-dir.js';21+import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';22 23 setFixtureDir();24 25 const testGeneratorFinal = async (t, fixtureName, execaMethod) => {117 unmodified lines143 144 test('Generator "transform" yields are sent right away', testManyYields, false);145 test('Generator "final" yields are sent right away', testManyYields, true);146 146-const maxBuffer = 10;147-147 const testMaxBuffer = async (t, type) => {148 const bigString = '.'.repeat(maxBuffer);149 const {stdout} = await execa('noop.js', {150 maxBuffer,151 stdout: generatorsMap[type].getOutput(bigString)(false, true),152 });153 t.is(stdout, bigString);154 156- await t.throwsAsync(execa('noop.js', {155+ const {isMaxBuffer, shortMessage} = await t.throwsAsync(execa('noop.js', {156 maxBuffer,157 stdout: generatorsMap[type].getOutput(`${bigString}.`)(false, true),158 }));159+ t.true(isMaxBuffer);160+ assertErrorMessage(t, shortMessage);161 };162 163 test('Generators take "maxBuffer" into account', testMaxBuffer, 'generator');164 test('Duplexes take "maxBuffer" into account', testMaxBuffer, 'duplex');165 test('WebTransforms take "maxBuffer" into account', testMaxBuffer, 'webTransform');166 167 test('Generators does not take "maxBuffer" into account, sync', t => {168 const bigString = '.'.repeat(maxBuffer);168- const {stdout} = execaSync('noop.js', {169+ const {isMaxBuffer, stdout} = execaSync('noop.js', {170 maxBuffer,171 stdout: generatorsMap.generator.getOutput(`${bigString}.`)(false, true),172 });173+ t.false(isMaxBuffer);174 t.is(stdout.length, maxBuffer + 1);175 });176 177 const testMaxBufferObject = async (t, type) => {3 unmodified lines181 stdout: generatorsMap[type].getOutputs(bigArray)(true, true),182 });183 t.is(stdout.length, maxBuffer);184 183- await t.throwsAsync(execa('noop.js', {185+ const {isMaxBuffer, shortMessage} = await t.throwsAsync(execa('noop.js', {186 maxBuffer,187 stdout: generatorsMap[type].getOutputs([...bigArray, ''])(true, true),188 }));189+ t.true(isMaxBuffer);190+ assertErrorMessage(t, shortMessage, {unit: 'objects'});191 };192 193 test('Generators take "maxBuffer" into account, objectMode', testMaxBufferObject, 'generator');194 test('Duplexes take "maxBuffer" into account, objectMode', testMaxBufferObject, 'duplex');195 test('WebTransforms take "maxBuffer" into account, objectMode', testMaxBufferObject, 'webTransform');196 197 test('Generators does not take "maxBuffer" into account, objectMode, sync', t => {198 const bigArray = Array.from({length: maxBuffer}).fill('..');195- const {stdout} = execaSync('noop.js', {199+ const {isMaxBuffer, stdout} = execaSync('noop.js', {200 maxBuffer,201 stdout: generatorsMap.generator.getOutputs([...bigArray, ''])(true, true),202 });203+ t.false(isMaxBuffer);204 t.is(stdout.length, maxBuffer + 1);205 });206 207 const testAsyncGenerators = async (t, type, final) => {90 unmodified linesmodified:test/stream/max-buffer.js+60 added-38 removed
2 unmodified lines3 import getStream from 'get-stream';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDir} from '../helpers/fixtures-dir.js';6 import {fullStdio} from '../helpers/stdio.js';7+import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';8+import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';9 10 setFixtureDir();11 10-const maxBuffer = 10;11-const maxBufferMessage = /maxBuffer exceeded/;12+const maxBufferMessage = {message: /maxBuffer exceeded/};13+const maxBufferCodeSync = {code: 'ENOBUFS'};14 13-const runMaxBuffer = (t, execaMethod, fdNumber, options) => execaMethod === execa14- ? t.throwsAsync(getMaxBufferSubprocess(execaMethod, fdNumber, options), {message: maxBufferMessage})15- : t.throws(() => {16- getMaxBufferSubprocess(execaMethod, fdNumber, options);17- }, {code: 'ENOBUFS'});15+const runMaxBuffer = async (t, execaMethod, fdNumber, options) => {16+ const error = execaMethod === execa17+ ? await t.throwsAsync(getMaxBufferSubprocess(execaMethod, fdNumber, options), maxBufferMessage)18+ : t.throws(() => {19+ getMaxBufferSubprocess(execaMethod, fdNumber, options);20+ }, maxBufferCodeSync);21+ t.true(error.isMaxBuffer);22+ t.is(error.maxBufferInfo, undefined);23+ return error;24+};25 26 const getMaxBufferSubprocess = (execaMethod, fdNumber, {length = maxBuffer, ...options} = {}) =>27 execaMethod('max-buffer.js', [`${fdNumber}`, `${length + 1}`], {...fullStdio, maxBuffer, ...options});28 29 const getExpectedOutput = (length = maxBuffer) => '.'.repeat(length);30 24-const testMaxBufferSuccess = async (t, fdNumber, all) => {25- await t.notThrowsAsync(getMaxBufferSubprocess(execa, fdNumber, {all, length: maxBuffer - 1}));31+const testMaxBufferSuccess = async (t, execaMethod, fdNumber, all) => {32+ const {isMaxBuffer} = await getMaxBufferSubprocess(execaMethod, fdNumber, {all, length: maxBuffer - 1});33+ t.false(isMaxBuffer);34 };35 28-test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, 1, false);29-test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, 2, false);30-test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, 3, false);31-test('maxBuffer does not affect all if too high', testMaxBufferSuccess, 1, true);36+test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, execa, 1, false);37+test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, execa, 2, false);38+test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, execa, 3, false);39+test('maxBuffer does not affect all if too high', testMaxBufferSuccess, execa, 1, true);40+test('maxBuffer does not affect stdout if too high, sync', testMaxBufferSuccess, execaSync, 1, false);41+test('maxBuffer does not affect stderr if too high, sync', testMaxBufferSuccess, execaSync, 2, false);42+test('maxBuffer does not affect stdio[*] if too high, sync', testMaxBufferSuccess, execaSync, 3, false);43+test('maxBuffer does not affect all if too high, sync', testMaxBufferSuccess, execaSync, 1, true);44 33-const testMaxBufferSuccessSync = (t, fdNumber, all) => {34- t.notThrows(() => {35- getMaxBufferSubprocess(execaSync, fdNumber, {all, length: maxBuffer - 1});36- });37-};38-39-test('maxBuffer does not affect stdout if too high, sync', testMaxBufferSuccessSync, 1, false);40-test('maxBuffer does not affect stderr if too high, sync', testMaxBufferSuccessSync, 2, false);41-test('maxBuffer does not affect stdio[*] if too high, sync', testMaxBufferSuccessSync, 3, false);42-test('maxBuffer does not affect all if too high, sync', testMaxBufferSuccessSync, 1, true);43-45 const testGracefulExit = async (t, fixtureName, expectedExitCode) => {45- const {exitCode, signal, stdout} = await t.throwsAsync(46+ const {isMaxBuffer, shortMessage, exitCode, signal, stdout} = await t.throwsAsync(47 execa(fixtureName, ['1', '.'.repeat(maxBuffer + 1)], {maxBuffer}),47- {message: maxBufferMessage},48+ maxBufferMessage,49 );50+ t.true(isMaxBuffer);51+ assertErrorMessage(t, shortMessage);52 t.is(exitCode, expectedExitCode);53 t.is(signal, undefined);54 t.is(stdout, getExpectedOutput());55 };1 unmodified line57 test('maxBuffer terminates stream gracefully, more writes', testGracefulExit, 'noop-repeat.js', 1);58 test('maxBuffer terminates stream gracefully, no more writes', testGracefulExit, 'noop-fd.js', 0);59 60 const testGracefulExitSync = (t, fixtureName) => {58- const {exitCode, signal, stdout} = t.throws(() => {61+ const {isMaxBuffer, shortMessage, exitCode, signal, stdout} = t.throws(() => {62 execaSync(fixtureName, ['1', '.'.repeat(maxBuffer + 1)], {maxBuffer, killSignal: 'SIGINT'});60- }, {code: 'ENOBUFS'});63+ }, maxBufferCodeSync);64+ t.true(isMaxBuffer);65+ assertErrorMessage(t, shortMessage, {execaMethod: execaSync});66 t.is(exitCode, undefined);67 t.is(signal, 'SIGINT');68 t.is(stdout, getExpectedOutput());69 };2 unmodified lines72 test('maxBuffer terminate stream with killSignal, no more writes, sync', testGracefulExitSync, 'noop-fd.js');73 74 const testMaxBufferLimit = async (t, execaMethod, fdNumber, all) => {75 const length = all && execaMethod === execa ? maxBuffer * 2 : maxBuffer;71- const result = await runMaxBuffer(t, execaMethod, fdNumber, {all, length});72- t.is(all ? result.all : result.stdio[fdNumber], getExpectedOutput(length));76+ const {shortMessage, all: allOutput, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {all, length});77+ assertErrorMessage(t, shortMessage, {execaMethod, fdNumber});78+ t.is(all ? allOutput : stdio[fdNumber], getExpectedOutput(length));79 };80 81 test('maxBuffer truncates stdout', testMaxBufferLimit, execa, 1, false);82 test('maxBuffer truncates stderr', testMaxBufferLimit, execa, 2, false);4 unmodified lines87 test('maxBuffer truncates stdio[*], sync', testMaxBufferLimit, execaSync, 3, false);88 test('maxBuffer truncates all, sync', testMaxBufferLimit, execaSync, 1, true);89 90 const testMaxBufferEncoding = async (t, execaMethod, fdNumber) => {85- const result = await runMaxBuffer(t, execaMethod, fdNumber, {encoding: 'buffer'});86- const stream = result.stdio[fdNumber];91+ const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {encoding: 'buffer'});92+ assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, unit: 'bytes'});93+ const stream = stdio[fdNumber];94 t.true(stream instanceof Uint8Array);95 t.is(Buffer.from(stream).toString(), getExpectedOutput());96 };97 5 unmodified lines103 test('maxBuffer works with encoding buffer and stdio[*], sync', testMaxBufferEncoding, execaSync, 3);104 105 const testMaxBufferHex = async (t, fdNumber) => {106 const length = maxBuffer / 2;100- const {stdio} = await runMaxBuffer(t, execa, fdNumber, {length, encoding: 'hex'});107+ const {shortMessage, stdio} = await runMaxBuffer(t, execa, fdNumber, {length, encoding: 'hex'});108+ assertErrorMessage(t, shortMessage, {fdNumber});109 t.is(stdio[fdNumber], Buffer.from(getExpectedOutput(length)).toString('hex'));110 };111 112 test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);1 unmodified line114 test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);115 116 const testMaxBufferHexSync = async (t, fdNumber) => {117 const length = maxBuffer / 2;110- const {stdio} = await getMaxBufferSubprocess(execaSync, fdNumber, {length, encoding: 'hex'});118+ const {isMaxBuffer, stdio} = await getMaxBufferSubprocess(execaSync, fdNumber, {length, encoding: 'hex'});119+ t.false(isMaxBuffer);120 t.is(stdio[fdNumber], Buffer.from(getExpectedOutput(length + 1)).toString('hex'));121 };122 123 test('maxBuffer ignores other encodings and stdout, sync', testMaxBufferHexSync, 1);1 unmodified line125 test('maxBuffer ignores other encodings and stdio[*], sync', testMaxBufferHexSync, 3);126 127 const testNoMaxBuffer = async (t, fdNumber) => {128 const subprocess = getMaxBufferSubprocess(execa, fdNumber, {buffer: false});120- const [{stdio}, output] = await Promise.all([129+ const [{isMaxBuffer, stdio}, output] = await Promise.all([130 subprocess,131 getStream(subprocess.stdio[fdNumber]),132 ]);133+ t.false(isMaxBuffer);134 t.is(stdio[fdNumber], undefined);135 t.is(output, getExpectedOutput(maxBuffer + 1));136 };137 1 unmodified line139 test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2);140 test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3);141 142 const testNoMaxBufferSync = (t, fdNumber) => {133- const {stdio} = getMaxBufferSubprocess(execaSync, fdNumber, {buffer: false});143+ const {isMaxBuffer, stdio} = getMaxBufferSubprocess(execaSync, fdNumber, {buffer: false});144+ t.false(isMaxBuffer);145 t.is(stdio[fdNumber], undefined);146 };147 148 // @todo: add a test for fd3 once the following Node.js bug is fixed.2 unmodified lines151 test('do not buffer stderr when `buffer` set to `false`, sync', testNoMaxBufferSync, 2);152 153 const testMaxBufferAbort = async (t, fdNumber) => {154 const subprocess = getMaxBufferSubprocess(execa, fdNumber);144- await Promise.all([145- t.throwsAsync(subprocess, {message: maxBufferMessage}),155+ const [{isMaxBuffer, shortMessage}] = await Promise.all([156+ t.throwsAsync(subprocess, maxBufferMessage),157 t.throwsAsync(getStream(subprocess.stdio[fdNumber]), {code: 'ERR_STREAM_PREMATURE_CLOSE'}),158 ]);159+ t.true(isMaxBuffer);160+ assertErrorMessage(t, shortMessage, {execaMethod: execa, fdNumber});161 };162 163 test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);164 test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);165 test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);166+167+const testEarlyError = async (t, getSubprocess) => {168+ const {failed, isMaxBuffer} = await getSubprocess({reject: false, maxBuffer: 1});169+ t.true(failed);170+ t.false(isMaxBuffer);171+};172+173+test('error.isMaxBuffer is false on early errors', testEarlyError, getEarlyErrorSubprocess);174+test('error.isMaxBuffer is false on early errors, sync', testEarlyError, getEarlyErrorSubprocessSync);modified:index.d.ts+9 added
586 unmodified lines587 588 /**589 Largest amount of data allowed on `stdout`, `stderr` and `stdio`.590 591+ When this threshold is hit, the subprocess fails and `error.isMaxBuffer` becomes `true`.592+593 This is measured:594 - By default: in [characters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length).595 - If the `encoding` option is `'buffer'`: in bytes.596 - If the `lines` option is `true`: in lines.241 unmodified lines838 */839 isCanceled: boolean;840 841 /**842+ Whether the subprocess failed because its output was larger than the `maxBuffer` option.843+ */844+ isMaxBuffer: boolean;845+846+ /**847 The output of the subprocess with `stdout` and `stderr` interleaved.848 849 This is `undefined` if either:850 - the `all` option is `false` (default value)531 unmodified lines1382 failed: true,1383 timedOut: false,1384 isCanceled: false,1385 isTerminated: false,1386+ isMaxBuffer: false,1387 code: 'ENOENT',1388 stdout: '',1389 stderr: '',1390 stdio: [undefined, '', ''],96 unmodified lines1487 failed: true,1488 timedOut: false,1489 isCanceled: false,1490 isTerminated: false,1491+ isMaxBuffer: false,1492 stdio: [],1493 pipedFrom: []1494 }1495 \*\/200 unmodified linesmodified:index.test-d.ts+4 added
500 unmodified lines501 expectType<boolean>(unicornsResult.failed);502 expectType<boolean>(unicornsResult.timedOut);503 expectType<boolean>(unicornsResult.isCanceled);504 expectType<boolean>(unicornsResult.isTerminated);505+ expectType<boolean>(unicornsResult.isMaxBuffer);506 expectType<string | undefined>(unicornsResult.signal);507 expectType<string | undefined>(unicornsResult.signalDescription);508 expectType<string>(unicornsResult.cwd);509 expectType<number>(unicornsResult.durationMs);438 unmodified lines948 expectType<boolean>(error.failed);949 expectType<boolean>(error.timedOut);950 expectType<boolean>(error.isCanceled);951 expectType<boolean>(error.isTerminated);952+ expectType<boolean>(error.isMaxBuffer);953 expectType<string | undefined>(error.signal);954 expectType<string | undefined>(error.signalDescription);955 expectType<string>(error.cwd);956 expectType<number>(error.durationMs);147 unmodified lines1104 expectType<boolean>(unicornsResult.failed);1105 expectType<boolean>(unicornsResult.timedOut);1106 expectType<boolean>(unicornsResult.isCanceled);1107 expectType<boolean>(unicornsResult.isTerminated);1108+ expectType<boolean>(unicornsResult.isMaxBuffer);1109 expectType<string | undefined>(unicornsResult.signal);1110 expectType<string | undefined>(unicornsResult.signalDescription);1111 expectType<string>(unicornsResult.cwd);1112 expectType<number>(unicornsResult.durationMs);73 unmodified lines1186 expectType<boolean>(error.failed);1187 expectType<boolean>(error.timedOut);1188 expectType<boolean>(error.isCanceled);1189 expectType<boolean>(error.isTerminated);1190+ expectType<boolean>(error.isMaxBuffer);1191 expectType<string | undefined>(error.signal);1192 expectType<string | undefined>(error.signalDescription);1193 expectType<string>(error.cwd);1194 expectType<number>(error.durationMs);2584 unmodified linesmodified:readme.md+9 added
252 unmodified lines253 failed: true,254 timedOut: false,255 isCanceled: false,256 isTerminated: false,257+ isMaxBuffer: false,258 code: 'ENOENT',259 stdout: '',260 stderr: '',261 stdio: [undefined, '', ''],397 unmodified lines659 Whether the subprocess was terminated by a signal (like `SIGTERM`) sent by either:660 - The current process.661 - Another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).662 663+#### isMaxBuffer664+665+Type: `boolean`666+667+Whether the subprocess failed because its output was larger than the [`maxBuffer`](#maxbuffer) option.668+669 #### exitCode670 671 Type: `number | undefined`672 328 unmodified lines1001 Default: `100_000_000`1002 1003 Largest amount of data allowed on [`stdout`](#stdout), [`stderr`](#stderr) and [`stdio`](#stdio).1004 1005+When this threshold is hit, the subprocess fails and [`error.isMaxBuffer`](#ismaxbuffer) becomes `true`.1006+1007 This is measured:1008 - By default: in [characters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length).1009 - If the [`encoding` option](#encoding) is `'buffer'`: in bytes.1010 - If the [`lines` option](#lines) is `true`: in lines.233 unmodified lines