Skip to content
Myr

Fix `stdin` iterables and input transforms edge cases

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 5f80cde · Browse files · 11 files+271 added−28 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+271 added−28 removed

  • tests:+190 added−9 removed
  • other:+81 added−19 removed

11 files+271 added−28 removed

modified:lib/io/input-sync.js+15 added-4 removed
modified:lib/resolve/wait-stream.js+15 added-2 removed
modified:lib/stdio/handle-async.js+38 added-9 removed
1 unmodified line
2import {Buffer} from 'node:buffer';3import {Readable, Writable, Duplex} from 'node:stream';4import {generatorToStream} from '../transform/generator.js';5import {getInputEncoding} from '../arguments/encoding-option.js';6import {isSerializableInput, throwOnSerializableInput} from '../io/input-sync.js';7import {handleStdio} from './handle.js';8import {TYPE_TO_MESSAGE} from './type.js';910// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode
9 unmodified lines
20 fileNumber: forbiddenIfAsync,21 generator: generatorToStream,22 asyncGenerator: generatorToStream,23 nodeStream: ({value}) => ({stream: value}),23 webTransform({value: {transform, writableObjectMode, readableObjectMode}}) {24 const objectMode = writableObjectMode || readableObjectMode;25 const stream = Duplex.fromWeb(transform, {objectMode});26 return {stream};27 },24 // `Duplex.fromWeb()` uses the same `objectMode` for both sides25 webTransform: ({value: {transform, writableObjectMode, readableObjectMode}}) => ({26 stream: Duplex.from({27 writable: Writable.fromWeb(transform.writable, {objectMode: writableObjectMode}),28 readable: Readable.fromWeb(transform.readable, {objectMode: readableObjectMode}),29 }),30 }),31 duplex: ({value: {transform}}) => ({stream: transform}),32 native() {},33};3435// Without transforms in object mode, iterable values are written to the subprocess, which only accepts strings and Uint8Arrays.36// `Readable.from()` emits the values of synchronous iterables on a later tick, where `subprocess.stdin.write()` throwing would crash the current process. Throwing while iterating errors the stream instead.37// Synchronous iterables must stay synchronous, otherwise their order would change when they are combined with other input sources.38const validateIterable = function * (iterable, optionName) {39 for (const value of iterable) {40 validateIterableValue(value, optionName);41 yield value;42 }43};4445const validateAsyncIterable = async function * (iterable, optionName) {46 for await (const value of iterable) {47 validateIterableValue(value, optionName);48 yield value;49 }50};5152const validateIterableValue = (value, optionName) => {53 if (!isSerializableInput(value)) {54 throwOnSerializableInput(optionName, value);55 }56};5758// Empty input is not passed as a chunk, otherwise binary transforms, which do not split lines, would run on it59const readableFromChunk = chunk => Readable.from(chunk.length === 0 ? [] : [chunk]);6061// Input transforms use UTF-8 with text encodings, since those only apply to the output62const generatorToInputStream = (stdioItem, {encoding}) => generatorToStream(stdioItem, {encoding: getInputEncoding(encoding)});6364const addPropertiesAsync = {
3 unmodified lines
68 asyncGenerator: generatorToInputStream,69 fileUrl: ({value}) => ({stream: createReadStream(value)}),70 filePath: ({value: {file}}) => ({stream: createReadStream(file)}),71 webStream: ({value}) => ({stream: Readable.fromWeb(value)}),43 iterable: ({value}) => ({stream: Readable.from(value)}),44 asyncIterable: ({value}) => ({stream: Readable.from(value)}),45 string: ({value}) => ({stream: Readable.from(value)}),46 uint8Array: ({value}) => ({stream: Readable.from(Buffer.from(value))}),72 iterable: ({value, optionName}, options, objectMode) => ({stream: Readable.from(objectMode ? value : validateIterable(value, optionName))}),73 asyncIterable: ({value, optionName}, options, objectMode) => ({stream: Readable.from(objectMode ? value : validateAsyncIterable(value, optionName))}),74 string: ({value}) => ({stream: readableFromChunk(value)}),75 uint8Array: ({value}) => ({stream: readableFromChunk(Buffer.from(value))}),76 },77 output: {78 ...addProperties,79 fileUrl: ({value}) => ({stream: createWriteStream(value)}),
8 unmodified lines
modified:lib/stdio/handle-sync.js+10 added-2 removed
26 unmodified lines
2728 return forbiddenNativeIfSync(stdioItem);29};3031// For the same reason, an input transform can only be used with `stdin`, which is fed with the `input` option32const forbiddenInputTransformIfSync = ({optionName}) => {33 if (optionName !== 'stdin') {34 throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be an input transform with synchronous methods.`);35 }36};3738const throwInvalidSyncValue = (optionName, value) => {39 throw new TypeError(`The \`${optionName}\` option cannot be ${value} with synchronous methods.`);40};41
12 unmodified lines
5455const addPropertiesSync = {56 input: {57 ...addProperties,58 generator: forbiddenInputTransformIfSync,59 native: forbiddenNativeInputIfSync,52 // Files are read lazily, so that a file which cannot be read is reported like any other early error, instead of being thrown as a raw error60 // Files and iterables are read lazily, so that a file which cannot be read, or an iterable which throws, is reported like any other early error, instead of being thrown as a raw error61 fileUrl: ({value}) => ({contents: () => [bufferToUint8Array(readFileSync(value))]}),62 filePath: ({value: {file}}) => ({contents: () => [bufferToUint8Array(readFileSync(file))]}),63 fileNumber: forbiddenIfSync,56 iterable: ({value}) => ({contents: [...value]}),64 iterable: ({value}) => ({contents: () => [...value]}),65 string: ({value}) => ({contents: [value]}),66 // `contents` is already set when reading from a file descriptor67 uint8Array: ({value, contents = [value]}) => ({contents}),68 },
10 unmodified lines
modified:lib/stdio/handle.js+3 added-2 removed
209 unmodified lines
210 finalFileDescriptor.stdioItems.push(addStreamProperties({211 stdioItem,212 addProperties,213 direction,214 objectMode,215 options,216 fileDescriptors,217 isSync,218 }));219 }220};221221const addStreamProperties = ({stdioItem, addProperties, direction, options, fileDescriptors, isSync}) => {222const addStreamProperties = ({stdioItem, addProperties, direction, objectMode, options, fileDescriptors, isSync}) => {223 const duplicateStream = getDuplicateStream({224 stdioItem,225 direction,226 fileDescriptors,
5 unmodified lines
232 }233234 return {235 ...stdioItem,235 ...addProperties[direction][stdioItem.type](stdioItem, options),236 ...addProperties[direction][stdioItem.type](stdioItem, options, objectMode),237 };238};239240// The stream error handling is performed by the piping logic above, which cannot be performed before subprocess spawning.
27 unmodified lines
added:test/fixtures/nested-input-transform-chunks.js+17 added
modified:test/resolve/wait-abort.js+25 added-1 removed
2 unmodified lines
3import test from 'node:test';4import {assertRejects, assertLike} from '../helpers/assert.js';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {prematureClose} from '../helpers/stdio.js';7import {prematureClose, getStdio} from '../helpers/stdio.js';8import {noopGenerator, noopAsyncGenerator} from '../helpers/generator.js';9import {noopDuplex as noopDuplexTransform} from '../helpers/duplex.js';10import {foobarString} from '../helpers/input.js';11import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';12import {13 endOptionStream,14 destroyOptionStream,
88 unmodified lines
103test('Throws abort error when stderr option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 2, true));104test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 2, true));105test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 3, true));106test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 3, true));107108// Like with `stdin: 'pipe'`, the subprocess does not need to read its input, nor `subprocess.stdin` to be ended109const testUnusedInputTransform = async (fdNumber, transform) => {110 const {exitCode} = await execa('empty.js', getStdio(fdNumber, {value: transform, input: true}));111 assert.equal(exitCode, 0);112};113114test('Passes when the subprocess does not read stdin, with a transform', () => testUnusedInputTransform(0, noopGenerator(false)));115test('Passes when the subprocess does not read stdin, with an async transform', () => testUnusedInputTransform(0, noopAsyncGenerator(false)));116test('Passes when the subprocess does not read stdin, with a Duplex', () => testUnusedInputTransform(0, noopDuplexTransform(false)));117test('Passes when the subprocess does not read stdin, with a TransformStream', () => testUnusedInputTransform(0, {transform: new TransformStream()}));118test('Passes when the subprocess does not read stdio[*], with a transform', () => testUnusedInputTransform(3, noopGenerator(false)));119test('Passes when the subprocess does not read stdin, with stdin: "pipe"', () => testUnusedInputTransform(0, 'pipe'));120test('Passes when the subprocess does not read stdio[*], with stdio[*]: "pipe"', () => testUnusedInputTransform(3, 'pipe'));121122test('Passes when the subprocess does not read the stdin transform it is written to', async () => {123 const subprocess = execa('empty.js', {stdin: noopGenerator(false)});124 subprocess.stdin.write(foobarString);125 const {exitCode} = await subprocess;126 assert.equal(exitCode, 0);127});
modified:test/stdio/direction.js+35 added
103 unmodified lines
104 execaSync('empty.js', {...getStdio(3, {value: 'pipe', input: true}), buffer: false});105 }, {message: /can be an input pipe with synchronous methods/});106});107108// Nothing could write to that file descriptor after spawning, so the subprocess would hang reading it109const testInputTransformSync = stdioOption => {110 assertThrows(() => {111 execaSync('stdin-fd.js', ['3'], getStdio(3, stdioOption));112 }, {message: /Only the `stdin` option, not `stdio\[3\]`, can be an input transform with synchronous methods/});113};114115test('stdio[*] { value: generator, input: true } cannot be used in sync mode', () => testInputTransformSync({116 * value(line) {117 yield line;118 },119 input: true,120}));121test('stdio[*] { value: {transform}, input: true } cannot be used in sync mode', () => testInputTransformSync({122 value: {123 * transform(line) {124 yield line;125 },126 },127 input: true,128}));129130test('stdin { value: generator, input: true } can be used in sync mode', () => {131 const {stdout} = execaSync('stdin.js', {132 stdin: {133 * value(line) {134 yield line.toUpperCase();135 },136 input: true,137 },138 input: foobarString,139 });140 assert.equal(stdout, foobarString.toUpperCase());141});142143const testDirectionOutputPipe = async (stdioOption, execaMethod) => {144 const {stdio} = await execaMethod('noop-fd.js', ['3', foobarString], getStdio(3, stdioOption));145 assert.equal(stdio[3], foobarString);146};
96 unmodified lines
modified:test/stdio/iterable.js+33 added-7 removed
1 unmodified line
2import {once} from 'node:events';3import {setImmediate} from 'node:timers/promises';4import test from 'node:test';5import {assertThrows, assertRejects} from '../helpers/assert.js';6import {execa, execaSync} from '../../index.js';6import {execa, execaSync, ExecaSyncError} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {getStdio} from '../helpers/stdio.js';9import {10 foobarString,
86 unmodified lines
97test('stdio[*] option can be an async iterable of objects', () => testObjectIterable(foobarAsyncObjectGenerator(), 3, execa));98test('stdin option can be an array of objects - sync', () => testObjectIterable([foobarObject], 0, execaSync));99test('stdin option can be an iterable of objects - sync', () => testObjectIterable(foobarObjectGenerator(), 0, execaSync));100101// Writing those objects to `subprocess.stdin` fails, which must not crash the current process102const testIterableNoGenerators = async (stdioOption, fdNumber) => {103 await assertRejects(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, stdioOption)), {message: /must be used to serialize/});104};105106test('stdin option cannot be an array of objects without generators', () => testIterableNoGenerators([[foobarObject]], 0));107test('stdin option cannot be an array of numbers without generators', () => testIterableNoGenerators([[0]], 0));108test('stdio[*] option cannot be an array of objects without generators', () => testIterableNoGenerators([[foobarObject]], 3));109test('stdin option cannot be an iterable of objects without generators', () => testIterableNoGenerators(foobarObjectGenerator(), 0));110test('stdin option cannot be an async iterable of objects without generators', () => testIterableNoGenerators(foobarAsyncObjectGenerator(), 0));111test('stdin option cannot be an array of strings and objects without generators', () => testIterableNoGenerators([[foobarString, foobarObject]], 0));112113const testIterableNoGeneratorsSync = (stdioOption, fdNumber) => {114 assertThrows(() => {115 execaSync('empty.js', getStdio(fdNumber, stdioOption));116 }, {message: /must be used to serialize/});
44 unmodified lines
161162test('stdin option handles errors in iterables', () => testIterableError(0));163test('stdio[*] option handles errors in iterables', () => testIterableError(3));164153const testIterableErrorSync = fdNumber => {165// Like with asynchronous methods, the iterable's error is reported as the subprocess error166test('stdin option handles errors in iterables - sync', () => {167 const cause = new Error(foobarString);168 const error = assertThrows(() => {156 execaSync('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, throwingGenerator(cause)().transform()));169 execaSync('stdin-fd.js', ['0'], getStdio(0, throwingGenerator(cause)().transform()));170 });171 assert.ok(error instanceof ExecaSyncError);172 assert.equal(error.cause, cause);158 assert.equal(error, cause);159};173 assert.equal(error.stdout, '');174});175161test('stdin option handles errors in iterables - sync', () => testIterableErrorSync(0));162test('stdio[*] option handles errors in iterables - sync', () => testIterableErrorSync(3));176test('stdin option handles errors in iterables, reject: false - sync', () => {177 const cause = new Error(foobarString);178 const {failed, cause: errorCause} = execaSync('stdin-fd.js', ['0'], {...getStdio(0, throwingGenerator(cause)().transform()), reject: false});179 assert.equal(failed, true);180 assert.equal(errorCause, cause);181});182183test('stdio[*] option cannot be an iterable - sync', () => {184 const error = assertThrows(() => {185 execaSync('stdin-fd.js', ['3'], getStdio(3, [[foobarString]]));186 }, {message: /Only the `stdin` option, not `stdio\[3\]`, can be an iterable with synchronous methods/});187 assert.ok(error instanceof ExecaSyncError);188});189190const testNoIterableOutput = (stdioOption, fdNumber, execaMethod) => {191 assertThrows(() => {192 execaMethod('empty.js', getStdio(fdNumber, stdioOption));193 }, {message: /cannot be an iterable/});
45 unmodified lines
modified:test/stdio/web-transform.js+35 added-1 removed
1import assert from 'node:assert/strict';2import {promisify} from 'node:util';3import {gunzip} from 'node:zlib';4import test from 'node:test';5import {assertRejects} from '../helpers/assert.js';6import {execa} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {foobarString, foobarUtf16Uint8Array, foobarUint8Array} from '../helpers/input.js';8import {9 foobarString,10 foobarUtf16Uint8Array,11 foobarUint8Array,12 foobarObject,13 foobarObjectString,14} from '../helpers/input.js';15import {outputObjectGenerator} from '../helpers/generator.js';16import {serializeWebTransform, outputObjectWebTransform, noopWebTransform} from '../helpers/web-transform.js';1718setFixtureDirectory();1920test('Can use CompressionStream()', async () => {
9 unmodified lines
30 encoding: 'buffer',31 });32 assert.deepEqual(stdout, foobarUint8Array);33});3435// A `TransformStream` has no `objectMode` of its own, so the `objectMode` option applies to its output, while its input uses the previous transform's36const testWebTransformObjectModeFalse = async (getTransforms, expectedOutput) => {37 const {stdout} = await execa('noop.js', [foobarString], {stdout: getTransforms()});38 assert.deepEqual(stdout, expectedOutput);39};4041test('TransformStream with "objectMode: false" can follow an objectMode transform', () => testWebTransformObjectModeFalse(() => [outputObjectGenerator(), serializeWebTransform(false)], foobarObjectString));42test('TransformStream with "objectMode: false" can follow an objectMode TransformStream', () => testWebTransformObjectModeFalse(() => [outputObjectWebTransform(), serializeWebTransform(false)], foobarObjectString));43test('TransformStream with "objectMode: false" splits lines after an objectMode transform', () => testWebTransformObjectModeFalse(() => [outputObjectGenerator(), {44 transform: new TransformStream({45 transform(object, controller) {46 controller.enqueue(`${JSON.stringify(object)}\n${JSON.stringify(object)}\n`);47 },48 }),49 objectMode: false,50}], `${foobarObjectString}\n${foobarObjectString}`));51test('TransformStream with "objectMode: true" can follow a TransformStream with "objectMode: false"', () => testWebTransformObjectModeFalse(() => [noopWebTransform(false), outputObjectWebTransform()], [foobarObject]));5253test('Destroying subprocess.stdin fails the subprocess when it is a TransformStream', async () => {54 const subprocess = execa('stdin.js', {stdin: new TransformStream()});55 subprocess.stdin.destroy();56 const {cause} = await assertRejects(subprocess);57 assert.equal(cause.code, 'ABORT_ERR');58});
modified:test/transform/generator-input.js+45 added
1import assert from 'node:assert/strict';2import {Buffer} from 'node:buffer';3import {writeFile, rm} from 'node:fs/promises';4import test from 'node:test';5import tempfile from 'tempfile';6import {execa, execaSync} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {getStdio} from '../helpers/stdio.js';9import {
148 unmodified lines
158test('Can use webTransforms with subprocess.stdio[*] as input', () => testGeneratorStdioInputPipe(false, false, 'webTransform'));159test('Can use webTransforms with subprocess.stdio[*] as input, objectMode', () => testGeneratorStdioInputPipe(true, false, 'webTransform'));160test('Can use webTransforms with subprocess.stdio[*] as input, noop transform', () => testGeneratorStdioInputPipe(false, true, 'webTransform'));161test('Can use webTransforms with subprocess.stdio[*] as input, objectMode, noop transform', () => testGeneratorStdioInputPipe(true, true, 'webTransform'));162163// Like with the output, an empty input is not passed as a chunk to binary transforms, which do not split lines164const testEmptyInput = async (options, execaMethod) => {165 const chunks = [];166 const {stdout} = await execaMethod('stdin.js', {167 ...options,168 stdin: {169 * transform(chunk) {170 chunks.push(chunk);171 yield chunk;172 },173 binary: true,174 },175 });176 assert.equal(stdout, '');177 assert.deepEqual(chunks, []);178};179180test('Binary input generators are not called with an empty "input" string', () => testEmptyInput({input: ''}, execa));181test('Binary input generators are not called with an empty "input" Uint8Array', () => testEmptyInput({input: new Uint8Array()}, execa));182test('Binary input generators are not called with an empty "input" string, sync', () => testEmptyInput({input: ''}, execaSync));183test('Binary input generators are not called with an empty "input" Uint8Array, sync', () => testEmptyInput({input: new Uint8Array()}, execaSync));184185const testEmptyInputFile = async execaMethod => {186 const filePath = tempfile();187 await writeFile(filePath, '');188 try {189 await testEmptyInput({inputFile: filePath}, execaMethod);190 } finally {191 await rm(filePath);192 }193};194195test('Binary input generators are not called with an empty "inputFile"', () => testEmptyInputFile(execa));196test('Binary input generators are not called with an empty "inputFile", sync', () => testEmptyInputFile(execaSync));197198const testEmptyInheritedInput = async isSync => {199 const {stdout} = await execa('nested-input-transform-chunks.js', [isSync ? 'sync' : 'async'], {input: ''});200 assert.equal(stdout, '0');201};202203test('Binary input generators are not called with an empty inherited stdin', () => testEmptyInheritedInput(false));204test('Binary input generators are not called with an empty inherited stdin, sync', () => testEmptyInheritedInput(true));