perfect-validator
Version:
A TypeScript-based validation library that supports both static and dynamic validation with serializable models.
3 lines (2 loc) • 34.6 kB
JavaScript
"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function t(e,t,r,n,i,a,o){try{var s=e[a](o),u=s.value}catch(e){return void r(e)}s.done?t(u):Promise.resolve(u).then(n,i)}function r(e){return function(){var r=this,n=arguments;return new Promise((function(i,a){var o=e.apply(r,n);function s(e){t(o,i,a,s,u,"next",e)}function u(e){t(o,i,a,s,u,"throw",e)}s(void 0)}))}}function n(e,t,r){if(o())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var i=new(e.bind.apply(e,n));return r&&u(i,r.prototype),i}function i(t,r){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,r){if(t){if("string"==typeof t)return e(t,r);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?e(t,r):void 0}}(t))||r&&t&&"number"==typeof t.length){n&&(t=n);var i=0;return function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function a(){return(a=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(null,arguments)}function o(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(o=function(){return!!e})()}function s(){s=function(){return t};var e,t={},r=Object.prototype,n=r.hasOwnProperty,i=Object.defineProperty||function(e,t,r){e[t]=r.value},a="function"==typeof Symbol?Symbol:{},o=a.iterator||"@@iterator",u=a.asyncIterator||"@@asyncIterator",l=a.toStringTag||"@@toStringTag";function c(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,r){return e[t]=r}}function d(e,t,r,n){var a=Object.create((t&&t.prototype instanceof y?t:y).prototype),o=new j(n||[]);return i(a,"_invoke",{value:O(e,r,o)}),a}function f(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}t.wrap=d;var p="suspendedStart",h="executing",m="completed",v={};function y(){}function g(){}function w(){}var b={};c(b,o,(function(){return this}));var x=Object.getPrototypeOf,E=x&&x(x(R([])));E&&E!==r&&n.call(E,o)&&(b=E);var M=w.prototype=y.prototype=Object.create(b);function A(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function L(e,t){function r(i,a,o,s){var u=f(e[i],e,a);if("throw"!==u.type){var l=u.arg,c=l.value;return c&&"object"==typeof c&&n.call(c,"__await")?t.resolve(c.__await).then((function(e){r("next",e,o,s)}),(function(e){r("throw",e,o,s)})):t.resolve(c).then((function(e){l.value=e,o(l)}),(function(e){return r("throw",e,o,s)}))}s(u.arg)}var a;i(this,"_invoke",{value:function(e,n){function i(){return new t((function(t,i){r(e,n,t,i)}))}return a=a?a.then(i,i):i()}})}function O(t,r,n){var i=p;return function(a,o){if(i===h)throw Error("Generator is already running");if(i===m){if("throw"===a)throw o;return{value:e,done:!0}}for(n.method=a,n.arg=o;;){var s=n.delegate;if(s){var u=k(s,n);if(u){if(u===v)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(i===p)throw i=m,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);i=h;var l=f(t,r,n);if("normal"===l.type){if(i=n.done?m:"suspendedYield",l.arg===v)continue;return{value:l.arg,done:n.done}}"throw"===l.type&&(i=m,n.method="throw",n.arg=l.arg)}}}function k(t,r){var n=r.method,i=t.iterator[n];if(i===e)return r.delegate=null,"throw"===n&&t.iterator.return&&(r.method="return",r.arg=e,k(t,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),v;var a=f(i,t.iterator,r.arg);if("throw"===a.type)return r.method="throw",r.arg=a.arg,r.delegate=null,v;var o=a.arg;return o?o.done?(r[t.resultName]=o.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=e),r.delegate=null,v):o:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,v)}function V(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function I(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function j(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(V,this),this.reset(!0)}function R(t){if(t||""===t){var r=t[o];if(r)return r.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,a=function r(){for(;++i<t.length;)if(n.call(t,i))return r.value=t[i],r.done=!1,r;return r.value=e,r.done=!0,r};return a.next=a}}throw new TypeError(typeof t+" is not iterable")}return g.prototype=w,i(M,"constructor",{value:w,configurable:!0}),i(w,"constructor",{value:g,configurable:!0}),g.displayName=c(w,l,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===g||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,w):(e.__proto__=w,c(e,l,"GeneratorFunction")),e.prototype=Object.create(M),e},t.awrap=function(e){return{__await:e}},A(L.prototype),c(L.prototype,u,(function(){return this})),t.AsyncIterator=L,t.async=function(e,r,n,i,a){void 0===a&&(a=Promise);var o=new L(d(e,r,n,i),a);return t.isGeneratorFunction(r)?o:o.next().then((function(e){return e.done?e.value:o.next()}))},A(M),c(M,l,"Generator"),c(M,o,(function(){return this})),c(M,"toString",(function(){return"[object Generator]"})),t.keys=function(e){var t=Object(e),r=[];for(var n in t)r.push(n);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},t.values=R,j.prototype={constructor:j,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(I),!t)for(var r in this)"t"===r.charAt(0)&&n.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=e)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var r=this;function i(n,i){return s.type="throw",s.arg=t,r.next=n,i&&(r.method="next",r.arg=e),!!i}for(var a=this.tryEntries.length-1;a>=0;--a){var o=this.tryEntries[a],s=o.completion;if("root"===o.tryLoc)return i("end");if(o.tryLoc<=this.prev){var u=n.call(o,"catchLoc"),l=n.call(o,"finallyLoc");if(u&&l){if(this.prev<o.catchLoc)return i(o.catchLoc,!0);if(this.prev<o.finallyLoc)return i(o.finallyLoc)}else if(u){if(this.prev<o.catchLoc)return i(o.catchLoc,!0)}else{if(!l)throw Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return i(o.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var a=i;break}}a&&("break"===e||"continue"===e)&&a.tryLoc<=t&&t<=a.finallyLoc&&(a=null);var o=a?a.completion:{};return o.type=e,o.arg=t,a?(this.method="next",this.next=a.finallyLoc,v):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),v},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),I(r),v}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;I(r)}return i}}throw Error("illegal catch attempt")},delegateYield:function(t,r,n){return this.delegate={iterator:R(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=e),v}},t}function u(e,t){return(u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}var l;Object.defineProperty(exports,"__esModule",{value:!0}),(l=exports.PerfectValidator||(exports.PerfectValidator={})).ValidationTypes={STRING:"S",NUMBER:"N",BOOLEAN:"B",LIST:"L",MAP:"M",EMAIL:"EMAIL",URL:"URL",DATE:"DATE",PHONE:"PHONE",REGEX:"REGEX"},l.DataTypeDescriptions={S:"String type - Text values with optional length and pattern constraints",N:"Number type - Numeric values with optional range constraints",B:"Boolean type - True/false values",L:"List type - Array of values with type validation",M:"Map type - Object with defined field structure",EMAIL:"Email type - Valid email address format",URL:"URL type - Valid URL format",DATE:"Date type - Valid date format",PHONE:"Phone type - Valid phone number format",REGEX:"Regex type - Custom pattern matching"};var c=["S","N","B","L","M","EMAIL","URL","DATE","PHONE","REGEX"],d={EMAIL:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z]{2,})+$/,URL:/^(https?:\/\/)([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})(:[0-9]{1,5})?(\/[^\s]*)?$/,PHONE:/^\+?[1-9]\d{0,2}[-.\s]?\(?\d{2,4}\)?[-.\s]?\d{3,4}[-.\s]?\d{3,4}$/,DATE:/^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])(?:T([01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-]([01]\d|2[0-3]):[0-5]\d)?)?$/};function f(e,t){for(var r,n=e,a=i(t.split(/\.|\[|\]/).filter(Boolean));!(r=a()).done;){var o=r.value;if(!n)return;n=/^\d+$/.test(o)?n[parseInt(o,10)]:n[o]}return n}function p(e){if("string"==typeof e)return e;var t=e.type;if(!t)return"unknown";switch(t){case"S":return"string"+(e.minLength?" (min length: "+e.minLength+")":"")+(e.maxLength?" (max length: "+e.maxLength+")":"");case"N":return"number"+(void 0!==e.min?" (min: "+e.min+")":"")+(void 0!==e.max?" (max: "+e.max+")":"")+(e.decimal?" (decimal)":"");case"EMAIL":return"email address";case"URL":return"URL";case"DATE":return"date (YYYY-MM-DD)";case"PHONE":return"phone number";case"B":return"boolean";case"L":return"array"+(e.items?" of "+p(e.items):"");case"REGEX":return"string matching pattern: "+e.pattern;default:return t}}function h(e){var t=[];return Object.entries(e).forEach((function(e){!function e(r,n){if("string"!=typeof r)if("object"==typeof r&&null!==r){var i=r;if(i.type&&!c.includes(i.type)&&t.push('Invalid type "'+i.type+'" at '+n),void 0!==i.values&&(Array.isArray(i.values)&&0!==i.values.length||t.push("Invalid values at "+n)),"N"===i.type&&(void 0!==i.min&&"number"!=typeof i.min&&t.push("Invalid min value at "+n),void 0!==i.max&&"number"!=typeof i.max&&t.push("Invalid max value at "+n),void 0!==i.min&&void 0!==i.max&&i.min>i.max&&t.push("Invalid range at "+n),void 0!==i.integer&&"boolean"!=typeof i.integer&&t.push("Invalid integer flag at "+n)),i.dependsOn&&(Array.isArray(i.dependsOn)?i.dependsOn:[i.dependsOn]).forEach((function(e,r){var i=n+".dependsOn["+r+"]";"object"==typeof e&&null!==e?(e.field||t.push("Missing field in dependency at "+i),e.condition&&"function"==typeof e.condition||t.push("Missing or invalid condition function at "+i),e.validate&&"function"==typeof e.validate||t.push("Missing or invalid validate function at "+i)):t.push("Invalid dependency definition at "+i)})),i.fields){if("object"!=typeof i.fields||null===i.fields)return void t.push("Invalid fields definition at "+n);Object.entries(i.fields).forEach((function(t){var r=t[0];e(t[1],n?n+"."+r:r)}))}i.items&&e(i.items,n+".items")}else t.push("Invalid field definition at "+n);else c.includes(r)||t.push('Invalid type "'+r+'" at '+n)}(e[1],e[0])})),{isValid:0===t.length,errors:t.length>0?t:null}}function m(e,t,r,n){void 0===r&&(r=!1),void 0===n&&(n="");var o=[],s=function(e,t){var r=a({},e);return Object.entries(t).forEach((function(e){var t=e[0],n=e[1];void 0===r[t]&&function(e){return"object"==typeof e&&null!==e}(n)&&!n.optional&&(r[t]=function(e){if(void 0!==e.default)return"function"==typeof e.default?e.default():JSON.parse(JSON.stringify(e.default))}(n))})),r}(e,t);if("object"==typeof s&&null!==s&&!r){var u=Object.keys(t);Object.keys(s).forEach((function(e){u.includes(e)||o.push({field:n?n+"."+e:e,message:"Unexpected field '"+e+"' found in data."})}))}return o.length>0?{isValid:!1,errors:o}:(Object.entries(t).forEach((function(e){var t=e[0],r=e[1];!function e(t,r,a){if(void 0!==t){var u="string"==typeof r?r:r.type;if(u){var l,c=(l=u).startsWith("L<")&&l.endsWith(">")?{isArray:!0,elementType:l.slice(2,-1)}:{isArray:!1,elementType:l},h=c.elementType;if(c.isArray)return Array.isArray(t)?void t.forEach((function(t,r){e(t,h,a+"["+r+"]")})):void o.push({field:a,message:"Expected array of "+h+", got "+typeof t});if(function(e,t,r){switch(t){case"S":return"string"==typeof e;case"N":return"number"==typeof e&&!isNaN(e);case"B":return"boolean"==typeof e;case"L":return Array.isArray(e);case"M":return"object"==typeof e&&null!==e&&!Array.isArray(e);case"EMAIL":return"string"==typeof e&&d.EMAIL.test(e);case"URL":return"string"==typeof e&&d.URL.test(e);case"DATE":return"string"==typeof e&&d.DATE.test(e);case"PHONE":return"string"==typeof e&&d.PHONE.test(e);case"REGEX":return"string"==typeof e&&!(null==r||!r.pattern)&&new RegExp(r.pattern).test(e);default:return!1}}(t,u,"object"==typeof r?r:void 0)){if("string"!=typeof r){if(r.values&&!r.values.includes(t)&&o.push({field:a,message:"Value must be one of: "+r.values.join(", ")}),"N"===r.type&&(void 0!==r.min&&t<r.min&&o.push({field:a,message:"Value must be >= "+r.min}),void 0!==r.max&&t>r.max&&o.push({field:a,message:"Value must be <= "+r.max}),r.integer&&!Number.isInteger(t)&&o.push({field:a,message:"Value must be an integer"}),r.decimal)){var m=t.toString().includes("."),v=Number.isInteger(t);m||v?void 0!==r.decimals&&(t.toString().split(".")[1]||"").length!==r.decimals&&o.push({field:a,message:"Value must have exactly "+r.decimals+" decimal places"}):o.push({field:a,message:"Value must be a decimal number"})}if("S"===r.type&&(void 0!==r.minLength&&t.length<r.minLength&&o.push({field:a,message:"String length must be >= "+r.minLength}),void 0!==r.maxLength&&t.length>r.maxLength&&o.push({field:a,message:"String length must be <= "+r.maxLength})),"object"==typeof r&&r.validate&&"function"==typeof r.validate)try{r.validate(t)||o.push({field:a,message:r.message||"Custom validation failed for field "+a})}catch(e){o.push({field:a,message:r.message||"Custom validation error for field "+a+": "+(e instanceof Error?e.message:"Unknown error")})}r.items&&Array.isArray(t)&&t.forEach((function(t,n){e(t,r.items,a+"["+n+"]")})),r.fields&&"object"==typeof t&&Object.entries(r.fields).forEach((function(r){var n=r[0];e(t[n],r[1],a?a+"."+n:n)})),"object"==typeof r&&r.dependsOn&&(Array.isArray(r.dependsOn)?r.dependsOn:[r.dependsOn]).forEach((function(e,r){var n=a.substring(0,a.lastIndexOf(".")),i=e.field.includes(".")?e.field:n?n+"."+e.field:e.field,u=f(s,i);e.condition(u)&&(e.validate(t,u,s)||o.push({field:a,message:e.message}))}))}}else o.push({field:a,message:"Invalid type, expected "+p(r)+", got "+typeof t})}}else{var y=!1;if("object"==typeof r&&r.dependsOn)for(var g,w=i(Array.isArray(r.dependsOn)?r.dependsOn:[r.dependsOn]);!(g=w()).done;){var b=g.value,x=b.field.includes(".")?b.field:n?n+"."+b.field:b.field,E=f(s,x);if(b.condition(E)&&b.isRequired)return y=!0,void o.push({field:a,message:b.message||"Field is required based on dependencies"})}if("object"==typeof r&&r.optional&&!y)return;y||o.push({field:a,message:"Field is required"})}}(t.includes(".")||t.includes("[]")?f(s,t):s[t],r,n?n+"."+t:t)})),o.length>0?{isValid:!1,errors:o}:{isValid:!0,data:s})}var v={S:{type:"String",description:"Text values with optional length and pattern constraints",params:[{name:"minLength",type:"number",description:"Minimum length of the string"},{name:"maxLength",type:"number",description:"Maximum length of the string"},{name:"values",type:"string[]",description:"Array of allowed values"},{name:"optional",type:"boolean",description:"Whether the field is optional"},{name:"default",type:"string",description:"Default value if field is not provided"}]},N:{type:"Number",description:"Numeric values with optional range constraints",params:[{name:"min",type:"number",description:"Minimum allowed value"},{name:"max",type:"number",description:"Maximum allowed value"},{name:"integer",type:"boolean",description:"Whether the number must be an integer"},{name:"decimal",type:"boolean",description:"can be decimal or an integer"},{name:"optional",type:"boolean",description:"Whether the field is optional"},{name:"values",type:"number[]",description:"Array of allowed values"},{name:"default",type:"number",description:"Default value if field is not provided"}]},B:{type:"Boolean",description:"True/false values",params:[{name:"optional",type:"boolean",description:"Whether the field is optional"},{name:"default",type:"boolean",description:"Default value if field is not provided"}]},L:{type:"Array",description:"Array of values with type validation",params:[{name:"items",type:"ValidationRule | string",description:"Validation rule for array items",required:!0},{name:"minLength",type:"number",description:"Minimum array length"},{name:"maxLength",type:"number",description:"Maximum array length"},{name:"values",type:"any[]",description:"Array of allowed values"},{name:"optional",type:"boolean",description:"Whether the field is optional"}]},M:{type:"Map",description:"Object with defined field structure",params:[{name:"fields",type:"Record<string, ValidationRule | string>",description:"Validation rules for object fields",required:!0},{name:"optional",type:"boolean",description:"Whether the field is optional"}]},EMAIL:{type:"Email",description:"Valid email address format",params:[{name:"optional",type:"boolean",description:"Whether the field is optional"},{name:"default",type:"string",description:"Default value if field is not provided"}]},URL:{type:"URL",description:"Valid URL format",params:[{name:"optional",type:"boolean",description:"Whether the field is optional"},{name:"default",type:"string",description:"Default value if field is not provided"}]},DATE:{type:"Date",description:"Valid date format",params:[{name:"optional",type:"boolean",description:"Whether the field is optional"},{name:"default",type:"string",description:"Default value if field is not provided"}]},PHONE:{type:"Phone",description:"Valid phone number format",params:[{name:"optional",type:"boolean",description:"Whether the field is optional"},{name:"default",type:"string",description:"Default value if field is not provided"}]},REGEX:{type:"Regex",description:"Custom pattern matching",params:[{name:"pattern",type:"string",description:"Regular expression pattern",required:!0},{name:"optional",type:"boolean",description:"Whether the field is optional"}]}},y=function(e){try{return JSON.stringify(function e(t){if("function"==typeof t)return{__type:"function",code:(r=t).toString().replace(/\n/g," ").trim(),original:r.toString().replace(/\n/g," ").trim()};var r;if(Array.isArray(t))return t.map((function(t){return e(t)}));if(t&&"object"==typeof t){for(var n={},i=0,a=Object.entries(t);i<a.length;i++){var o=a[i];n[o[0]]=e(o[1])}return n}return t}(e))}catch(e){if(e instanceof Error)throw new Error("Failed to serialize model: "+e.message);throw new Error("Failed to serialize model: Unknown error")}},g=function(e){try{var t,r=function e(t){if(t&&"function"===t.__type&&t.code)try{return function(e){try{var t=("object"==typeof e?e.original||e.code:e).trim().replace(/^function\s*[a-zA-Z0-9_]*\s*/,"");if((t=t.replace(/function anonymous/,"").replace(/\s+/g," ").trim()).includes("=>")){var r=t.match(/^\s*(?:\((.*?)\)|([^=>\s]+))\s*=>\s*\{([\s\S]*)\}\s*$/);if(r){var i=r[3];return n(Function,(r[1]||r[2]).split(",").map((function(e){return e.trim()})).concat([i.trim()]))}var a=t.match(/^\s*(?:\((.*?)\)|([^=>\s]+))\s*=>\s*(.+?)\s*$/);if(a){var o=a[3],s=a[1]||a[2],u=o.includes("\n")?o.split("\n").map((function(e){return e.trim()})).join(" "):o.trim();return n(Function,s.split(",").map((function(e){return e.trim()})).concat(["return "+u+";"]))}}var l=t.match(/^\s*\((.*?)\)\s*\{([\s\S]*)\}\s*$/);if(l){var c=l[2];return n(Function,l[1].split(",").map((function(e){return e.trim()})).concat([c.trim()]))}throw new Error("Invalid function format")}catch(e){if(e instanceof Error)throw new Error("Failed to deserialize function: "+e.message);throw new Error("Failed to deserialize function: Unknown error")}}(t.original||t.code)}catch(e){throw e}if(Array.isArray(t))return t.map((function(t){return e(t)}));if(t&&"object"==typeof t){for(var r={},i=function(){var t=o[a],n=t[0],i=t[1];if("dependsOn"===n){var s=function(e){return"object"==typeof e&&null!==e&&"field"in e};if(Array.isArray(i))r[n]=i.map((function(t){if(!s(t))throw new Error("Invalid dependency object structure");return{field:t.field,message:t.message,condition:t.condition?e(t.condition):void 0,validate:t.validate?e(t.validate):void 0}}));else{if(!s(i))throw new Error("Invalid dependency structure");r[n]={field:i.field,message:i.message,condition:i.condition?e(i.condition):void 0,validate:i.validate?e(i.validate):void 0}}}else r[n]=e(i)},a=0,o=Object.entries(t);a<o.length;a++)i();return r}return t}(JSON.parse(e)),i=h(r);if(!i.isValid)throw new Error("Invalid model after deserialization: "+(null==(t=i.errors)?void 0:t.join(", ")));return r}catch(e){throw e}};function w(e){var t=v[e];if(!t||null==t)throw new Error("Invalid validation type: "+e);return t}var b={user:{type:"M",fields:{name:{type:"S",minLength:2},age:{type:"N",min:13},email:{type:"EMAIL"},subscription:{type:"M",fields:{plan:{type:"S",values:["FREE","BASIC","PREMIUM"],dependsOn:{field:"user.age",condition:function(e){return e<18},validate:function(e){return"PREMIUM"!==e},message:"Users under 18 cannot have PREMIUM plan"}},features:{type:"L",items:{type:"S"},dependsOn:{field:"user.subscription.plan",condition:function(e){return"FREE"===e},validate:function(e){return e.length<=3},message:"FREE plan can only have up to 3 features"}},paymentMethod:{type:"S",values:["CREDIT_CARD","DEBIT_CARD","PAYPAL"],dependsOn:[{field:"user.age",condition:function(e){return e<18},validate:function(e){return"DEBIT_CARD"===e},message:"Users under 18 can only use debit cards"},{field:"user.subscription.plan",condition:function(e){return"PREMIUM"===e},validate:function(e){return"CREDIT_CARD"===e},message:"PREMIUM plan requires credit card payment"}]}}}}}},x=[{name:"Valid adult premium user",data:{user:{name:"John Doe",age:25,email:"john@example.com",subscription:{plan:"PREMIUM",features:["feature1","feature2","feature3","feature4"],paymentMethod:"CREDIT_CARD"}}}},{name:"Valid teen user with free plan",data:{user:{name:"Teen User",age:15,email:"teen@example.com",subscription:{plan:"FREE",features:["feature1","feature2"],paymentMethod:"DEBIT_CARD"}}}},{name:"Invalid - Teen trying premium plan",data:{user:{name:"Teen Premium",age:16,email:"teen.premium@example.com",subscription:{plan:"PREMIUM",features:["feature1","feature2"],paymentMethod:"DEBIT_CARD"}}}},{name:"Invalid - Free plan with too many features",data:{user:{name:"Free User",age:20,email:"free@example.com",subscription:{plan:"FREE",features:["feature1","feature2","feature3","feature4"],paymentMethod:"PAYPAL"}}}}],E=function(){function e(e){this.storage=e}var t=e.prototype;return t.validateStatic=function(e,t,r){var n=this.validateModel(t);return!n.isValid&&n.errors?{isValid:!1,errors:n.errors.map((function(e){return{field:"model",message:e}}))}:m(e,t,r)},e.getInstance=function(t){if(!e.instance)try{e.instance=new e(t)}catch(e){if(e instanceof Error)throw new Error("Failed to create PV instance: "+e.message);throw new Error("Failed to create PV instance: Unknown error")}return e.instance},t.validateDynamic=function(){var e=r(s().mark((function e(t,r,n,i,a){var o,u,l,c;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.storage){e.next=2;break}throw new Error("Storage is required for dynamic validation");case 2:if(e.prev=2,void 0===n){e.next=12;break}return e.next=6,this.storage.getModelVersion(r,n,i);case 6:if(u=e.sent){e.next=9;break}throw new Error("Model "+r+" version "+n+" not found");case 9:o=u.model,e.next=18;break;case 12:return e.next=14,this.storage.getLatestModelVersion(r,i);case 14:if(l=e.sent){e.next=17;break}throw new Error("Model "+r+" not found");case 17:o=l.model;case 18:if(o){e.next=20;break}throw new Error("Model "+r+" not found");case 20:return c=g(o),e.abrupt("return",m(t,c,a));case 24:if(e.prev=24,e.t0=e.catch(2),!(e.t0 instanceof Error)){e.next=28;break}return e.abrupt("return",{isValid:!1,errors:[{field:"model",message:"Failed to load model: "+e.t0.message}]});case 28:return e.abrupt("return",{isValid:!1,errors:[{field:"model",message:"Failed to load model: Unknown error"}]});case 29:case"end":return e.stop()}}),e,this,[[2,24]])})));return function(t,r,n,i,a){return e.apply(this,arguments)}}(),t.storeModel=function(){var e=r(s().mark((function e(t,r,n,i){var a,o,u,l,c;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,this.storage){e.next=3;break}throw new Error("Storage is required for model storage");case 3:if((a=this.validateModel(r)).isValid){e.next=6;break}throw new Error("Model validation failed: "+(null==(o=a.errors)?void 0:o.join(", ")));case 6:return e.next=8,this.serializeModelSafely(r);case 8:return u=e.sent,e.next=11,this.deserializeAndValidate(u);case 11:if(void 0===n){e.next=17;break}return e.next=15,this.storage.storeModelVersion(t,u,n,i);case 15:e.next=23;break;case 17:return e.next=19,this.storage.getLatestModelVersion(t,i);case 19:return c=(l=e.sent)?l.version+1:1,e.next=23,this.storage.storeModelVersion(t,u,c,i);case 23:return e.abrupt("return",{isValid:!0,errors:null});case 26:if(e.prev=26,e.t0=e.catch(0),!(e.t0 instanceof Error)){e.next=30;break}return e.abrupt("return",{isValid:!1,errors:["Failed to store model: "+e.t0.message]});case 30:return e.abrupt("return",{isValid:!1,errors:["Failed to store model: Unknown error"]});case 31:case"end":return e.stop()}}),e,this,[[0,26]])})));return function(t,r,n,i){return e.apply(this,arguments)}}(),t.validateModel=function(e){return h(e)},t.serializeModelSafely=function(){var e=r(s().mark((function e(t){return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.abrupt("return",y(t));case 4:if(e.prev=4,e.t0=e.catch(0),!(e.t0 instanceof Error)){e.next=8;break}throw new Error("Model serialization failed: "+e.t0.message);case 8:throw new Error("Model serialization failed: Unknown error");case 9:case"end":return e.stop()}}),e,null,[[0,4]])})));return function(t){return e.apply(this,arguments)}}(),t.deserializeAndValidate=function(){var e=r(s().mark((function e(t){var r,n,i;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,r=g(t),(n=h(r)).isValid){e.next=5;break}throw new Error("Invalid model after deserialization: "+((null==(i=n.errors)?void 0:i.join(", "))||"Unknown error"));case 5:return e.abrupt("return",r);case 8:if(e.prev=8,e.t0=e.catch(0),!(e.t0 instanceof Error)){e.next=12;break}throw new Error("Model deserialization failed: "+e.t0.message);case 12:throw new Error("Model deserialization failed: Unknown error");case 13:case"end":return e.stop()}}),e,null,[[0,8]])})));return function(t){return e.apply(this,arguments)}}(),t.getDataTypes=function(){return exports.PerfectValidator.ValidationTypes},t.getModelExample=function(){return b},t.getDataExample=function(){return x},t.getValidationTypeParams=function(e){try{return w(e)}catch(e){if(e instanceof Error)throw new Error("Failed to get validation type params: "+e.message);throw new Error("Failed to get validation type params: Unknown error")}},t.getLatestModelVersion=function(){var e=r(s().mark((function e(t,r){var n;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.storage){e.next=2;break}throw new Error("Storage is required");case 2:return e.next=4,this.storage.getLatestModelVersion(t,r);case 4:if(n=e.sent){e.next=7;break}throw new Error("Model "+t+" not found");case 7:return e.abrupt("return",g(n.model));case 8:case"end":return e.stop()}}),e,this)})));return function(t,r){return e.apply(this,arguments)}}(),t.getModelVersion=function(){var e=r(s().mark((function e(t,r,n){var i;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.storage){e.next=2;break}throw new Error("Storage is required");case 2:return e.prev=2,e.next=5,this.storage.getModelVersion(t,r,n);case 5:if(i=e.sent){e.next=8;break}throw new Error("Model "+t+" version "+r+" not found");case 8:return e.abrupt("return",g(i.model));case 11:if(e.prev=11,e.t0=e.catch(2),!(e.t0 instanceof Error)){e.next=15;break}throw new Error("Failed to get model version: "+e.t0.message);case 15:throw new Error("Failed to get model version: Unknown error");case 16:case"end":return e.stop()}}),e,this,[[2,11]])})));return function(t,r,n){return e.apply(this,arguments)}}(),t.listModelVersions=function(){var e=r(s().mark((function e(t,r){return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.storage){e.next=2;break}throw new Error("Storage is required");case 2:return e.prev=2,e.next=5,this.storage.listModelVersions(t,r);case 5:return e.abrupt("return",e.sent);case 8:if(e.prev=8,e.t0=e.catch(2),!(e.t0 instanceof Error)){e.next=12;break}throw new Error("Failed to list model versions: "+e.t0.message);case 12:throw new Error("Failed to list model versions: Unknown error");case 13:case"end":return e.stop()}}),e,this,[[2,8]])})));return function(t,r){return e.apply(this,arguments)}}(),e}();E.instance=null;var M=function(){function e(e){this.defaultCollection="validation_models",this.db=e,this.checkRequiredIndexes()}var t=e.prototype;return t.checkRequiredIndexes=function(){var e=r(s().mark((function e(){var t;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,t=this.getCollection(),e.next=4,t.indexInformation();case 4:Object.keys(e.sent).length<=1&&(console.warn("================================================================="),console.warn("WARNING: No custom indexes found on validation_models collection"),console.warn("Suggested indexes:"),console.warn("1. { name: 1, version: 1 } with unique constraint"),console.warn("2. { name: 1, version: -1 } for latest version queries"),console.warn("=================================================================")),e.next=12;break;case 9:e.prev=9,e.t0=e.catch(0),console.error("Failed to check indexes:",e.t0);case 12:case"end":return e.stop()}}),e,this,[[0,9]])})));return function(){return e.apply(this,arguments)}}(),t.getCollection=function(e){return this.db.collection(e||this.defaultCollection)},t.getModel=function(){var e=r(s().mark((function e(t){var r;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getCollection().findOne({name:t},{sort:{version:-1}});case 2:return e.abrupt("return",(r=e.sent)?r.model:null);case 4:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),t.storeModelVersion=function(){var e=r(s().mark((function e(t,r,n,i){var a;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=this.getCollection(i),e.next=3,a.findOne({name:t,version:n});case 3:if(!e.sent){e.next=6;break}throw new Error("Version "+n+" already exists for model "+t);case 6:return e.next=8,a.insertOne({name:t,version:n,model:r,createdAt:new Date});case 8:case"end":return e.stop()}}),e,this)})));return function(t,r,n,i){return e.apply(this,arguments)}}(),t.getModelVersion=function(){var e=r(s().mark((function e(t,r,n){var i;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getCollection(n).findOne({name:t,version:r});case 2:if((i=e.sent)&&i.model&&0!==Object.keys(i.model).length){e.next=5;break}return e.abrupt("return",null);case 5:return e.abrupt("return",{version:i.version,model:i.model,createdAt:i.createdAt});case 6:case"end":return e.stop()}}),e,this)})));return function(t,r,n){return e.apply(this,arguments)}}(),t.getLatestModelVersion=function(){var e=r(s().mark((function e(t,r){var n,i;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.getCollection(r).find({name:t}).sort({version:-1}).limit(1),e.next=3,n.hasNext();case 3:if(!e.sent){e.next=9;break}return e.next=6,n.next();case 6:if(!((i=e.sent)&&i.model&&Object.keys(i.model).length>0)){e.next=9;break}return e.abrupt("return",{version:i.version,model:i.model,createdAt:i.createdAt});case 9:return e.abrupt("return",null);case 10:case"end":return e.stop()}}),e,this)})));return function(t,r){return e.apply(this,arguments)}}(),t.listModelVersions=function(){var e=r(s().mark((function e(t,r){var n,i;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=this.getCollection(r).find({name:t},{projection:{version:1}}).sort({version:-1}),i=[];case 2:return e.next=4,n.hasNext();case 4:if(!e.sent){e.next=11;break}return e.next=7,n.next();case 7:i.push(e.sent.version),e.next=2;break;case 11:return e.abrupt("return",i);case 12:case"end":return e.stop()}}),e,this)})));return function(t,r){return e.apply(this,arguments)}}(),t.insertModel=function(){var e=r(s().mark((function e(t,r){var n;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=y(r),e.next=3,this.storeModelVersion(t,n,1);case 3:case"end":return e.stop()}}),e,this)})));return function(t,r){return e.apply(this,arguments)}}(),t.updateModel=function(){var e=r(s().mark((function e(t,r){var n,i,a;return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=y(r),e.next=3,this.getLatestModelVersion(t);case 3:return a=(i=e.sent)?i.version+1:1,e.next=7,this.storeModelVersion(t,n,a);case 7:case"end":return e.stop()}}),e,this)})));return function(t,r){return e.apply(this,arguments)}}(),t.deleteModel=function(){var e=r(s().mark((function e(t){return s().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getCollection().deleteMany({name:t});case 2:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}(),e}();exports.BaseStorage=function(){},exports.MongoStorage=M,exports.PV=E,exports.createPV=function(e){return E.getInstance(e)},exports.deserializeValidationModel=g,exports.getValidationTypeParams=w,exports.isValidationError=function(e){return null!==e&&"object"==typeof e&&"isValid"in e&&!e.isValid},exports.serializeValidationModel=y,exports.validateAgainstModel=m,exports.validateDataModel=h;
//# sourceMappingURL=perfect-validator.cjs.production.min.js.map