UNPKG

@serpent/common-cli

Version:

通用的 cli 相关的函数

90 lines (87 loc) 3.8 kB
import { _ as __awaiter, a as __generator, c as __assign } from './tslib.es6-636c4f06.mjs'; import { w as warn } from './warn-1994a28d.mjs'; import { e as exists } from './exists-d3d14d46.mjs'; import Module from 'module'; var require = Module.createRequire(import.meta.url); /** * 获取环境变量中的 boolean 类型的变量 * * 如 `process.env.FOO = false` 时使用 `getBoolEnv('FOO') === false` * @param key 环境变量的键名 */ function getBoolEnv(key) { var val = process.env[key]; if (val == null) return false; if (/^(0|no|false|null|nil)$/i.test(val.trim())) return false; return true; } /** * 加载文件模块,如果文件模块不存在或加载失败,会使用 defaults 内容 * @param filePath 文件模块路径 * @param defaults 默认内容(文件模块不存在,或字段不全时会使用此字段中的内容) * @param options 配置项 */ function loadScript(filePath, defaults, options) { if (options === void 0) { options = {}; } return __awaiter(this, void 0, void 0, function () { var mod, _a, validateKey, _b, validateType, scriptFile, getMod, defaultKeys_1, modKeys, e_2; return __generator(this, function (_c) { switch (_c.label) { case 0: mod = {}; _a = options.validateKey, validateKey = _a === void 0 ? true : _a, _b = options.validateType, validateType = _b === void 0 ? true : _b; _c.label = 1; case 1: _c.trys.push([1, 7, , 8]); scriptFile = getOptionalScriptFile(filePath); if (!scriptFile) return [3 /*break*/, 6]; getMod = function (m) { return m.default ? m.default : m; }; _c.label = 2; case 2: _c.trys.push([2, 4, , 5]); return [4 /*yield*/, import(scriptFile).then(getMod)]; case 3: mod = _c.sent(); return [3 /*break*/, 5]; case 4: _c.sent(); mod = getMod(require(scriptFile)); return [3 /*break*/, 5]; case 5: defaultKeys_1 = Object.keys(defaults); modKeys = Object.keys(mod); modKeys.forEach(function (k) { var modType = typeof mod[k]; var defType = typeof defaults[k]; if (validateKey && !defaultKeys_1.includes(k)) { warn(" find extra property \"".concat(k, "\", in file \"").concat(filePath, "\"")); } else if (validateType && modType && defType && modType !== defType) { warn(" expect property ".concat(k, "'s type to be \"").concat(defType, "\", not ").concat(modType, ", in file \"").concat(filePath, "\"")); } }); _c.label = 6; case 6: return [3 /*break*/, 8]; case 7: e_2 = _c.sent(); warn(" load script \"".concat(filePath, "\" error:"), e_2); return [3 /*break*/, 8]; case 8: return [2 /*return*/, __assign(__assign({}, defaults), mod)]; } }); }); } function getOptionalScriptFile(filePath) { var base = filePath.replace(/\.\w+$/, ''); var files = [ base + '.js', base + '.cjs', base + '.mjs', ]; if (!files.includes(filePath)) files.unshift(filePath); return files.find(function (file) { return exists.file(file); }); } export { getBoolEnv as g, loadScript as l };