@hirosystems/api-toolkit
Version:
API development toolkit
165 lines • 5.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.has0xPrefix = exports.isProdEnv = exports.isTestEnv = exports.isDevEnv = void 0;
exports.sha256 = sha256;
exports.parseBoolean = parseBoolean;
exports.bufferToHex = bufferToHex;
exports.hexToBuffer = hexToBuffer;
exports.coerceToBuffer = coerceToBuffer;
exports.hexToUtf8String = hexToUtf8String;
exports.numberToHex = numberToHex;
exports.toEnumValue = toEnumValue;
exports.unwrap = unwrap;
const node_crypto_1 = require("node:crypto");
const types_1 = require("node:util/types");
exports.isDevEnv = process.env.NODE_ENV === 'development';
exports.isTestEnv = process.env.NODE_ENV === 'test';
exports.isProdEnv = process.env.NODE_ENV === 'production' ||
process.env.NODE_ENV === 'prod' ||
!process.env.NODE_ENV ||
(!exports.isTestEnv && !exports.isDevEnv);
/**
* Digests a string value into a SHA256 hash.
* @param content - String input
* @returns Hashed value
*/
function sha256(content) {
return (0, node_crypto_1.createHash)('sha256').update(content).digest('hex');
}
/**
* Parses a boolean string using conventions from CLI arguments, URL query params, and environmental
* variables. If the input is defined but empty string then true is returned. If the input is
* undefined or null than false is returned. For example, if the input comes from a CLI arg like
* `--enable_thing` or URL query param like `?enable_thing`, then this function expects to receive a
* defined but empty string, and returns true. Otherwise, it checks or values like `true`, `1`,
* `on`, `yes` (and the inverses). Throws if an unexpected input value is provided.
*/
function parseBoolean(val) {
if (typeof val === 'undefined' || val === null) {
return false;
}
switch (val.trim().toLowerCase()) {
case '':
case 'true':
case '1':
case 'on':
case 'yes':
return true;
case 'false':
case '0':
case 'off':
case 'no':
return false;
default:
throw new Error(`Cannot parse boolean`);
}
}
/**
* Encodes a buffer as a `0x` prefixed lower-case hex string. Returns an empty string if the buffer
* is zero length.
*/
function bufferToHex(buff, prefix = true) {
return buff.length === 0 ? '' : (prefix ? '0x' : '') + buff.toString('hex');
}
/**
* Decodes a `0x` prefixed hex string to a buffer.
* @param hex - A hex string with a `0x` prefix.
*/
function hexToBuffer(hex) {
if (hex.length === 0) {
return Buffer.alloc(0);
}
if (!hex.startsWith('0x')) {
throw new Error(`Hex string is missing the "0x" prefix`);
}
if (hex.length % 2 !== 0) {
throw new Error(`Hex string is an odd number of digits`);
}
return Buffer.from(hex.substring(2), 'hex');
}
/**
* Decodes a hex string to a Buffer, trims the 0x-prefix if exists.
* If already a buffer, returns the input immediately.
*/
function coerceToBuffer(hex) {
if (typeof hex === 'string') {
if (hex.startsWith('0x')) {
hex = hex.substring(2);
}
if (hex.length % 2 !== 0) {
throw new Error(`Hex string is an odd number of characters`);
}
if (!/^[0-9a-fA-F]*$/.test(hex)) {
throw new Error(`Hex string contains non-hexadecimal characters`);
}
return Buffer.from(hex, 'hex');
}
else if (Buffer.isBuffer(hex)) {
return hex;
}
else if ((0, types_1.isArrayBufferView)(hex)) {
return Buffer.from(hex.buffer, hex.byteOffset, hex.byteLength);
}
else {
throw new Error(`Cannot convert to Buffer, unexpected type: ${hex.constructor.name}`);
}
}
/**
* Converts a hex string into a UTF-8 string.
* @param hex - Hex string
* @returns UTF-8 string
*/
function hexToUtf8String(hex) {
const buffer = hexToBuffer(hex);
return buffer.toString('utf8');
}
/**
* Converts a number to a hex string.
* @param number - Number
* @param paddingBytes - Padding bytes
* @returns Hex string
*/
function numberToHex(number, paddingBytes = 4) {
let result = number.toString(16);
if (result.length % 2 > 0) {
result = '0' + result;
}
if (paddingBytes && result.length / 2 < paddingBytes) {
result = '00'.repeat(paddingBytes - result.length / 2) + result;
}
return '0x' + result;
}
/**
* Checks if a string has `0x` prefix.
* @param val - Hex string
* @returns Boolean
*/
const has0xPrefix = (val) => val.substring(0, 2).toLowerCase() === '0x';
exports.has0xPrefix = has0xPrefix;
/**
* Converts a string to an enum value.
* @param enumType - The enum type
* @param value - The string value to convert
* @returns Enum item or undefined
*/
function toEnumValue(enm, value) {
return Object.values(enm).includes(value)
? value
: undefined;
}
/**
* Unwraps a value that may be undefined or null.
* @param val - The value to unwrap
* @param onNullish - Callback to throw an error if the value is null or undefined
* @returns The unwrapped value
*/
function unwrap(val, onNullish) {
if (val === undefined) {
throw new Error(onNullish?.() ?? 'value is undefined');
}
if (val === null) {
throw new Error(onNullish?.() ?? 'value is null');
}
return val;
}
//# sourceMappingURL=values.js.map