Skip to content
Myr

encoding.js

This file

Path

lib/arguments/encoding.js

49 lines · 1.4 KiB · JavaScript

Last changed by

Stricter values for the `encoding` option (#928)ehmickybefore adoption477bbc4

History of this file

Take it

Stricter values for the `encoding` option (#928)ehmickybefore adoption477bbc4

lines 1–49why, one step back
1export const validateEncoding = ({encoding}) => {
2 if (ENCODINGS.has(encoding)) {3 return;4 }56 const correctEncoding = getCorrectEncoding(encoding);7 if (correctEncoding !== undefined) {8 throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`.9Please rename it to ${serializeEncoding(correctEncoding)}.`);10 }1112 const correctEncodings = [...ENCODINGS].map(correctEncoding => serializeEncoding(correctEncoding)).join(', ');13 throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`.14Please rename it to one of: ${correctEncodings}.`);15};1617const TEXT_ENCODINGS = new Set(['utf8', 'utf16le']);18export const BINARY_ENCODINGS = new Set(['buffer', 'hex', 'base64', 'base64url', 'latin1', 'ascii']);19const ENCODINGS = new Set([...TEXT_ENCODINGS, ...BINARY_ENCODINGS]);2021const getCorrectEncoding = encoding => {22 if (encoding === null) {23 return 'buffer';24 }2526 if (typeof encoding !== 'string') {27 return;28 }2930 const lowerEncoding = encoding.toLowerCase();31 if (lowerEncoding in ENCODING_ALIASES) {32 return ENCODING_ALIASES[lowerEncoding];33 }3435 if (ENCODINGS.has(lowerEncoding)) {36 return lowerEncoding;37 }38};3940const ENCODING_ALIASES = {41 // eslint-disable-next-line unicorn/text-encoding-identifier-case42 'utf-8': 'utf8',43 'utf-16le': 'utf16le',44 'ucs-2': 'utf16le',45 ucs2: 'utf16le',46 binary: 'latin1',47};4849const serializeEncoding = encoding => typeof encoding === 'string' ? `"${encoding}"` : String(encoding);