UNPKG

envalid

Version:

Validation for your environment variables

71 lines 3 kB
"use strict"; var _a; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultReporter = exports.envalidErrorFormatter = void 0; /* eslint-disable no-console */ var errors_1 = require("./errors"); var defaultLogger = console.error.bind(console); // Apply ANSI colors to the reporter output only if we detect that we're running in Node var isNode = !!(typeof process === 'object' && ((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node)); var colorWith = function (colorCode) { return function (str) { return isNode ? "\u001B[".concat(colorCode, "m").concat(str, "\u001B[0m") : str; }; }; var colors = { blue: colorWith('34'), white: colorWith('37'), yellow: colorWith('33'), }; var RULE = colors.white('================================'); // Takes the provided errors, formats them all to an output string, and passes that string output to the // provided "logger" function. // // This is exposed in the public API so third-party reporters can leverage this logic if desired var envalidErrorFormatter = function (errors, logger) { if (logger === void 0) { logger = defaultLogger; } var missingVarsOutput = []; var invalidVarsOutput = []; for (var _i = 0, _a = Object.entries(errors); _i < _a.length; _i++) { var _b = _a[_i], k = _b[0], err = _b[1]; if (err instanceof errors_1.EnvMissingError) { missingVarsOutput.push(" ".concat(colors.blue(k), ": ").concat(err.message || '(required)')); } else invalidVarsOutput.push(" ".concat(colors.blue(k), ": ").concat((err === null || err === void 0 ? void 0 : err.message) || '(invalid format)')); } // Prepend "header" output for each section of the output: if (invalidVarsOutput.length) { invalidVarsOutput.unshift(" ".concat(colors.yellow('Invalid'), " environment variables:")); } if (missingVarsOutput.length) { missingVarsOutput.unshift(" ".concat(colors.yellow('Missing'), " environment variables:")); } var output = [ RULE, invalidVarsOutput.sort().join('\n'), missingVarsOutput.sort().join('\n'), RULE, ] .filter(function (x) { return !!x; }) .join('\n'); logger(output); }; exports.envalidErrorFormatter = envalidErrorFormatter; var defaultReporter = function (_a, _b) { var _c = _a.errors, errors = _c === void 0 ? {} : _c; var _d = _b === void 0 ? { logger: defaultLogger } : _b, onError = _d.onError, logger = _d.logger; if (!Object.keys(errors).length) return; (0, exports.envalidErrorFormatter)(errors, logger); if (onError) { onError(errors); } else if (isNode) { logger(colors.yellow('\n Exiting with error code 1')); process.exit(1); } else { throw new TypeError('Environment validation failed'); } }; exports.defaultReporter = defaultReporter; //# sourceMappingURL=reporter.js.map