Allow `stdout`/`stderr` option to be a `WritableStream` (#619)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent fcf648e · Browse files · 6 files·+147 added−45 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+147 added−45 removed
- tests:+38 added−2 removed
- other:+109 added−43 removed
Provenance
- Commit
4110dfc- Tree
c99fee1- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
fcf648e
6 files changed+147 added−45 removed
modified:lib/stdio.js+87 added-33 removed
1 import {createReadStream, readFileSync} from 'node:fs';2 import {isAbsolute} from 'node:path';3-import {Readable} from 'node:stream';3+import {Readable, Writable} from 'node:stream';4 import {isStream as isNodeStream} from 'is-stream';5 6 const aliases = ['stdin', 'stdout', 'stderr'];7 4 unmodified lines12 && !isNodeStream(stdinOption)13 && !isReadableStream(stdinOption)14 && (typeof stdinOption[Symbol.asyncIterator] === 'function' || typeof stdinOption[Symbol.iterator] === 'function');15 16-const getIterableStdin = stdioArray => isIterableStdin(stdioArray[0])17- ? stdioArray[0]16+const getIterableStdin = stdioOption => isIterableStdin(stdioOption)17+ ? stdioOption18 : undefined;19 20 const isUrlInstance = stdioOption => Object.prototype.toString.call(stdioOption) === '[object URL]';21 const hasFileProtocol = url => url.protocol === 'file:';4 unmodified lines26 const isFilePath = stdioOption => typeof stdioOption === 'string' && stringIsFilePath(stdioOption);27 const isUnknownStdioString = stdioOption => typeof stdioOption === 'string' && !stringIsFilePath(stdioOption) && !KNOWN_STDIO.has(stdioOption);28 29 const isReadableStream = stdioOption => Object.prototype.toString.call(stdioOption) === '[object ReadableStream]';30+const isWritableStream = stdioOption => Object.prototype.toString.call(stdioOption) === '[object WritableStream]';31 32 // Check whether the `stdin` option results in `spawned.stdin` being `undefined`.33 // We use a deny list instead of an allow list to be forward compatible with new options.33-const cannotPipeStdio = stdioOption => NO_PIPE_STDIO.has(stdioOption)34- || isNodeStream(stdioOption)35- || isReadableStream(stdioOption)36- || typeof stdioOption === 'number'37- || isIterableStdin(stdioOption)38- || isFileUrl(stdioOption)39- || isFilePath(stdioOption);34+const cannotPipeStdin = stdinOption => NO_PIPE_STDIO.has(stdinOption)35+ || isNodeStream(stdinOption)36+ || isReadableStream(stdinOption)37+ || typeof stdinOption === 'number'38+ || isIterableStdin(stdinOption)39+ || isFileUrl(stdinOption)40+ || isFilePath(stdinOption);41 42 const NO_PIPE_STDIO = new Set(['ipc', 'ignore', 'inherit']);43 const KNOWN_STDIO = new Set([...NO_PIPE_STDIO, 'overlapped', 'pipe']);44 12 unmodified lines57 if (input !== undefined && inputFile !== undefined) {58 throw new TypeError('The `input` and `inputFile` options cannot be both set.');59 }60 60- const noPipeStdin = cannotPipeStdio(stdioArray[0]);61+ const noPipeStdin = cannotPipeStdin(stdioArray[0]);62 if (noPipeStdin && input !== undefined) {63 throw new TypeError('The `input` and `stdin` options cannot be both set.');64 }65 3 unmodified lines69 70 validateFileSdio(stdioArray[0]);71 };72 72-const getStdioStreams = (stdioArray, {input, inputFile}) => {73- const iterableStdin = getIterableStdin(stdioArray);73+const getStdioStreams = (stdioArray, {input, inputFile}) => ({74+ ...getStdinStream(stdioArray[0], input, inputFile),75+ ...getStdoutStream(stdioArray[1]),76+ ...getStderrStream(stdioArray[2]),77+});78 79+const getStdinStream = (stdinOption, input, inputFile) => {80+ const iterableStdin = getIterableStdin(stdinOption);81+82 if (iterableStdin !== undefined) {83 return {stdinStream: Readable.from(iterableStdin)};84 }85 79- if (isReadableStream(stdioArray[0])) {80- return {stdinStream: Readable.fromWeb(stdioArray[0])};86+ if (isReadableStream(stdinOption)) {87+ return {stdinStream: Readable.fromWeb(stdinOption)};88 }89 83- if (isFileUrl(stdioArray[0]) || isFilePath(stdioArray[0])) {84- return {stdinStream: createReadStream(stdioArray[0])};90+ if (isFileUrl(stdinOption) || isFilePath(stdinOption)) {91+ return {stdinStream: createReadStream(stdinOption)};92 }93 94 if (inputFile !== undefined) {95 return {stdinStream: createReadStream(inputFile)};9 unmodified lines105 106 return {stdinInput: input};107 };108 102-// When the `stdin: iterable`, `input` or `inputFile` option is used, we pipe to `spawned.stdin`.103-// Therefore the `stdin` option must be either `pipe` or `overlapped`. Other values do not set `spawned.stdin`.104-const willPipeStdin = (index, {stdinStream, stdinInput}) =>105- index === 0 && (stdinStream !== undefined || stdinInput !== undefined);109+const getStdoutStream = stdoutOption => {110+ const stdoutStream = getOutputStream(stdoutOption);111+ return stdoutStream === undefined ? {} : {stdoutStream};112+};113 114+const getStderrStream = stderrOption => {115+ const stderrStream = getOutputStream(stderrOption);116+ return stderrStream === undefined ? {} : {stderrStream};117+};118+119+const getOutputStream = stdioOption => {120+ if (isWritableStream(stdioOption)) {121+ return Writable.fromWeb(stdioOption);122+ }123+};124+125+// When the `stdin: Iterable | ReadableStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `spawned.std*`.126+// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `spawned.std*`.127+const willPipeStreams = (index, {stdinStream, stdinInput, stdoutStream, stderrStream}) => {128+ if (index === 0) {129+ return stdinStream !== undefined || stdinInput !== undefined;130+ }131+132+ if (index === 1) {133+ return stdoutStream !== undefined;134+ }135+136+ if (index === 2) {137+ return stderrStream !== undefined;138+ }139+140+ return false;141+};142+143 const transformStdioItem = (stdioItem, index, stdioStreams) =>108- willPipeStdin(index, stdioStreams) && stdioItem !== 'overlapped' ? 'pipe' : stdioItem;144+ willPipeStreams(index, stdioStreams) && stdioItem !== 'overlapped' ? 'pipe' : stdioItem;145 146 const transformStdio = (stdio, stdioStreams) => Array.isArray(stdio)147 ? stdio.map((stdioItem, index) => transformStdioItem(stdioItem, index, stdioStreams))148 : stdio;8 unmodified lines157 return stdioStreams;158 };159 160 // Handle `input`, `inputFile` and `stdin` options, after spawning, in async mode125-export const pipeStdioOption = (spawned, {stdinStream, stdinInput}) => {161+export const pipeStdioOption = (spawned, {stdinStream, stdinInput, stdoutStream, stderrStream}) => {162 if (stdinStream !== undefined) {163 stdinStream.pipe(spawned.stdin);128- return;164 }165 166 if (stdinInput !== undefined) {167 spawned.stdin.end(stdinInput);168 }169+170+ if (stdoutStream !== undefined) {171+ spawned.stdout.pipe(stdoutStream);172+ }173+174+ if (stderrStream !== undefined) {175+ spawned.stderr.pipe(stderrStream);176+ }177 };178 179 const transformStdioItemSync = stdioItem => isFileUrl(stdioItem) || isFilePath(stdioItem) ? 'pipe' : stdioItem;180 181 const transformStdioSync = stdio => Array.isArray(stdio)182 ? stdio.map(stdioItem => transformStdioItemSync(stdioItem))183 : stdio;184 142-const validateInputOptionsSync = (stdioArray, input) => {143- if (getIterableStdin(stdioArray) !== undefined) {185+const validateInputOptionsSync = (stdinOption, input) => {186+ if (getIterableStdin(stdinOption) !== undefined) {187 throw new TypeError('The `stdin` option cannot be an iterable in sync mode');188 }189 147- if (isReadableStream(stdioArray[0])) {190+ if (isReadableStream(stdinOption)) {191 throw new TypeError('The `stdin` option cannot be a stream in sync mode');192 }193 194 if (isNodeStream(input)) {195 throw new TypeError('The `input` option cannot be a stream in sync mode');196 }197 };198 156-const getInputOption = (stdio, {input, inputFile}) => {157- const stdioArray = arrifyStdio(stdio);199+const validateOutputOptionsSync = (stdioOption, optionName) => {200+ if (isWritableStream(stdioOption)) {201+ throw new TypeError(`The \`${optionName}\` option cannot be a stream in sync mode`);202+ }203+};204+205+const validateOptionsSync = (stdioArray, {input, inputFile}) => {206 validateInputOptions(stdioArray, input, inputFile);159- validateInputOptionsSync(stdioArray, input);207+ validateInputOptionsSync(stdioArray[0], input);208+ validateOutputOptionsSync(stdioArray[1], 'stdout');209+ validateOutputOptionsSync(stdioArray[2], 'stderr');210+};211 212+const getInputOption = (stdinOption, {input, inputFile}) => {161- if (isFileUrl(stdioArray[0]) || isFilePath(stdioArray[0])) {162- return readFileSync(stdioArray[0]);213+ if (isFileUrl(stdinOption) || isFilePath(stdinOption)) {214+ return readFileSync(stdinOption);215 }216 217 if (inputFile !== undefined) {218 return readFileSync(inputFile);4 unmodified lines223 224 // Handle `input`, `inputFile` and `stdin` options, before spawning, in sync mode225 export const handleInputOption = options => {226 const stdio = normalizeStdio(options);227+ const stdioArray = arrifyStdio(stdio);228+ validateOptionsSync(stdioArray, options);229 176- const input = getInputOption(stdio, options);230+ const input = getInputOption(stdioArray[0], options);231 if (input !== undefined) {232 options.input = input;233 }234 50 unmodified linesmodified:lib/stream.js+4 added-4 removed
51 unmodified lines5253545556575657585960616263646566666768697070717273749 unmodified lines51 unmodified lines const buffer = await getStreamAsBuffer(stream, {maxBuffer}); return buffer.toString(encoding);};
// Handle any errors thrown by the iterable passed to the `stdin` option, if any.// We do not consume nor wait on that stream though, since it could potentially be infinite (like `process.stdin` in an interactive TTY).// Handle any errors thrown by the iterable passed to the `stdin`/`stdout`/`stderr` option, if any.// We do not consume nor wait on those streams though, since it could potentially be infinite (like `process.stdin` in an interactive TTY).const throwOnStreamsError = streams => streams.filter(Boolean).map(stream => throwOnStreamError(stream));
const throwOnStreamError = async stream => { const [error] = await once(stream, 'error'); throw error;};
// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)export const getSpawnedResult = async (spawned, {encoding, buffer, maxBuffer}, {stdinStream}, processDone) => {export const getSpawnedResult = async (spawned, {encoding, buffer, maxBuffer}, {stdinStream, stdoutStream, stderrStream}, processDone) => { const stdoutPromise = getStreamPromise(spawned.stdout, {encoding, buffer, maxBuffer}); const stderrPromise = getStreamPromise(spawned.stderr, {encoding, buffer, maxBuffer}); const allPromise = getStreamPromise(spawned.all, {encoding, buffer, maxBuffer: maxBuffer * 2}); const processDoneOrStreamsError = Promise.race([processDone, ...throwOnStreamsError([stdinStream])]); const processDoneOrStreamsError = Promise.race([processDone, ...throwOnStreamsError([stdinStream, stdoutStream, stderrStream])]);
try { return await Promise.all([processDoneOrStreamsError, stdoutPromise, stderrPromise, allPromise]); } catch (error) {9 unmodified linesmodified:test/stream.js+38 added-2 removed
184 unmodified lines185 }, {message: /`inputFile` and `stdin` options/});186 });187 188 test('stdin option handles errors in iterables', async t => {189- const {originalMessage} = await t.throwsAsync(() => execa('stdin.js', {stdin: throwingGenerator()}));189+ const {originalMessage} = await t.throwsAsync(execa('stdin.js', {stdin: throwingGenerator()}));190 t.is(originalMessage, 'generator error');191 });192 193+const testWritableStreamError = async (t, streamName) => {194+ const writableStream = new WritableStream({195+ start(controller) {196+ controller.error(new Error('foobar'));197+ },198+ });199+ const {originalMessage} = await t.throwsAsync(execa('noop.js', {[streamName]: writableStream}));200+ t.is(originalMessage, 'foobar');201+};202+203+test('stdout option handles errors in WritableStream', testWritableStreamError, 'stdout');204+test('stderr option handles errors in WritableStream', testWritableStreamError, 'stderr');205+206 test('input option can be a String', async t => {207 const {stdout} = await execa('stdin.js', {input: 'foobar'});208 t.is(stdout, 'foobar');209 });39 unmodified lines249 const {stdout} = await execa('stdin.js', {stdin});250 t.is(stdout, 'howdy');251 });252 253+const testWritableStream = async (t, streamName, fixtureName) => {254+ const result = [];255+ const writableStream = new WritableStream({256+ write(chunk) {257+ result.push(chunk);258+ },259+ });260+ await execa(fixtureName, ['foobar'], {[streamName]: writableStream});261+ t.is(result.join(''), 'foobar\n');262+};263+264+test('stdout can be a WritableStream', testWritableStream, 'stdout', 'noop.js');265+test('stderr can be a WritableStream', testWritableStream, 'stderr', 'noop-err.js');266+267 test('stdin cannot be a ReadableStream when input is used', t => {268 const stdin = Stream.Readable.toWeb(Stream.Readable.from('howdy'));269 t.throws(() => {270 execa('stdin.js', {stdin, input: 'foobar'});109 unmodified lines380 });381 t.is(stdout, undefined);382 });383 357-test('input cannot be a stream in sync mode', t => {384+test('input cannot be a Node.js Readable in sync mode', t => {385 t.throws(() => {386 execaSync('stdin.js', {input: new Stream.PassThrough()});387 }, {message: /The `input` option cannot be a stream in sync mode/});388 });4 unmodified lines393 execaSync('stdin.js', {stdin});394 }, {message: /The `stdin` option cannot be a stream in sync mode/});395 });396 397+const testWritableStreamSync = (t, streamName) => {398+ t.throws(() => {399+ execaSync('noop.js', {[streamName]: new WritableStream()});400+ }, {message: new RegExp(`The \`${streamName}\` option cannot be a stream in sync mode`)});401+};402+403+test('stdout cannot be a WritableStream in sync mode', testWritableStreamSync, 'stdout');404+test('stderr cannot be a WritableStream in sync mode', testWritableStreamSync, 'stderr');405+406 test('stdin can be a file URL - sync', t => {407 const inputFile = tempfile();408 fs.writeFileSync(inputFile, 'howdy');409 const stdin = pathToFileURL(inputFile);181 unmodified linesmodified:index.d.ts+11 added-3 removed
18 unmodified lines19 | URL20 | string21 | ReadableStream;22 23+export type StdoutStderrOption =24+ | StdioOption25+ | WritableStream;26+27 type EncodingOption =28 | 'utf8'29 // eslint-disable-next-line unicorn/text-encoding-identifier-case30 | 'utf-8'66 unmodified lines97 98 /**99 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).100 97- It can also be a file path, a file URL, a web stream ([`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)) an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), providing neither [`execaSync()`](#execasyncfile-arguments-options), the [`input` option](#input) nor the [`inputFile` option](#inputfile) is used. If the file path is relative, it must start with `.`.101+ It can also be a file path, a file URL, a web stream ([`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)), an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), unless either [`execaSync()`](#execasyncfile-arguments-options), the [`input` option](#input) or the [`inputFile` option](#inputfile) is used. If the file path is relative, it must start with `.`.102 103 @default `inherit` with `$`, `pipe` otherwise104 */105 readonly stdin?: StdinOption;106 107 /**108 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).109 110+ It can also be a web stream ([`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream)), unless [`execaSync()`](#execasyncfile-arguments-options) is used.111+112 @default 'pipe'113 */108- readonly stdout?: StdioOption;114+ readonly stdout?: StdoutStderrOption;115 116 /**117 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).118 119+ It can also be a web stream ([`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream)), unless [`execaSync()`](#execasyncfile-arguments-options) is used.120+121 @default 'pipe'122 */115- readonly stderr?: StdioOption;123+ readonly stderr?: StdoutStderrOption;124 125 /**126 Setting this to `false` resolves the promise with the error instead of rejecting it.127 886 unmodified linesmodified:index.test-d.ts+2 added
173 unmodified lines174 execa('unicorns', {stdout: 'ipc'});175 execa('unicorns', {stdout: 'ignore'});176 execa('unicorns', {stdout: 'inherit'});177 execa('unicorns', {stdout: process.stdout});178+execa('unicorns', {stdout: new WritableStream()});179 execa('unicorns', {stdout: 1});180 execa('unicorns', {stdout: undefined});181 execa('unicorns', {stderr: 'pipe'});182 execa('unicorns', {stderr: 'overlapped'});183 execa('unicorns', {stderr: 'ipc'});184 execa('unicorns', {stderr: 'ignore'});185 execa('unicorns', {stderr: 'inherit'});186 execa('unicorns', {stderr: process.stderr});187+execa('unicorns', {stderr: new WritableStream()});188 execa('unicorns', {stderr: 1});189 execa('unicorns', {stderr: undefined});190 execa('unicorns', {all: true});191 execa('unicorns', {reject: false});179 unmodified linesmodified:readme.md+5 added-3 removed
562 unmodified lines563 Default: `inherit` with [`$`](#command), `pipe` otherwise564 565 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).566 567-It can also be a file path, a file URL, a web stream ([`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)) an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), providing neither [`execaSync()`](#execasyncfile-arguments-options), the [`input` option](#input) nor the [`inputFile` option](#inputfile) is used. If the file path is relative, it must start with `.`.567+It can also be a file path, a file URL, a web stream ([`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)), an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), unless either [`execaSync()`](#execasyncfile-arguments-options), the [`input` option](#input) or the [`inputFile` option](#inputfile) is used. If the file path is relative, it must start with `.`.568 569 #### stdout570 571-Type: `string | number | Stream | undefined`\571+Type: `string | number | stream.Writable | WritableStream | undefined`\572 Default: `pipe`573 574 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).575 576+It can also be a web stream ([`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream)), unless [`execaSync()`](#execasyncfile-arguments-options) is used.577+578 #### stderr579 578-Type: `string | number | Stream | undefined`\580+Type: `string | number | stream.Writable | WritableStream | undefined`\581 Default: `pipe`582 583 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).584 231 unmodified lines