UNPKG

cn-shell

Version:
110 lines (109 loc) 3.49 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return mod && mod.__esModule ? mod : { default: mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ConfigMan = exports.ConfigTypes = void 0; const dotenv_1 = __importDefault(require("dotenv")); const minimist_1 = __importDefault(require("minimist")); const CFG_DOTENV_PATH = "DOTENV_PATH"; const DEFAULT_CONFIG_OPTIONS = { silent: false, redact: false, envVarPrefix: "", }; var ConfigTypes; (function (ConfigTypes) { ConfigTypes[(ConfigTypes["String"] = 0)] = "String"; ConfigTypes[(ConfigTypes["Boolean"] = 1)] = "Boolean"; ConfigTypes[(ConfigTypes["Number"] = 2)] = "Number"; })((ConfigTypes = exports.ConfigTypes || (exports.ConfigTypes = {}))); class ConfigMan { _minimist; constructor() { this._minimist = (0, minimist_1.default)(process.argv.slice(2)); let dotenvPath = this.get(CFG_DOTENV_PATH, ConfigTypes.String, { defaultVal: "", }); if (dotenvPath.length) { dotenv_1.default.config({ path: dotenvPath }); } } convertConfigValue(value, type) { switch (type) { case ConfigTypes.Number: return parseInt(value); case ConfigTypes.Boolean: if (value.toUpperCase() === "Y") { return true; } return false; default: return value; } } get(config, type, passedOptions = {}, appOrExtName = "", logger) { let options = { ...DEFAULT_CONFIG_OPTIONS, ...passedOptions, }; let cliParams = config.toLowerCase(); let value = this._minimist[cliParams]; if (value !== undefined) { if (logger !== undefined && logger.started && options.silent === false) { logger.startup( appOrExtName, "CLI parameter (%s) = (%j)", cliParams, options.redact ? "redacted" : value, ); } if (type === ConfigTypes.String && typeof value === "number") { return value.toString(); } if (type === ConfigTypes.String && typeof value !== "string") { throw Error(`Config parameter (${config}) should be a string!`); } if (type === ConfigTypes.Number && typeof value !== "number") { throw Error(`Config parameter (${config}) should be a number!`); } if (type === ConfigTypes.Boolean && typeof value !== "boolean") { throw Error(`Config parameter (${config}) should be a boolean!`); } return value; } let evar = `${options.envVarPrefix}${config.toUpperCase()}`; value = process.env[evar]; if (value !== undefined) { value = this.convertConfigValue(value, type); if (logger !== undefined && logger.started && options.silent === false) { logger.startup( appOrExtName, "Env var (%s) = (%j)", evar, options.redact ? "redacted" : value, ); } } if (value === undefined) { if (options.defaultVal === undefined) { throw Error( `Config parameter (${config}) not set on the CLI or as an env var!`, ); } value = options.defaultVal; if (logger !== undefined && logger.started && options.silent === false) { logger.startup( appOrExtName, "Default value used for (%s) = (%j)", config, options.redact ? "redacted" : value, ); } } return value; } } exports.ConfigMan = ConfigMan;