validate.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import {Buffer} from 'node:buffer';
  2. import {isUint8Array} from '../utils/uint-array.js';
  3. // Validate the type of chunk argument passed to transform generators
  4. export const getValidateTransformInput = (writableObjectMode, optionName) => writableObjectMode
  5. ? undefined
  6. : validateStringTransformInput.bind(undefined, optionName);
  7. const validateStringTransformInput = function * (optionName, chunk) {
  8. if (typeof chunk !== 'string' && !isUint8Array(chunk) && !Buffer.isBuffer(chunk)) {
  9. throw new TypeError(`The \`${optionName}\` option's transform must use "objectMode: true" to receive as input: ${typeof chunk}.`);
  10. }
  11. yield chunk;
  12. };
  13. // Validate the type of the value returned by transform generators
  14. export const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode
  15. ? validateObjectTransformReturn.bind(undefined, optionName)
  16. : validateStringTransformReturn.bind(undefined, optionName);
  17. const validateObjectTransformReturn = function * (optionName, chunk) {
  18. validateEmptyReturn(optionName, chunk);
  19. yield chunk;
  20. };
  21. const validateStringTransformReturn = function * (optionName, chunk) {
  22. validateEmptyReturn(optionName, chunk);
  23. if (typeof chunk !== 'string' && !isUint8Array(chunk)) {
  24. throw new TypeError(`The \`${optionName}\` option's function must yield a string or an Uint8Array, not ${typeof chunk}.`);
  25. }
  26. yield chunk;
  27. };
  28. const validateEmptyReturn = (optionName, chunk) => {
  29. if (chunk === null || chunk === undefined) {
  30. throw new TypeError(`The \`${optionName}\` option's function must not call \`yield ${chunk}\`.
  31. Instead, \`yield\` should either be called with a value, or not be called at all. For example:
  32. if (condition) { yield value; }`);
  33. }
  34. };