input-sync.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import {runGeneratorsSync} from '../transform/generator.js';
  2. import {joinToUint8Array, isUint8Array} from '../utils/uint-array.js';
  3. import {TYPE_TO_MESSAGE} from '../stdio/type.js';
  4. // Apply `stdin`/`input`/`inputFile` options, before spawning, in sync mode, by converting it to the `input` option
  5. export const addInputOptionsSync = (fileDescriptors, options) => {
  6. for (const fdNumber of getInputFdNumbers(fileDescriptors)) {
  7. addInputOptionSync(fileDescriptors, fdNumber, options);
  8. }
  9. };
  10. const getInputFdNumbers = fileDescriptors => new Set(Object.entries(fileDescriptors)
  11. .filter(([, {direction}]) => direction === 'input')
  12. .map(([fdNumber]) => Number(fdNumber)));
  13. const addInputOptionSync = (fileDescriptors, fdNumber, options) => {
  14. const {stdioItems} = fileDescriptors[fdNumber];
  15. const allStdioItems = stdioItems.filter(({contents}) => contents !== undefined);
  16. if (allStdioItems.length === 0) {
  17. return;
  18. }
  19. if (fdNumber !== 0) {
  20. const [{type, optionName}] = allStdioItems;
  21. throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`);
  22. }
  23. const allContents = allStdioItems.map(({contents}) => contents);
  24. const transformedContents = allContents.map(contents => applySingleInputGeneratorsSync(contents, stdioItems));
  25. options.input = joinToUint8Array(transformedContents);
  26. };
  27. const applySingleInputGeneratorsSync = (contents, stdioItems) => {
  28. const newContents = runGeneratorsSync(contents, stdioItems, 'utf8', true);
  29. validateSerializable(newContents);
  30. return joinToUint8Array(newContents);
  31. };
  32. const validateSerializable = newContents => {
  33. const invalidItem = newContents.find(item => typeof item !== 'string' && !isUint8Array(item));
  34. if (invalidItem !== undefined) {
  35. 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}.`);
  36. }
  37. };