Skip to content
Myr

input-sync.js

This file

Path

lib/stdio/input-sync.js

47 lines · 2.0 KiB · JavaScript

Last changed by

Add support for transforms with `execaSync()` (#945)ehmickybefore adoptionc5f9f09

History of this file

Take it

Add support for transforms with `execaSync()` (#945)ehmickybefore adoptionc5f9f09

lines 1–47why, one step back
1import {joinToUint8Array, isUint8Array} from './uint-array.js';
2import {TYPE_TO_MESSAGE} from './type.js';3import {getGenerators, runGeneratorsSync} from './generator.js';45// Apply `stdin`/`input`/`inputFile` options, before spawning, in sync mode, by converting it to the `input` option6export const addInputOptionsSync = (fileDescriptors, options) => {7 for (const fdNumber of getInputFdNumbers(fileDescriptors)) {8 addInputOptionSync(fileDescriptors, fdNumber, options);9 }10};1112const getInputFdNumbers = fileDescriptors => new Set(fileDescriptors13 .filter(({direction}) => direction === 'input')14 .map(({fdNumber}) => fdNumber));1516const addInputOptionSync = (fileDescriptors, fdNumber, options) => {17 const selectedStdioItems = fileDescriptors18 .filter(fileDescriptor => fileDescriptor.fdNumber === fdNumber)19 .flatMap(({stdioItems}) => stdioItems);20 const allStdioItems = selectedStdioItems.filter(({contents}) => contents !== undefined);21 if (allStdioItems.length === 0) {22 return;23 }2425 if (fdNumber !== 0) {26 const [{type, optionName}] = allStdioItems;27 throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`);28 }2930 const allContents = allStdioItems.map(({contents}) => contents);31 const transformedContents = allContents.map(contents => applySingleInputGeneratorsSync(contents, selectedStdioItems));32 options.input = joinToUint8Array(transformedContents);33};3435const applySingleInputGeneratorsSync = (contents, selectedStdioItems) => {36 const generators = getGenerators(selectedStdioItems).reverse();37 const newContents = runGeneratorsSync(contents, generators);38 validateSerializable(newContents);39 return joinToUint8Array(newContents);40};4142const validateSerializable = newContents => {43 const invalidItem = newContents.find(item => typeof item !== 'string' && !isUint8Array(item));44 if (invalidItem !== undefined) {45 throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${invalidItem}.`);46 }47};