@bshg/validation
Version:
Validation Library for TypeScript projects
967 lines (948 loc) • 85.2 kB
JavaScript
const options = {
dev: false,
resultsType: `object`,
};
const updateValidatorOptions = (validatorOptions) => {
var _a, _b;
options.dev = (_a = validatorOptions.dev) !== null && _a !== void 0 ? _a : options.dev;
options.resultsType = (_b = validatorOptions.resultsType) !== null && _b !== void 0 ? _b : options.resultsType;
};
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
const messageVars = {
prefix: "%",
value: "%val",
name: "%name",
};
const messageArgs = (defaultMsg, options, ...args) => {
const msg = message(defaultMsg, options);
return (msg.includes("%") || (args === null || args === void 0 ? void 0 : args.length) > 0) ? msg.replace(/%(\d+)/g, (_, i) => args[i - 1]) : msg;
};
const message = (message, options) => {
if (options && options.message) {
return (typeof options.message == "string") ? options.message : options.message();
}
return message;
};
class TypeValidator {
constructor() {
this.validations = [];
this.validationsDepend = [];
this.validationsAsync = [];
this.validationsDependAsync = [];
this.validationsCtx = [];
this.validationsDependCtx = [];
this.validationsCtxAsync = [];
this.validationsDependCtxAsync = [];
}
onError(config) {
if ("error" in config) {
if (config.error.length > 1) {
this.validationsDepend.push(config);
}
else {
this.validations.push(config);
}
}
return this;
}
onErrorCtx(config) {
if ("error" in config) {
if (config.error.length > 2) {
this.validationsDependCtx.push(config);
}
else {
this.validationsCtx.push(config);
}
}
return this;
}
useCostume(arg) {
return this.onError({
error: arg.error,
message: messageArgs(arg.message, arg.options, arg.args),
});
}
onErrorAsync(config) {
if ("error" in config && config.error.length > 1) {
this.validationsDependAsync.push(config);
}
else if ("error" in config) {
this.validationsAsync.push(config);
}
return this;
}
onErrorCtxAsync(config) {
if ("error" in config && config.error.length > 2) {
this.validationsDependCtxAsync.push(config);
}
else if ("error" in config) {
this.validationsCtxAsync.push(config);
}
return this;
}
}
const fr = {
noMessage: "No Error Message Was Provided!",
string: {
required: "Ce champ est requis !",
notEmpty: "Ce champ ne peut pas être vide !",
min: "La longueur minimale requise est de %1",
max: "La longueur maximale autorisée est de %1",
includes: "Doit inclure \"%1\"",
includesAll: "Doit inclure tous : %1",
startsWith: "Doit commencer par \"%1\"",
endsWith: "Doit se terminer par \"%1\"",
matches: "Ne correspond pas au modèle requis",
email: "Format d'email invalide",
phone: "Format de téléphone invalide",
url: "Format d'URL invalide",
date: "Format de date invalide",
time: "Format d'heure invalide",
hexColor: "Format de couleur hexadécimale invalide",
creditCard: "Format de numéro de carte de crédit invalide",
htmlTag: "Format de balise HTML invalide",
base64: "Format Base64 invalide",
alphanumeric: "Doit contenir uniquement des caractères alphanumériques",
numeric: "Doit contenir uniquement des caractères numériques",
alpha: "Doit contenir uniquement des caractères alphabétiques",
as: "La valeur doit être comme '%1'",
},
number: {
required: "Ce champ est requis !",
min: "La valeur doit être supérieure ou égale à %1",
max: "La valeur doit être inférieure ou égale à %1",
range: "La valeur doit être comprise entre %1 et %2",
integer: "La valeur doit être un nombre entier",
positive: "La valeur doit être positive",
negative: "La valeur doit être négative",
decimal: "La valeur doit être un nombre décimal",
multipleOf: "La valeur doit être un multiple de %1",
betweenExclusive: "La valeur doit être comprise entre %1 (exclusif) et %2 (exclusif)",
even: "La valeur doit être un nombre pair",
odd: "La valeur doit être un nombre impair",
positiveInteger: "La valeur doit être un entier positif",
negativeInteger: "La valeur doit être un entier négatif",
positiveDecimal: "La valeur doit être un nombre décimal positif",
negativeDecimal: "La valeur doit être un nombre décimal négatif",
divisibleBy: "La valeur doit être divisible par %1",
perfectSquare: "La valeur doit être un carré parfait",
primeNumber: "La valeur doit être un nombre premier",
fibonacciNumber: "La valeur doit être un nombre de Fibonacci",
powerOfTwo: "La valeur doit être une puissance de deux",
as: "La valeur doit être comme '%1'",
},
boolean: {
required: "Ce champ est requis !",
true: "La valeur doit être vrai",
false: "La valeur doit être faux",
equals: "La valeur doit être égale à %1",
as: "La valeur doit être comme '%1'",
},
array: {
length: "La valeur doit avoir une longueur de %1",
min: "La longueur minimale requise est de %1",
max: "La longueur maximale autorisée est de %1",
has: "La valeur doit inclure %1",
hasAll: "La valeur doit inclure tous : %1",
hasAny: "La valeur doit inclure n'importe lequel de : %1",
hasNone: "La valeur ne doit inclure aucun de : %1",
some: "Le tableau ne correspond pas au prédicat donné",
every: "Le tableau ne correspond pas au prédicat donné",
},
datetime: {
required: "Ce champ est requis !",
equals: "La valeur doit être %1",
after: "La date et l'heure doivent être postérieures à %1",
before: "La date et l'heure doivent être antérieures à %1",
between: "La date et l'heure doivent être comprises entre %1 et %2",
todayOrAfter: "La date et l'heure doivent être aujourd'hui ou postérieures à aujourd'hui",
todayOrBefore: "La date et l'heure doivent être aujourd'hui ou antérieures à aujourd'hui",
past: "La date et l'heure doivent être dans le passé",
future: "La date et l'heure doivent être dans le futur",
weekday: "La date et l'heure doivent être un jour de semaine",
weekend: "La date et l'heure doivent être un jour de week-end",
as: "La valeur doit être comme '%1'",
},
date: {
required: "Ce champ est requis !",
equals: "La valeur doit être %1",
after: "La date doit être postérieure à %1",
before: "La date doit être antérieure à %1",
between: "La date doit être comprise entre %1 et %2",
todayOrAfter: "La date doit être aujourd'hui ou postérieure à aujourd'hui",
todayOrBefore: "La date doit être aujourd'hui ou antérieure à aujourd'hui",
past: "La date doit être dans le passé",
future: "La date doit être dans le futur",
weekday: "La date doit être un jour de semaine",
weekend: "La date doit être un jour de week-end",
leapYear: "La date doit être dans une année bissextile",
sameDayAs: "La date doit être le même jour que %1",
as: "La valeur doit être comme '%1'",
},
time: {
required: "Ce champ est requis !",
equals: "La valeur doit être %1",
after: "L'heure doit être postérieure à %1",
before: "L'heure doit être antérieure à %1",
between: "L'heure doit être comprise entre %1 et %2",
nowOrAfter: "L'heure doit être maintenant ou postérieure à maintenant",
nowOrBefore: "L'heure doit être maintenant ou antérieure à maintenant",
past: "L'heure doit être dans le passé",
future: "L'heure doit être dans le futur",
within24Hours: "L'heure doit être dans les 24 prochaines heures",
as: "La valeur doit être comme '%1'",
},
};
const en = {
noMessage: "No Error Message Was Provided!",
string: {
required: "This field is required!",
notEmpty: "This field is required!",
min: "Minimum length required is %1",
max: "Maximum length allowed is %1",
includes: "Must include \"%1\"",
includesAll: "Must include all of: %1",
startsWith: "Must start with \"%1\"",
endsWith: "Must end with \"%1\"",
matches: "Does not match the required pattern",
email: "Invalid email format",
phone: "Invalid phone format",
url: "Invalid URL format",
date: "Invalid date format",
time: "Invalid time format",
hexColor: "Invalid hex color format",
creditCard: "Invalid credit card number format",
htmlTag: "Invalid HTML tag format",
base64: "Invalid Base64 format",
alphanumeric: "Must contain only alphanumeric characters",
numeric: "Must contain only numeric characters",
alpha: "Must contain only alphabetic characters",
as: "Value must be as '%1'",
},
number: {
required: "This field is required!",
min: "Value must be greater than or equal to %1",
max: "Value must be less than or equal to %1",
range: "Value must be between %1 and %2",
integer: "Value must be an integer",
positive: "Value must be positive",
negative: "Value must be negative",
decimal: "Value must be a decimal number",
multipleOf: "Value must be a multiple of %1",
betweenExclusive: "Value must be between %1 (exclusive) and %2 (exclusive)",
even: "Value must be an even number",
odd: "Value must be an odd number",
positiveInteger: "Value must be a positive integer",
negativeInteger: "Value must be a negative integer",
positiveDecimal: "Value must be a positive decimal number",
negativeDecimal: "Value must be a negative decimal number",
divisibleBy: "Value must be divisible by %1",
perfectSquare: "Value must be a perfect square",
primeNumber: "Value must be a prime number",
fibonacciNumber: "Value must be a Fibonacci number",
powerOfTwo: "Value must be a power of two",
as: "value must be as '%1'",
},
boolean: {
required: "This field is required!",
true: "Value must be true",
false: "Value must be false",
equals: "Value must be equal to %1",
as: "value must be as '%1'",
},
array: {
length: "Value must be of length %1",
min: "Minimum length required is %1",
max: "Maximum length allowed is %1",
has: "Value must include %1",
hasAll: "Value must include all of: %1",
hasAny: "Value must include any of: %1",
hasNone: "Value must include none of: %1",
some: "Array does not match the given predicate!",
every: "Array does not match the given predicate!",
},
datetime: {
required: "This field is required!",
equals: "value must be %1",
after: "DateTime must be after %1",
before: "DateTime must be before %1",
between: "DateTime must be between %1 and %2",
todayOrAfter: "DateTime must be today or after today",
todayOrBefore: "DateTime must be today or before today",
past: "DateTime must be in the past",
future: "DateTime must be in the future",
weekday: "DateTime must be a weekday",
weekend: "DateTime must be a weekend",
as: "Value must be as '%1'",
},
date: {
required: "This field is required!",
equals: "value must be %1",
after: "Date must be after %1",
before: "Date must be before %1",
between: "Date must be between %1 and %2",
todayOrAfter: "Date must be today or after today",
todayOrBefore: "Date must be today or before today",
past: "Date must be in the past",
future: "Date must be in the future",
weekday: "Date must be a weekday",
weekend: "Date must be a weekend",
leapYear: "Date must be in a leap year",
sameDayAs: "Date must be the same day as %1",
as: "value must be as '%1'",
},
time: {
required: "This field is required!",
equals: "value must be %1",
after: "Time must be after %1",
before: "Time must be before %1",
between: "Time must be between %1 and %2",
nowOrAfter: "Time must be now or after now",
nowOrBefore: "Time must be now or before now",
past: "Time must be in the past",
future: "Time must be in the future",
within24Hours: "Time must be within the next 24 hours",
as: "value must be as '%1'",
},
};
const ar = {
noMessage: "No Error Message Was Provided!",
string: {
required: "هذا الحقل إلزامي!",
notEmpty: "هذا الحقل إلزامي!",
min: "الحد الأدنى للطول هو %1",
max: "الحد الأقصى للطول هو %1",
includes: "يجب أن يحتوي على \"%1\"",
includesAll: "يجب أن يحتوي على الكل: %1",
startsWith: "يجب أن يبدأ بـ \"%1\"",
endsWith: "يجب أن ينتهي بـ \"%1\"",
matches: "لا يتطابق مع النمط المطلوب",
email: "صيغة البريد الإلكتروني غير صالحة",
phone: "صيغة الهاتف غير صالحة",
url: "صيغة الرابط غير صالحة",
date: "صيغة التاريخ غير صالحة",
time: "صيغة الوقت غير صالحة",
hexColor: "صيغة اللون الهكساديسيمال غير صالحة",
creditCard: "صيغة رقم بطاقة الائتمان غير صالحة",
htmlTag: "صيغة العلامة HTML غير صالحة",
base64: "صيغة Base64 غير صالحة",
alphanumeric: "يجب أن يحتوي على حروف أبجدية وأرقام فقط",
numeric: "يجب أن يحتوي على أرقام فقط",
alpha: "يجب أن يحتوي على حروف أبجدية فقط",
as: "القيمة يجب أن تكون كـ '%1'",
},
number: {
required: "هذا الحقل إلزامي!",
min: "القيمة يجب أن تكون أكبر من أو تساوي %1",
max: "القيمة يجب أن تكون أصغر من أو تساوي %1",
range: "القيمة يجب أن تكون بين %1 و %2",
integer: "القيمة يجب أن تكون عدد صحيح",
positive: "القيمة يجب أن تكون إيجابية",
negative: "القيمة يجب أن تكون سالبة",
decimal: "القيمة يجب أن تكون عددًا عشريًا",
multipleOf: "القيمة يجب أن تكون مضاعفة لـ %1",
betweenExclusive: "القيمة يجب أن تكون بين %1 (حصريًا) و %2 (حصريًا)",
even: "القيمة يجب أن تكون عددًا زوجيًا",
odd: "القيمة يجب أن تكون عددًا فرديًا",
positiveInteger: "القيمة يجب أن تكون عددًا صحيحًا موجبًا",
negativeInteger: "القيمة يجب أن تكون عددًا صحيحًا سالبًا",
positiveDecimal: "القيمة يجب أن تكون عددًا عشريًا موجبًا",
negativeDecimal: "القيمة يجب أن تكون عددًا عشريًا سالبًا",
divisibleBy: "القيمة يجب أن تكون قابلة للقسمة على %1",
perfectSquare: "القيمة يجب أن تكون عددًا مربعًا مثاليًا",
primeNumber: "القيمة يجب أن تكون عددًا أوليًا",
fibonacciNumber: "القيمة يجب أن تكون عددًا في سلسلة فيبوناتشي",
powerOfTwo: "القيمة يجب أن تكون عددًا مربعًا للعدد 2",
as: "القيمة يجب أن تكون كـ '%1'",
},
boolean: {
required: "هذا الحقل إلزامي!",
true: "القيمة يجب أن تكون 'صحيحة'",
false: "القيمة يجب أن تكون 'خاطئة'",
equals: "القيمة يجب أن تكون %1",
as: "القيمة يجب أن تكون '%1'",
},
array: {
length: "القيمة يجب أن تكون بطول %1",
min: "الحد الأدنى للطول المطلوب هو %1",
max: "الحد الأقصى المسموح به هو %1",
has: "القيمة يجب أن تتضمن %1",
hasAll: "القيمة يجب أن تتضمن الكل من: %1",
hasAny: "القيمة يجب أن تتضمن أيًا من: %1",
hasNone: "القيمة يجب أن لا تتضمن أيًا من: %1",
some: "المصفوفة لا تتطابق مع الشرط المعطى!",
every: "المصفوفة لا تتطابق مع الشرط المعطى!",
},
datetime: {
required: "هذا الحقل إلزامي!",
equals: "القيمة يجب أن تكون %1",
after: "يجب أن يكون التاريخ بعد %1",
before: "يجب أن يكون التاريخ قبل %1",
between: "يجب أن يكون التاريخ بين %1 و %2",
todayOrAfter: "يجب أن يكون التاريخ اليوم أو بعد اليوم",
todayOrBefore: "يجب أن يكون التاريخ اليوم أو قبل اليوم",
past: "يجب أن يكون التاريخ في الماضي",
future: "يجب أن يكون التاريخ في المستقبل",
weekday: "يجب أن يكون التاريخ يومًا عمليًا",
weekend: "يجب أن يكون التاريخ عطلة نهاية أسبوع",
as: "القيمة يجب أن تكون كـ '%1'",
},
date: {
required: "هذا الحقل إلزامي!",
equals: "القيمة يجب أن تكون %1",
after: "يجب أن يكون التاريخ بعد %1",
before: "يجب أن يكون التاريخ قبل %1",
between: "يجب أن يكون التاريخ بين %1 و %2",
todayOrAfter: "يجب أن يكون التاريخ اليوم أو بعد اليوم",
todayOrBefore: "يجب أن يكون التاريخ اليوم أو قبل اليوم",
past: "يجب أن يكون التاريخ في الماضي",
future: "يجب أن يكون التاريخ في المستقبل",
weekday: "يجب أن يكون التاريخ يومًا عمليًا",
weekend: "يجب أن يكون التاريخ عطلة نهاية أسبوع",
leapYear: "يجب أن يكون التاريخ في سنة كبيسة",
sameDayAs: "يجب أن يكون التاريخ نفس اليوم كـ %1",
as: "القيمة يجب أن تكون كـ '%1'",
},
time: {
required: "هذا الحقل إلزامي!",
equals: "القيمة يجب أن تكون %1",
after: "يجب أن يكون الوقت بعد %1",
before: "يجب أن يكون الوقت قبل %1",
between: "يجب أن يكون الوقت بين %1 و %2",
nowOrAfter: "يجب أن يكون الوقت الآن أو بعد الآن",
nowOrBefore: "يجب أن يكون الوقت الآن أو قبل الآن",
past: "يجب أن يكون الوقت في الماضي",
future: "يجب أن يكون الوقت في المستقبل",
within24Hours: "يجب أن يكون الوقت خلال الـ 24 ساعة القادمة",
as: "القيمة يجب أن تكون كـ '%1'",
},
};
const Messages = { en, fr, ar };
let CurrentLocalize = en;
const changeLocal = (local) => {
CurrentLocalize = Messages[local];
};
var index = /*#__PURE__*/Object.freeze({
__proto__: null,
get CurrentLocalize () { return CurrentLocalize; },
Messages: Messages,
changeLocal: changeLocal
});
const timestamp = () => new Date().toISOString();
const prefix = (level, tag) => `[${timestamp()}] [@bshg/validation] [${level}] [${tag}]`;
const info = (tag, log, ...data) => {
if (log)
console.log(prefix("INFO", tag), ...data);
};
const warn = (tag, log, ...data) => {
if (log)
console.warn(prefix("WARNING", tag), ...data);
};
const error = (tag, log, ...data) => {
if (log)
console.error(prefix("ERROR", tag), ...data);
};
var logger = { info, warn, error };
const LOGGER = { info, warn, error };
class BshgError extends Error {
constructor(tag, err) {
super(err);
if (tag != undefined)
LOGGER.error(tag, true, err);
}
}
class ValidationFailedError extends BshgError {
constructor() {
super();
}
}
var _ValidatorItem_instances, _ValidatorItem_validations, _ValidatorItem_validationsDepend, _ValidatorItem_validationsAsync, _ValidatorItem_validationsDependAsync, _ValidatorItem_validationsCtx, _ValidatorItem_validationsDependCtx, _ValidatorItem_validationsCtxAsync, _ValidatorItem_validationsDependCtxAsync, _ValidatorItem_validationsWithContext, _ValidatorItem_onChange, _ValidatorItem_getMessage, _ValidatorItem_setTheError, _ValidatorItem_doValidations, _ValidatorItem_doValidationsCtx, _ValidatorItem_doValidationsAsync, _ValidatorItem_doValidationsCtxAsync, _ValidatorItem_takeValidationsFromContext, _ValidatorItem_doValidationsWithContext, _ValidatorItem_doValidationsWithContextAsync;
class ValidatorItem {
constructor() {
var _a;
_ValidatorItem_instances.add(this);
this.context = (_a = this.validator) === null || _a === void 0 ? void 0 : _a.context;
_ValidatorItem_validations.set(this, void 0);
_ValidatorItem_validationsDepend.set(this, void 0);
_ValidatorItem_validationsAsync.set(this, void 0);
_ValidatorItem_validationsDependAsync.set(this, void 0);
_ValidatorItem_validationsCtx.set(this, void 0);
_ValidatorItem_validationsDependCtx.set(this, void 0);
_ValidatorItem_validationsCtxAsync.set(this, void 0);
_ValidatorItem_validationsDependCtxAsync.set(this, void 0);
_ValidatorItem_validationsWithContext.set(this, void 0);
this.validate = () => {
var _a, _b, _c, _d;
try {
(_a = __classPrivateFieldGet(this, _ValidatorItem_validations, "f")) === null || _a === void 0 ? void 0 : _a.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidations).call(this, it));
(_b = __classPrivateFieldGet(this, _ValidatorItem_validationsDepend, "f")) === null || _b === void 0 ? void 0 : _b.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidations).call(this, it));
(_c = __classPrivateFieldGet(this, _ValidatorItem_validationsCtx, "f")) === null || _c === void 0 ? void 0 : _c.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtx).call(this, it));
(_d = __classPrivateFieldGet(this, _ValidatorItem_validationsDependCtx, "f")) === null || _d === void 0 ? void 0 : _d.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtx).call(this, it));
__classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsWithContext).call(this);
}
catch (e) {
if (e instanceof ValidationFailedError)
return;
throw e;
}
this.markAsValid();
};
this.validateAsync = async () => {
var _a, _b, _c, _d, _e, _f, _g, _h;
try {
(_a = __classPrivateFieldGet(this, _ValidatorItem_validations, "f")) === null || _a === void 0 ? void 0 : _a.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidations).call(this, it));
(_b = __classPrivateFieldGet(this, _ValidatorItem_validationsDepend, "f")) === null || _b === void 0 ? void 0 : _b.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidations).call(this, it));
(_c = __classPrivateFieldGet(this, _ValidatorItem_validationsCtx, "f")) === null || _c === void 0 ? void 0 : _c.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtx).call(this, it));
(_d = __classPrivateFieldGet(this, _ValidatorItem_validationsDependCtx, "f")) === null || _d === void 0 ? void 0 : _d.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtx).call(this, it));
await Promise.all([
...(((_e = __classPrivateFieldGet(this, _ValidatorItem_validationsAsync, "f")) === null || _e === void 0 ? void 0 : _e.map(async (it) => await __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsAsync).call(this, it))) || []),
...(((_f = __classPrivateFieldGet(this, _ValidatorItem_validationsDependAsync, "f")) === null || _f === void 0 ? void 0 : _f.map(async (it) => await __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsAsync).call(this, it))) || []),
...(((_g = __classPrivateFieldGet(this, _ValidatorItem_validationsCtxAsync, "f")) === null || _g === void 0 ? void 0 : _g.map(async (it) => await __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtxAsync).call(this, it))) || []),
...(((_h = __classPrivateFieldGet(this, _ValidatorItem_validationsDependCtxAsync, "f")) === null || _h === void 0 ? void 0 : _h.map(async (it) => await __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtxAsync).call(this, it))) || []),
]);
await __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsWithContextAsync).call(this);
}
catch (e) {
return;
}
this.valid = true;
this.message = undefined;
};
_ValidatorItem_getMessage.set(this, (fn) => {
return message(CurrentLocalize.noMessage, { message: fn.message });
});
}
setValidations(value) {
if (value instanceof Array) {
__classPrivateFieldSet(this, _ValidatorItem_validationsWithContext, value, "f");
}
else if (value) {
value = value;
__classPrivateFieldSet(this, _ValidatorItem_validations, value === null || value === void 0 ? void 0 : value.validations, "f");
__classPrivateFieldSet(this, _ValidatorItem_validationsDepend, value === null || value === void 0 ? void 0 : value.validationsDepend, "f");
__classPrivateFieldSet(this, _ValidatorItem_validationsAsync, value === null || value === void 0 ? void 0 : value.validationsAsync, "f");
__classPrivateFieldSet(this, _ValidatorItem_validationsDependAsync, value === null || value === void 0 ? void 0 : value.validationsDependAsync, "f");
__classPrivateFieldSet(this, _ValidatorItem_validationsCtx, value === null || value === void 0 ? void 0 : value.validationsCtx, "f");
__classPrivateFieldSet(this, _ValidatorItem_validationsDependCtx, value === null || value === void 0 ? void 0 : value.validationsDependCtx, "f");
__classPrivateFieldSet(this, _ValidatorItem_validationsCtxAsync, value === null || value === void 0 ? void 0 : value.validationsCtxAsync, "f");
__classPrivateFieldSet(this, _ValidatorItem_validationsDependCtxAsync, value === null || value === void 0 ? void 0 : value.validationsDependCtxAsync, "f");
}
}
reset() {
this.valid = undefined;
this.message = undefined;
__classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_onChange).call(this);
}
markAsError(msg) {
this.valid = false;
this.message = msg
.replace(messageVars.value, this.get() + "")
.replace(messageVars.name, this.name);
__classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_onChange).call(this);
}
/**
* @deprecated
* replaced with `markAsError`
* @param msg
* @see #markAsError
*/
error(msg) {
this.markAsError(msg);
}
markAsValid() {
this.valid = true;
this.message = undefined;
__classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_onChange).call(this);
}
apply(value) {
this.get = () => value;
this.validate();
return { status: this.valid, err: this.message };
}
}
_ValidatorItem_validations = new WeakMap(), _ValidatorItem_validationsDepend = new WeakMap(), _ValidatorItem_validationsAsync = new WeakMap(), _ValidatorItem_validationsDependAsync = new WeakMap(), _ValidatorItem_validationsCtx = new WeakMap(), _ValidatorItem_validationsDependCtx = new WeakMap(), _ValidatorItem_validationsCtxAsync = new WeakMap(), _ValidatorItem_validationsDependCtxAsync = new WeakMap(), _ValidatorItem_validationsWithContext = new WeakMap(), _ValidatorItem_getMessage = new WeakMap(), _ValidatorItem_instances = new WeakSet(), _ValidatorItem_onChange = function _ValidatorItem_onChange() {
var _a;
((_a = this.validator) === null || _a === void 0 ? void 0 : _a.onChangeEvent) && this.validator.onChangeEvent(this.container());
}, _ValidatorItem_setTheError = function _ValidatorItem_setTheError(fn, result) {
if (result) {
this.markAsError(__classPrivateFieldGet(this, _ValidatorItem_getMessage, "f").call(this, fn));
throw new ValidationFailedError();
}
}, _ValidatorItem_doValidations = function _ValidatorItem_doValidations(fn) {
const result = fn.error.length > 1
? fn.error(this.get(), this.container())
: fn.error(this.get());
__classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_setTheError).call(this, fn, result);
}, _ValidatorItem_doValidationsCtx = function _ValidatorItem_doValidationsCtx(fn) {
var _a, _b;
const result = fn.error.length > 2
? fn.error(this.get(), this.container(), (_a = this.validator) === null || _a === void 0 ? void 0 : _a.context)
: fn.error(this.get(), (_b = this.validator) === null || _b === void 0 ? void 0 : _b.context);
__classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_setTheError).call(this, fn, result);
}, _ValidatorItem_doValidationsAsync = async function _ValidatorItem_doValidationsAsync(fn) {
const result = fn.error.length > 1
? await fn.error(this.get(), this.container())
: await fn.error(this.get());
__classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_setTheError).call(this, fn, result);
}, _ValidatorItem_doValidationsCtxAsync = async function _ValidatorItem_doValidationsCtxAsync(fn) {
var _a, _b;
const result = fn.error.length > 2
? await fn.error(this.get(), this.container(), (_a = this.validator) === null || _a === void 0 ? void 0 : _a.context)
: await fn.error(this.get(), (_b = this.validator) === null || _b === void 0 ? void 0 : _b.context);
__classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_setTheError).call(this, fn, result);
}, _ValidatorItem_takeValidationsFromContext = function _ValidatorItem_takeValidationsFromContext(val) {
return val.ctx == undefined ? false
: typeof val.ctx == "function"
? val.ctx(this.validator.context)
: Object.keys(val.ctx).every(key => this.validator.context[key] == val.ctx[key]);
}, _ValidatorItem_doValidationsWithContext = function _ValidatorItem_doValidationsWithContext() {
var _a;
(_a = __classPrivateFieldGet(this, _ValidatorItem_validationsWithContext, "f")) === null || _a === void 0 ? void 0 : _a.forEach(val => {
var _a, _b, _c, _d;
if (__classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_takeValidationsFromContext).call(this, val)) {
(_a = val.validations.validations) === null || _a === void 0 ? void 0 : _a.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtx).call(this, it));
(_b = val.validations.validationsDepend) === null || _b === void 0 ? void 0 : _b.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtx).call(this, it));
(_c = val.validations.validationsCtx) === null || _c === void 0 ? void 0 : _c.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtx).call(this, it));
(_d = val.validations.validationsDependCtx) === null || _d === void 0 ? void 0 : _d.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtx).call(this, it));
}
});
}, _ValidatorItem_doValidationsWithContextAsync = async function _ValidatorItem_doValidationsWithContextAsync() {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (__classPrivateFieldGet(this, _ValidatorItem_validationsWithContext, "f")) {
for (let val of __classPrivateFieldGet(this, _ValidatorItem_validationsWithContext, "f")) {
if (__classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_takeValidationsFromContext).call(this, val)) {
(_a = val.validations.validations) === null || _a === void 0 ? void 0 : _a.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidations).call(this, it));
(_b = val.validations.validationsDepend) === null || _b === void 0 ? void 0 : _b.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidations).call(this, it));
(_c = val.validations.validationsCtx) === null || _c === void 0 ? void 0 : _c.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtx).call(this, it));
(_d = val.validations.validationsDependCtx) === null || _d === void 0 ? void 0 : _d.forEach(it => __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtx).call(this, it));
await Promise.all([
...(((_e = val.validations.validationsAsync) === null || _e === void 0 ? void 0 : _e.map(async (it) => await __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsAsync).call(this, it))) || []),
...(((_f = val.validations.validationsDependAsync) === null || _f === void 0 ? void 0 : _f.map(async (it) => await __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsAsync).call(this, it))) || []),
...(((_g = val.validations.validationsCtxAsync) === null || _g === void 0 ? void 0 : _g.map(async (it) => await __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtxAsync).call(this, it))) || []),
...(((_h = val.validations.validationsDependCtxAsync) === null || _h === void 0 ? void 0 : _h.map(async (it) => await __classPrivateFieldGet(this, _ValidatorItem_instances, "m", _ValidatorItem_doValidationsCtxAsync).call(this, it))) || []),
]);
}
}
}
};
class BshValidationError extends BshgError {
constructor(results) {
super();
this.results = results;
}
}
class BshBatchValidationError extends BshgError {
constructor(results) {
super();
this.results = results;
}
}
var _Validator_instances, _Validator_id, _Validator_options, _Validator_getter, _Validator_items, _Validator_nested, _Validator_ready, _Validator_validatorItems_get, _Validator_nestedValues_get, _Validator_info, _Validator_warn;
class Validator {
constructor() {
_Validator_instances.add(this);
_Validator_id.set(this, Object.getPrototypeOf(this).constructor.name);
_Validator_options.set(this, options);
_Validator_getter.set(this, void 0);
_Validator_items.set(this, void 0);
_Validator_nested.set(this, void 0);
// TODO: show the status in the results collections
this.status = {};
}
config(config) {
if (__classPrivateFieldGet(this, _Validator_getter, "f") != undefined && __classPrivateFieldGet(this, _Validator_getter, "f").call(this) == undefined)
throw new BshgError(__classPrivateFieldGet(this, _Validator_id, "f"), `The Object is undefined! We can not create a validator for undefined object.`);
if (config.id)
__classPrivateFieldSet(this, _Validator_id, config.id, "f");
if (config.items) {
const fields = {};
for (const key in config.items) {
if (!Object.prototype.hasOwnProperty.call(config.items, key))
continue;
const item = new ValidatorItem();
item.container = () => __classPrivateFieldGet(this, _Validator_getter, "f").call(this);
item.get = () => __classPrivateFieldGet(this, _Validator_getter, "f").call(this)[key];
item.set = (value) => (__classPrivateFieldGet(this, _Validator_getter, "f").call(this)[key] = value);
item.name = key;
item.setValidations(config.items[key]);
item.validator = this;
fields[key] = item;
}
__classPrivateFieldSet(this, _Validator_items, fields, "f");
}
if (config.nested) {
for (const key in config.nested) {
if (!Object.prototype.hasOwnProperty.call(config.nested, key))
continue;
const nested = config.nested[key];
if (nested == undefined)
continue;
__classPrivateFieldSet(nested, _Validator_getter, () => __classPrivateFieldGet(this, _Validator_getter, "f").call(this)[key], "f");
// @ts-ignore
nested.status.field = key;
this.nested[key] = nested;
}
}
return this;
}
get nested() {
if (!__classPrivateFieldGet(this, _Validator_nested, "f"))
__classPrivateFieldSet(this, _Validator_nested, {}, "f");
return __classPrivateFieldGet(this, _Validator_nested, "f");
}
get items() {
return __classPrivateFieldGet(this, _Validator_items, "f") ? __classPrivateFieldGet(this, _Validator_items, "f") : {};
}
options(value) {
__classPrivateFieldSet(this, _Validator_options, { ...__classPrivateFieldGet(this, _Validator_options, "f"), ...value }, "f");
return this;
}
allGood() {
const filtered = __classPrivateFieldGet(this, _Validator_instances, "a", _Validator_validatorItems_get).filter(it => it.valid != undefined); /* filter out the none validated items */
if (filtered.length == 0)
return this.status.valid != undefined && this.status.valid; // no validation are applied
const result = filtered.every((it) => it.valid);
this.status.valid = result;
this.status.message = result ? undefined : "invalid";
return result;
}
applyAll() {
__classPrivateFieldGet(this, _Validator_instances, "a", _Validator_validatorItems_get).forEach((it) => it.validate());
}
async applyAllAsync() {
await Promise.all(__classPrivateFieldGet(this, _Validator_instances, "a", _Validator_validatorItems_get).map(async (it) => await it.validateAsync()));
}
reset() {
const validators = [this, ...__classPrivateFieldGet(this, _Validator_instances, "a", _Validator_nestedValues_get)];
validators.forEach((it) => __classPrivateFieldGet(it, _Validator_instances, "a", _Validator_validatorItems_get).forEach((it) => it.reset()));
}
init(getter) {
__classPrivateFieldSet(this, _Validator_getter, getter, "f");
return this;
}
///////////////////////////////////////////////////
///////////// CONTEXT /////////////////////////////
///////////////////////////////////////////////////
withContext(context) {
this.context = context;
return this;
}
///////////////////////////////////////////////////
///////////// ERRORS GENERATORS ///////////////////
///////////////////////////////////////////////////
generateErrorsAsObject() {
var _a;
const result = {};
if (__classPrivateFieldGet(this, _Validator_instances, "a", _Validator_validatorItems_get).length > 0) {
const simple = __classPrivateFieldGet(this, _Validator_instances, "a", _Validator_validatorItems_get)
.filter(it => it && !it.valid)
.map((it) => {
return {
field: it.name,
message: it.message,
valid: false,
value: it.get(),
};
});
if (simple.length > 0)
result.items = simple;
}
if (__classPrivateFieldGet(this, _Validator_nested, "f")) {
const nested = {};
for (let key in __classPrivateFieldGet(this, _Validator_nested, "f")) {
if (__classPrivateFieldGet(this, _Validator_nested, "f")[key] != undefined) {
// @ts-ignore
nested[key] = (_a = __classPrivateFieldGet(this, _Validator_nested, "f")[key]) === null || _a === void 0 ? void 0 : _a.generateErrorsAsObject();
}
}
if (Object.keys(nested).length > 0)
result.nested = nested;
}
return result;
}
generateErrorsAsArray() {
var _a;
const result = {};
if (__classPrivateFieldGet(this, _Validator_instances, "a", _Validator_validatorItems_get).length > 0) {
const simple = __classPrivateFieldGet(this, _Validator_instances, "a", _Validator_validatorItems_get)
.filter((it) => it && !it.valid)
.map((it) => {
return {
field: it.name,
message: it.message,
valid: false,
value: it.get(),
};
});
if (simple.length > 0)
result.items = simple;
}
if (__classPrivateFieldGet(this, _Validator_nested, "f")) {
const nested = [];
for (let key in __classPrivateFieldGet(this, _Validator_nested, "f")) {
const error = {};
error.field = key;
error.result = (_a = __classPrivateFieldGet(this, _Validator_nested, "f")[key]) === null || _a === void 0 ? void 0 : _a.generateErrorsAsArray();
nested.push(error);
}
if (nested.length > 0)
result.nested = nested;
}
return result;
}
generateErrors() {
if (__classPrivateFieldGet(this, _Validator_options, "f").resultsType == "array")
return this.generateErrorsAsArray();
else
return this.generateErrorsAsObject();
}
///////////////////////////////////////////////////
///////////// SINGLE VALIDATIONS //////////////////
///////////////////////////////////////////////////
validate(data) {
if (data) {
__classPrivateFieldSet(this, _Validator_getter, () => data, "f");
}
const validators = [this, ...Object.values(this.nested)];
validators.forEach((it) => {
if (__classPrivateFieldGet(it, _Validator_instances, "m", _Validator_ready).call(it))
it.applyAll();
});
const isValid = validators.every((it) => it.allGood());
__classPrivateFieldGet(this, _Validator_instances, "m", _Validator_info).call(this, `validation result `, isValid);
return isValid;
}
async validateAsync(data) {
if (data) {
__classPrivateFieldSet(this, _Validator_getter, () => data, "f");
}
const validators = [this, ...Object.values(this.nested)];
await Promise.all(validators.map(async (it) => {
if (__classPrivateFieldGet(it, _Validator_instances, "m", _Validator_ready).call(it))
await it.applyAllAsync();
}));
const isValid = validators.every((it) => it.allGood());
__classPrivateFieldGet(this, _Validator_instances, "m", _Validator_info).call(this, `validation result `, isValid);
return isValid;
}
validateInfo(data) {
if (this.validate(data))
return { success: true };
else {
const results = this.generateErrors();
__classPrivateFieldGet(this, _Validator_instances, "m", _Validator_info).call(this, results);
return { success: false, results };
}
}
async validateInfoAsync(data) {
const res = await this.validateAsync(data);
if (res)
return { success: true };
else {
const results = this.generateErrors();
__classPrivateFieldGet(this, _Validator_instances, "m", _Validator_info).call(this, results);
return { success: false, results };
}
}
validateThrow(data) {
if (!this.validate(data)) {
const results = this.generateErrors();
__classPrivateFieldGet(this, _Validator_instances, "m", _Validator_info).call(this, results);
throw new BshValidationError(results);
}
}
async validateThrowAsync(data) {
const res = await this.validateAsync(data);
if (!res) {
const results = this.generateErrors();
__classPrivateFieldGet(this, _Validator_instances, "m", _Validator_info).call(this, results);
throw new BshValidationError(results);
}
}
///////////////////////////////////////////////////
///////////// BATCH VALIDATIONS ///////////////////
///////////////////////////////////////////////////
batchValidate(...data) {
const results = [];
data === null || data === void 0 ? void 0 : data.forEach(it => {
results.push(this.init(() => it).validateInfo());
});
return { success: results.every(it => it.success), results };
}
async batchValidateAsync(...data) {
const results = [];
// TODO: Do the validations in the same time for all items,
// to reduce the validation duration
// if it is possible?
for (let it of data) {
const validatorResultInfo = await this.init(() => it).validateInfoAsync();
results.push(validatorResultInfo);
}
return { success: results.every(it => it.success), results };
}
batchValidateThrow(...data) {
const batchResult = this.batchValidate(...data);
if (!batchResult.success)
throw new BshBatchValidationError(batchResult.results);
}
async batchValidateThrowAsync(...data) {
const batchResult = await this.batchValidateAsync(...data);
if (!batchResult.success)
throw new BshBatchValidationError(batchResult.results);
}
///////////////////////////////////////////////////
///////////// IMPORT METHOD ///////////////////////
///////////////////////////////////////////////////
import(results) {
var _a;
if (__classPrivateFieldGet(this, _Validator_items, "f") != undefined) {
(_a = results.items) === null || _a === void 0 ? void 0 : _a.forEach(it => {
const validatorItem = __classPrivateFieldGet(this, _Validator_items, "f")[it.field];
if (validatorItem == undefined) {
__classPrivateFieldGet(this, _Validator_instances, "m", _Validator_warn).call(this, `Unknown validatorItem '${it.field}' in ${__classPrivateFieldGet(this, _Validator_id, "f")}!\nIt Will be ignored!`);
}
else {
validatorItem.valid = it.valid;
validatorItem.message = it.message;
// TODO: add these logs to separate file to let the code source clean
if (__classPrivateFieldGet(this, _Validator_getter, "f") == undefined)
__classPrivateFieldGet(this, _Validator_instances, "m", _Validator_warn).call(this, `if the value of '${it.field}' value is modified, the change will be ignored unless the \`.init()\` method is used. To ensure the update is applied, please use \`.init()\` to apply the changes correctly.`);
else
validatorItem.set(it.value);
}
});
}
else if (results.items) {
__classPrivateFieldGet(this, _Validator_instances, "m", _Validator_warn).call(this, `No Simple Fields Found in ${__classPrivateFieldGet(this, _Validator_id, "f")}`);
}
if (__classPrivateFieldGet(this, _Validator_nested, "f") != undefined) {
if (__classPrivateFieldGet(this, _Validator_options, "f").resultsType == "object") {
const nested = results.nested;
for (const key in nested) {