@ideascol/cli-maker
Version:
A simple library to help create CLIs
74 lines (73 loc) • 3.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Validator = void 0;
const colors_1 = require("../colors");
const interfaces_1 = require("../interfaces");
class Validator {
validateParam(value, type, isRequired, options, paramName) {
if (this.checkEmpty(value) && isRequired) {
return { error: `${colors_1.Colors.FgRed}Missing required parameter${paramName ? `: ${paramName}` : ''}${colors_1.Colors.Reset}` };
}
else if (this.checkEmpty(value) && !isRequired) {
return { value: undefined, error: "" };
}
if (value === undefined) {
return { value };
}
switch (type) {
case interfaces_1.ParamType.Number:
if (!/^[0-9]+$/.test(value)) {
return { error: `${colors_1.Colors.FgRed}Invalid number:${colors_1.Colors.Reset} ${value}` };
}
return { value: Number(value) };
case interfaces_1.ParamType.Custom:
try {
const customValue = JSON.parse(value);
if (Array.isArray(customValue) || typeof customValue === 'object') {
return { value: customValue };
}
else {
return { error: `${colors_1.Colors.FgRed}Invalid custom value:${colors_1.Colors.Reset} ${value}` };
}
}
catch {
return { error: `${colors_1.Colors.FgRed}Invalid custom value:${colors_1.Colors.Reset} ${value}` };
}
case interfaces_1.ParamType.List:
if (options === undefined || options?.length === 0) {
return { error: `${colors_1.Colors.FgRed}Invalid List:${colors_1.Colors.Reset} empty options`, value: undefined };
}
const foundValue = options?.filter(x => x === value);
if (foundValue?.length === 0) {
return { error: `${colors_1.Colors.FgRed}Invalid List:${colors_1.Colors.Reset} ${value} doesn't exists`, value: undefined };
}
return { value: value };
case interfaces_1.ParamType.Boolean:
if (value.toLowerCase() !== 'true' && value.toLowerCase() !== 'false') {
return { error: `${colors_1.Colors.FgRed}Invalid boolean:${colors_1.Colors.Reset} ${value}` };
}
return { value: value.toLowerCase() === 'true' };
case interfaces_1.ParamType.Email:
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
return { error: `${colors_1.Colors.FgRed}Invalid email:${colors_1.Colors.Reset} ${value}` };
}
return { value };
case interfaces_1.ParamType.Url:
if (!/^https?:\/\/.+$/.test(value)) {
return { error: `${colors_1.Colors.FgRed}Invalid URL:${colors_1.Colors.Reset} ${value}` };
}
return { value };
case interfaces_1.ParamType.Package:
if (!/^@[a-zA-Z0-9-]+\/[a-zA-Z0-9-]+$/.test(value)) {
return { error: `${colors_1.Colors.FgRed}the format of the package is not correct, @company/package-name${colors_1.Colors.Reset}` };
}
return { value };
default:
return { value };
}
}
checkEmpty(value) {
return value === undefined || value === '' || value === null;
}
}
exports.Validator = Validator;