parameters.js 1.3 KB

12345678910111213141516171819202122232425262728293031
  1. import isPlainObject from 'is-plain-obj';
  2. import {safeNormalizeFileUrl} from '../arguments/file-url.js';
  3. // The command `arguments` and `options` are both optional.
  4. // This also does basic validation on them and on the command file.
  5. export const normalizeParameters = (rawFile, rawArguments = [], rawOptions = {}) => {
  6. const filePath = safeNormalizeFileUrl(rawFile, 'First argument');
  7. const [commandArguments, options] = isPlainObject(rawArguments)
  8. ? [[], rawArguments]
  9. : [rawArguments, rawOptions];
  10. if (!Array.isArray(commandArguments)) {
  11. throw new TypeError(`Second argument must be either an array of arguments or an options object: ${commandArguments}`);
  12. }
  13. if (commandArguments.some(commandArgument => typeof commandArgument === 'object' && commandArgument !== null)) {
  14. throw new TypeError(`Second argument must be an array of strings: ${commandArguments}`);
  15. }
  16. const normalizedArguments = commandArguments.map(String);
  17. const nullByteArgument = normalizedArguments.find(normalizedArgument => normalizedArgument.includes('\0'));
  18. if (nullByteArgument !== undefined) {
  19. throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${nullByteArgument}`);
  20. }
  21. if (!isPlainObject(options)) {
  22. throw new TypeError(`Last argument must be an options object: ${options}`);
  23. }
  24. return [filePath, normalizedArguments, options];
  25. };