@oxog/vld 2.2.5 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/README.md +242 -1125
- package/dist/chunks/errors-core-CerMg2rq.js +1 -0
- package/dist/chunks/index-CKPStM3V.js +1 -0
- package/dist/cjs/chunks/errors-core-DrydF46s.cjs +1 -0
- package/dist/cjs/chunks/index-lejEpLfv.cjs +1 -0
- package/dist/cjs/cli/bin.cjs +1 -1
- package/dist/cjs/codecs/index.cjs +1 -1
- package/dist/cjs/coercion/index.cjs +1 -1
- package/dist/cjs/compile.cjs +1 -0
- package/dist/cjs/errors.cjs +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/locales/gu.cjs +1 -0
- package/dist/cjs/locales/index.cjs +1 -1
- package/dist/cjs/locales/kn.cjs +1 -0
- package/dist/cjs/locales/ne.cjs +1 -0
- package/dist/cjs/locales/pt-BR-v4.cjs +1 -0
- package/dist/cjs/locales/sk.cjs +1 -0
- package/dist/cjs/mini.cjs +1 -1
- package/dist/cjs/v3/index.cjs +1 -1
- package/dist/cjs/v4/core/index.cjs +1 -1
- package/dist/cjs/v4/index.cjs +1 -1
- package/dist/cjs/v4/locales/index.cjs +1 -1
- package/dist/cjs/v4/mini/index.cjs +1 -1
- package/dist/cjs/v4-mini/index.cjs +1 -1
- package/dist/cjs/validators/any.cjs +1 -1
- package/dist/cjs/validators/array.cjs +1 -1
- package/dist/cjs/validators/base.cjs +1 -1
- package/dist/cjs/validators/base64.cjs +1 -1
- package/dist/cjs/validators/bigint.cjs +1 -1
- package/dist/cjs/validators/boolean.cjs +1 -1
- package/dist/cjs/validators/codec.cjs +1 -1
- package/dist/cjs/validators/custom.cjs +1 -1
- package/dist/cjs/validators/date.cjs +1 -1
- package/dist/cjs/validators/discriminated-union.cjs +1 -1
- package/dist/cjs/validators/enum.cjs +1 -1
- package/dist/cjs/validators/file.cjs +1 -1
- package/dist/cjs/validators/function.cjs +1 -1
- package/dist/cjs/validators/hex.cjs +1 -1
- package/dist/cjs/validators/index.cjs +1 -1
- package/dist/cjs/validators/intersection.cjs +1 -1
- package/dist/cjs/validators/json.cjs +1 -1
- package/dist/cjs/validators/lazy.cjs +1 -1
- package/dist/cjs/validators/literal.cjs +1 -1
- package/dist/cjs/validators/map.cjs +1 -1
- package/dist/cjs/validators/nan.cjs +1 -1
- package/dist/cjs/validators/never.cjs +1 -1
- package/dist/cjs/validators/null.cjs +1 -1
- package/dist/cjs/validators/number.cjs +1 -1
- package/dist/cjs/validators/object.cjs +1 -1
- package/dist/cjs/validators/promise.cjs +1 -1
- package/dist/cjs/validators/record.cjs +1 -1
- package/dist/cjs/validators/set.cjs +1 -1
- package/dist/cjs/validators/string-bool.cjs +1 -1
- package/dist/cjs/validators/string-formats.cjs +1 -1
- package/dist/cjs/validators/string.cjs +1 -1
- package/dist/cjs/validators/symbol.cjs +1 -1
- package/dist/cjs/validators/template-literal.cjs +1 -1
- package/dist/cjs/validators/tuple.cjs +1 -1
- package/dist/cjs/validators/uint8array.cjs +1 -1
- package/dist/cjs/validators/undefined.cjs +1 -1
- package/dist/cjs/validators/union.cjs +1 -1
- package/dist/cjs/validators/unknown.cjs +1 -1
- package/dist/cjs/validators/void.cjs +1 -1
- package/dist/cjs/validators/xor.cjs +1 -1
- package/dist/coercion/index.js +1 -1
- package/dist/compile.d.ts +81 -0
- package/dist/compile.js +1 -0
- package/dist/errors-core.d.ts +12 -1
- package/dist/errors.js +1 -1
- package/dist/index.d.ts +384 -14
- package/dist/index.js +1 -1
- package/dist/locales/gu.d.ts +2 -0
- package/dist/locales/gu.js +1 -0
- package/dist/locales/index.js +1 -1
- package/dist/locales/kn.d.ts +2 -0
- package/dist/locales/kn.js +1 -0
- package/dist/locales/ne.d.ts +2 -0
- package/dist/locales/ne.js +1 -0
- package/dist/locales/pt-BR-v4.d.ts +2 -0
- package/dist/locales/pt-BR-v4.js +1 -0
- package/dist/locales/sk.d.ts +2 -0
- package/dist/locales/sk.js +1 -0
- package/dist/v3/index.js +1 -1
- package/dist/v4/core/index.d.ts +13 -0
- package/dist/v4/core/index.js +1 -1
- package/dist/v4/index.d.ts +1 -0
- package/dist/v4/index.js +1 -1
- package/dist/v4/locales/index.d.ts +6 -0
- package/dist/v4/locales/index.js +1 -1
- package/dist/v4/mini/index.js +1 -1
- package/dist/v4-mini/index.d.ts +2 -0
- package/dist/v4-mini/index.js +1 -1
- package/dist/validators/array.js +1 -1
- package/dist/validators/base.d.ts +147 -9
- package/dist/validators/base.js +1 -1
- package/dist/validators/base64.js +1 -1
- package/dist/validators/bigint.d.ts +7 -0
- package/dist/validators/bigint.js +1 -1
- package/dist/validators/boolean.js +1 -1
- package/dist/validators/codec.js +1 -1
- package/dist/validators/custom.d.ts +20 -10
- package/dist/validators/custom.js +1 -1
- package/dist/validators/date.d.ts +2 -0
- package/dist/validators/date.js +1 -1
- package/dist/validators/discriminated-union.d.ts +2 -0
- package/dist/validators/discriminated-union.js +1 -1
- package/dist/validators/enum.d.ts +8 -2
- package/dist/validators/enum.js +1 -1
- package/dist/validators/file.js +1 -1
- package/dist/validators/function.js +1 -1
- package/dist/validators/hex.js +1 -1
- package/dist/validators/intersection.js +1 -1
- package/dist/validators/json.js +1 -1
- package/dist/validators/literal.d.ts +1 -0
- package/dist/validators/literal.js +1 -1
- package/dist/validators/map.d.ts +7 -0
- package/dist/validators/map.js +1 -1
- package/dist/validators/nan.js +1 -1
- package/dist/validators/never.js +1 -1
- package/dist/validators/null.js +1 -1
- package/dist/validators/number.d.ts +5 -0
- package/dist/validators/number.js +1 -1
- package/dist/validators/object.d.ts +15 -0
- package/dist/validators/object.js +1 -1
- package/dist/validators/promise.d.ts +6 -7
- package/dist/validators/promise.js +1 -1
- package/dist/validators/record.d.ts +2 -0
- package/dist/validators/record.js +1 -1
- package/dist/validators/set.d.ts +5 -0
- package/dist/validators/set.js +1 -1
- package/dist/validators/string-bool.js +1 -1
- package/dist/validators/string-formats.d.ts +1 -0
- package/dist/validators/string-formats.js +1 -1
- package/dist/validators/string.d.ts +2 -0
- package/dist/validators/string.js +1 -1
- package/dist/validators/symbol.js +1 -1
- package/dist/validators/template-literal.js +1 -1
- package/dist/validators/tuple.js +1 -1
- package/dist/validators/uint8array.js +1 -1
- package/dist/validators/undefined.js +1 -1
- package/dist/validators/union.d.ts +1 -0
- package/dist/validators/union.js +1 -1
- package/dist/validators/void.js +1 -1
- package/dist/validators/xor.js +1 -1
- package/package.json +8 -2
- package/dist/chunks/errors-core-Cqi4-9ew.js +0 -1
- package/dist/chunks/index-yjpbvFgw.js +0 -1
- package/dist/cjs/chunks/errors-core-DKPohm9I.cjs +0 -1
- package/dist/cjs/chunks/index-BEV9nG0N.cjs +0 -1
package/dist/validators/date.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as t}from"./base.js";import{getMessages as
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as t}from"./base.js";import{getMessages as n}from"../locales/runtime.js";import{V as s}from"../chunks/errors-core-CerMg2rq.js";function i(e){return new s([{code:"invalid_date",path:[],message:e}])}class VldDate extends e{constructor(e){super(e?.validatorType||t.DATE),this.config={checks:e?.checks||[],errorMessage:e?.errorMessage,jsonSchema:e?.jsonSchema},this._checks=this.config.checks,this._isSimple=0===this._checks.length}get jsonSchema(){return this.config.jsonSchema}get minDate(){const e=this.config.jsonSchema?.formatMinimum??this.config.jsonSchema?.minimum;return e?new Date(e):null}get maxDate(){const e=this.config.jsonSchema?.formatMaximum??this.config.jsonSchema?.maximum;return e?new Date(e):null}static create(){return new VldDate}parse(e){let t;if(e instanceof Date)t=e;else{if("string"!=typeof e&&"number"!=typeof e)throw new Error(this.config.errorMessage||n().invalidDate);t=new Date(e)}if(isNaN(t.getTime()))throw new Error(this.config.errorMessage||n().invalidDate);return this.parseValidDate(t)}parseKnownDate(e){if(isNaN(e.getTime()))throw new Error(this.config.errorMessage||n().invalidDate);return this.parseValidDate(e)}parseValidDate(e){if(this._isSimple)return e;for(const t of this._checks)if(!t.fn(e))throw new Error(t.message);return e}safeParse(e){if(e instanceof Date)try{return{success:!0,data:this.parseKnownDate(e)}}catch(e){return{success:!1,error:i(e.message)}}try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:i(e.message)}}}min(e,t){const s=e instanceof Date?e:new Date(e);if(isNaN(s.getTime()))throw new Error(`Invalid date provided to min(): ${e}`);return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e>=s,message:t||n().dateMin(s)}],jsonSchema:{...this.config.jsonSchema,formatMinimum:s.toISOString()}})}max(e,t){const s=e instanceof Date?e:new Date(e);if(isNaN(s.getTime()))throw new Error(`Invalid date provided to max(): ${e}`);return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e<=s,message:t||n().dateMax(s)}],jsonSchema:{...this.config.jsonSchema,formatMaximum:s.toISOString()}})}between(e,t,n){const s=e instanceof Date?e:new Date(e),i=t instanceof Date?t:new Date(t);if(isNaN(s.getTime()))throw new Error(`Invalid min date provided to between(): ${e}`);if(isNaN(i.getTime()))throw new Error(`Invalid max date provided to between(): ${t}`);return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e>=s&&e<=i,message:n||`Date must be between ${s.toISOString()} and ${i.toISOString()}`}],jsonSchema:{...this.config.jsonSchema,formatMinimum:s.toISOString(),formatMaximum:i.toISOString()}})}past(e){const t=new Date;return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e<t,message:e||"Date must be in the past"}],jsonSchema:{...this.config.jsonSchema,formatExclusiveMaximum:t.toISOString()}})}future(e){const t=new Date;return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e>t,message:e||"Date must be in the future"}],jsonSchema:{...this.config.jsonSchema,formatExclusiveMinimum:t.toISOString()}})}today(e){const t=new Date,n=t.getFullYear(),s=t.getMonth(),i=t.getDate();return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e.getFullYear()===n&&e.getMonth()===s&&e.getDate()===i,message:e||"Date must be today"}]})}weekday(e){return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>{const t=e.getDay();return t>=1&&t<=5},message:e||"Date must be a weekday"}]})}weekend(e){return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>{const t=e.getDay();return 0===t||6===t},message:e||"Date must be a weekend"}]})}gt(e,t){const n=e instanceof Date?e:new Date(e);return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e.getTime()>n.getTime(),message:t||`Date must be greater than ${n.toISOString()}`}],jsonSchema:{...this.config.jsonSchema,formatExclusiveMinimum:n.toISOString()}})}lt(e,t){const n=e instanceof Date?e:new Date(e);return new VldDate({...this.config,checks:[...this.config.checks,{fn:e=>e.getTime()<n.getTime(),message:t||`Date must be less than ${n.toISOString()}`}],jsonSchema:{...this.config.jsonSchema,formatExclusiveMaximum:n.toISOString()}})}}export{VldDate};
|
|
@@ -16,6 +16,8 @@ export declare class VldDiscriminatedUnion<K extends string, Options extends rea
|
|
|
16
16
|
private readonly _stringDiscriminatorMap;
|
|
17
17
|
private readonly _validValues;
|
|
18
18
|
constructor(_discriminator: K, _options: Options);
|
|
19
|
+
get options(): Options;
|
|
20
|
+
get discriminator(): K;
|
|
19
21
|
static create<K extends string, Options extends readonly VldBase<any, any>[]>(discriminator: K, options: Options): VldDiscriminatedUnion<K, Options>;
|
|
20
22
|
parse(value: unknown): Options[number] extends VldBase<any, infer T> ? T : never;
|
|
21
23
|
safeParse(value: unknown): ParseResult<Options[number] extends VldBase<any, infer T> ? T : never>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as i,VLD_VALIDATOR_TYPES as r}from"./base.js";import{VldObject as
|
|
1
|
+
import{VldBase as i,VLD_VALIDATOR_TYPES as r,ensureVldError as t}from"./base.js";import{VldObject as s}from"./object.js";import{VldLiteral as n}from"./literal.js";import{VldEnum as e}from"./enum.js";function o(i){if(i instanceof n)return[...i.values];if(i instanceof e)return[...i.values];throw new Error("Discriminator must be a literal or enum schema")}class VldDiscriminatedUnion extends i{constructor(i,t){super(r.DISCRIMINATED_UNION),this._discriminator=i,this._options=t,this._discriminatorMap=new Map,this._stringDiscriminatorMap=Object.create(null);for(const i of t){if(!(i instanceof s))throw new Error("All options in a discriminated union must be objects");const r=i.config?.shape?.[this._discriminator];if(!r)throw new Error(`Missing discriminator key "${this._discriminator}" in one of the options`);const t=o(r);for(const r of t){if(this._discriminatorMap.has(r))throw new Error(`Duplicate discriminator value "${String(r)}" found in discriminated union`);this._discriminatorMap.set(r,i),"string"==typeof r&&(this._stringDiscriminatorMap[r]=i)}}this._validValues=Array.from(this._discriminatorMap.keys())}get options(){return this._options}get discriminator(){return this._discriminator}static create(i,r){return new VldDiscriminatedUnion(i,r)}parse(i){if("object"!=typeof i||null===i)throw new Error("Expected object, received "+(null===i?"null":typeof i));const r=i[this._discriminator],t="string"==typeof r?this._stringDiscriminatorMap[r]:this._discriminatorMap.get(r);if(!t)throw new Error(`Invalid discriminator value for "${this._discriminator}". Expected one of: ${JSON.stringify(this._validValues)}, received: ${JSON.stringify(r)}`);return t.parseTrustedKnownObject(i,this._discriminator)}safeParse(i){if("object"!=typeof i||null===i)return{success:!1,error:t("Expected object, received "+(null===i?"null":typeof i))};const r=i[this._discriminator],s="string"==typeof r?this._stringDiscriminatorMap[r]:this._discriminatorMap.get(r);if(!s)return{success:!1,error:t(`Invalid discriminator value for "${this._discriminator}". Expected one of: ${JSON.stringify(this._validValues)}, received: ${JSON.stringify(r)}`)};try{return{success:!0,data:s.parseTrustedKnownObject(i,this._discriminator)}}catch(i){return{success:!1,error:t(i)}}}getDiscriminator(){return this._discriminator}getOptions(){return this._options}}export{VldDiscriminatedUnion};
|
|
@@ -16,6 +16,10 @@ export declare class VldEnum<T extends readonly [EnumValue, ...EnumValue[]]> ext
|
|
|
16
16
|
* Get the enum values
|
|
17
17
|
*/
|
|
18
18
|
get values(): T;
|
|
19
|
+
get options(): T;
|
|
20
|
+
get enum(): {
|
|
21
|
+
[K in T[number]]: K;
|
|
22
|
+
};
|
|
19
23
|
/**
|
|
20
24
|
* Create a new enum validator
|
|
21
25
|
*/
|
|
@@ -32,11 +36,13 @@ export declare class VldEnum<T extends readonly [EnumValue, ...EnumValue[]]> ext
|
|
|
32
36
|
* Exclude specific values from the enum
|
|
33
37
|
* Creates a new enum validator without the specified values
|
|
34
38
|
*/
|
|
35
|
-
exclude<const E extends readonly EnumValue[]>(
|
|
39
|
+
exclude<const E extends readonly EnumValue[]>(values: E): VldEnum<any>;
|
|
40
|
+
exclude<const E extends readonly EnumValue[]>(...values: E): VldEnum<any>;
|
|
36
41
|
/**
|
|
37
42
|
* Extract specific values from the enum
|
|
38
43
|
* Creates a new enum validator with only the specified values
|
|
39
44
|
*/
|
|
40
|
-
extract<const E extends readonly EnumValue[]>(
|
|
45
|
+
extract<const E extends readonly EnumValue[]>(values: E): VldEnum<any>;
|
|
46
|
+
extract<const E extends readonly EnumValue[]>(...values: E): VldEnum<any>;
|
|
41
47
|
}
|
|
42
48
|
export {};
|
package/dist/validators/enum.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{getMessages as s}from"../locales/runtime.js";import{V as t}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{getMessages as s}from"../locales/runtime.js";import{V as t}from"../chunks/errors-core-CerMg2rq.js";class VldEnum extends e{constructor(e,s){super(r.ENUM),this._values=e,this.errorMessage=s,this._valueSet=e.length>6?new Set(e):void 0}createError(e){const r={code:"invalid_value",path:[],values:[...this._values],message:this.errorMessage||s().enumExpected([...this._values],JSON.stringify(e))};return new t([r])}get values(){return this._values}get options(){return this._values}get enum(){const e={};for(const r of this._values)e[r]=r;return e}static create(e){return new VldEnum(e)}parse(e){if("string"!=typeof e&&"number"!=typeof e)throw this.createError(e);const r=this._values;switch(r.length){case 1:if(e===r[0])return e;break;case 2:if(e===r[0]||e===r[1])return e;break;case 3:if(e===r[0]||e===r[1]||e===r[2])return e;break;case 4:if(e===r[0]||e===r[1]||e===r[2]||e===r[3])return e;break;case 5:if(e===r[0]||e===r[1]||e===r[2]||e===r[3]||e===r[4])return e;break;case 6:if(e===r[0]||e===r[1]||e===r[2]||e===r[3]||e===r[4]||e===r[5])return e;break;default:if(this._valueSet.has(e))return e}throw this.createError(e)}safeParse(e){if("string"!=typeof e&&"number"!=typeof e)return{success:!1,error:this.createError(e)};const r=this._values;switch(r.length){case 1:if(e===r[0])return{success:!0,data:e};break;case 2:if(e===r[0]||e===r[1])return{success:!0,data:e};break;case 3:if(e===r[0]||e===r[1]||e===r[2])return{success:!0,data:e};break;case 4:if(e===r[0]||e===r[1]||e===r[2]||e===r[3])return{success:!0,data:e};break;case 5:if(e===r[0]||e===r[1]||e===r[2]||e===r[3]||e===r[4])return{success:!0,data:e};break;case 6:if(e===r[0]||e===r[1]||e===r[2]||e===r[3]||e===r[4]||e===r[5])return{success:!0,data:e};break;default:if(this._valueSet.has(e))return{success:!0,data:e}}return{success:!1,error:this.createError(e)}}exclude(...e){const r=1===e.length&&Array.isArray(e[0])?e[0]:e,s=this._values.filter(e=>!r.includes(e));if(0===s.length)throw new Error("Cannot exclude all enum values");return new VldEnum(s,this.errorMessage)}extract(...e){const r=1===e.length&&Array.isArray(e[0])?e[0]:e,s=this._values.filter(e=>r.includes(e));if(0===s.length)throw new Error("Cannot extract non-existent enum values");return new VldEnum(s,this.errorMessage)}}export{VldEnum};
|
package/dist/validators/file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as s}from"./base.js";import{getMessages as i}from"../locales/runtime.js";import{V as r}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as s}from"./base.js";import{getMessages as i}from"../locales/runtime.js";import{V as r}from"../chunks/errors-core-CerMg2rq.js";class VldFile extends e{constructor(e=[]){super(s.FILE),this.checks=e}static create(){return new VldFile}isFileLike(e){return"object"==typeof e&&null!==e&&("undefined"!=typeof File&&e instanceof File||"size"in e&&"type"in e)}parse(e){if(this.isFileLike(e))return this.parseKnownFile(e);if("undefined"==typeof File)throw new Error(i().fileNotSupported||"File API not supported in this environment");throw new Error(i().invalidFile||"Expected a File object")}parseKnownFile(e){return this.runChecks(e)}runChecks(e){const s=i();for(const i of this.checks)switch(i.type){case"min":if(e.size<i.value)throw new Error(i.message||s.fileMinSize?.(i.value)||`File size must be at least ${i.value} bytes`);break;case"max":if(e.size>i.value)throw new Error(i.message||s.fileMaxSize?.(i.value)||`File size must not exceed ${i.value} bytes`);break;case"mime":if(!i.value.includes(e.type))throw new Error(i.message||s.fileMimeType?.(i.value)||`Invalid file type. Expected: ${i.value.join(", ")}`)}return e}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:(s=e.message,new r([{code:"invalid_type",path:[],message:s}]))}}var s}min(e,s){return new VldFile([...this.checks,{type:"min",value:e,message:s}])}max(e,s){return new VldFile([...this.checks,{type:"max",value:e,message:s}])}mime(e,s){const i=Array.isArray(e)?e:[e];return new VldFile([...this.checks,{type:"mime",value:i,message:s}])}size(e,s,i){return this.min(e,i).max(s,i)}}function t(){return VldFile.create()}export{VldFile,t as file};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as r,VLD_VALIDATOR_TYPES as e}from"./base.js";import{getMessages as t}from"../locales/runtime.js";import{V as n}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as r,VLD_VALIDATOR_TYPES as e}from"./base.js";import{getMessages as t}from"../locales/runtime.js";import{V as n}from"../chunks/errors-core-CerMg2rq.js";class VldFunction extends r{constructor(){super(e.FUNCTION)}static create(){return new VldFunction}parse(r){if("function"!=typeof r)throw new Error(t().invalidFunction||"Expected a function");return r}parseKnownFunction(r){return r}safeParse(r){try{return{success:!0,data:this.parse(r)}}catch(r){return{success:!1,error:(e=r.message,new n([{code:"invalid_type",path:[],message:e}]))}}var e}}function s(){return VldFunction.create()}export{VldFunction,s as functionValidator};
|
package/dist/validators/hex.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{createIssue as s}from"../errors.js";import{getMessages as t}from"../locales/runtime.js";import{V as o}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{createIssue as s}from"../errors.js";import{getMessages as t}from"../locales/runtime.js";import{V as o}from"../chunks/errors-core-CerMg2rq.js";class VldHex extends e{constructor(e=!1){super(r.HEX),this.lowercase=e}parse(e){const r=this.safeParse(e);if(!r.success)throw r.error;return r.data}safeParse(e){if("string"!=typeof e)return{success:!1,error:new o([s("invalid_type",[],t().expectedString)])};if(!VldHex.HEX_REGEX.test(e))return{success:!1,error:new o([s("custom",[],t().invalidHex)])};if(e.length%2!=0)return{success:!1,error:new o([s("custom",[],t().invalidHex)])};return{success:!0,data:this.lowercase?e.toLowerCase():e}}lowercaseMode(){return new VldHex(!0)}static create(e=!1){return new VldHex(e)}}VldHex.HEX_REGEX=/^[0-9a-fA-F]*$/;export{VldHex};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as t,VLD_VALIDATOR_TYPES as e}from"./base.js";import{i as r}from"../chunks/security-Dy24T8N7.js";import{getMessages as o}from"../locales/runtime.js";import{V as s}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as t,VLD_VALIDATOR_TYPES as e}from"./base.js";import{i as r}from"../chunks/security-Dy24T8N7.js";import{getMessages as o}from"../locales/runtime.js";import{V as s}from"../chunks/errors-core-CerMg2rq.js";function n(t){return null!==t&&"object"==typeof t&&t.constructor===Object&&"[object Object]"===Object.prototype.toString.call(t)}function c(t,e){const o={...t},s=Object.keys(e);for(let i=0;i<s.length;i++){const a=s[i];if(r(a))continue;if(!Object.prototype.hasOwnProperty.call(e,a))continue;const u=e[a],p=t[a];n(u)&&n(p)?o[a]=c(p,u):o[a]=u}return o}class VldIntersection extends t{constructor(t,r){super(e.INTERSECTION),this.validatorA=t,this.validatorB=r}static create(t,e){return new VldIntersection(t,e)}parse(t){try{const e=this.validatorA.parse(t),r=this.validatorB.parse(t),o=n(e),s=n(r);if(o&&s)return c(e,r);if(!o&&!s){if(e===r)return e;throw new Error("Values must be identical for intersection of primitive types")}throw new Error("Cannot create intersection of object and primitive types. Both validators must produce the same type category.")}catch(t){throw new Error(o().intersectionError(t.message))}}safeParse(t){try{return{success:!0,data:this.parse(t)}}catch(t){return{success:!1,error:(e=t.message,new s([{code:"invalid_type",path:[],message:e}]))}}var e}}export{VldIntersection};
|
package/dist/validators/json.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as s,VLD_VALIDATOR_TYPES as r}from"./base.js";import{getMessages as
|
|
1
|
+
import{VldBase as s,VLD_VALIDATOR_TYPES as r,ensureVldError as e}from"./base.js";import{getMessages as t}from"../locales/runtime.js";class VldJson extends s{constructor(s){super(r.JSON),this.schema=s}static create(s){return new VldJson(s)}parse(s){let r;if("string"==typeof s)try{r=JSON.parse(s)}catch{throw new Error(t().invalidJson)}else r=s;return this.schema?this.schema.parse(r):r}safeParse(s){try{return{success:!0,data:this.parse(s)}}catch(s){return{success:!1,error:e(s)}}}withSchema(s){return new VldJson(s)}}export{VldJson};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{getMessages as t}from"../locales/runtime.js";import{V as s}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{getMessages as t}from"../locales/runtime.js";import{V as s}from"../chunks/errors-core-CerMg2rq.js";function a(e){const r=JSON.stringify(e,(e,r)=>"bigint"==typeof r?r.toString():r);return void 0===r?String(e):r}class VldLiteral extends e{constructor(e,t){super(r.LITERAL),this._values=e,this.errorMessage=t}get literal(){return this._values[0]}get value(){return this._values[0]}get values(){return this._values}get isSimple(){return 1===this._values.length}get expectedDisplay(){return a(1===this._values.length?this._values[0]:this._values)}static create(e){const r=Array.isArray(e)?e:[e];if(0===r.length)throw new Error("Cannot create literal schema with no valid values");return new VldLiteral(r)}parse(e){if(!this._values.includes(e))throw this._createLiteralError(e);return e}_createLiteralError(e){const r={code:"invalid_value",path:[],values:[...this._values],message:this.errorMessage||t().literalExpected(this.expectedDisplay,a(e))};return new s([r])}safeParse(e){return this._values.includes(e)?{success:!0,data:e}:{success:!1,error:this._createLiteralError(e)}}}export{VldLiteral};
|
package/dist/validators/map.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ export declare class VldMap<K, V> extends VldBase<unknown, Map<K, V>> {
|
|
|
6
6
|
private readonly keyValidator;
|
|
7
7
|
private readonly valueValidator;
|
|
8
8
|
private readonly errorMessage?;
|
|
9
|
+
private readonly _checks;
|
|
9
10
|
/**
|
|
10
11
|
* Private constructor to enforce immutability
|
|
11
12
|
*/
|
|
@@ -16,6 +17,8 @@ export declare class VldMap<K, V> extends VldBase<unknown, Map<K, V>> {
|
|
|
16
17
|
private readonly _simpleValueValue;
|
|
17
18
|
get keySchema(): VldBase<unknown, K>;
|
|
18
19
|
get valueSchema(): VldBase<unknown, V>;
|
|
20
|
+
get keyType(): VldBase<unknown, K>;
|
|
21
|
+
get valueType(): VldBase<unknown, V>;
|
|
19
22
|
/**
|
|
20
23
|
* Create a new Map validator
|
|
21
24
|
*/
|
|
@@ -36,4 +39,8 @@ export declare class VldMap<K, V> extends VldBase<unknown, Map<K, V>> {
|
|
|
36
39
|
* Safely parse and validate a Map value
|
|
37
40
|
*/
|
|
38
41
|
safeParse(value: unknown): ParseResult<Map<K, V>>;
|
|
42
|
+
min(size: number, message?: string): VldMap<K, V>;
|
|
43
|
+
max(size: number, message?: string): VldMap<K, V>;
|
|
44
|
+
size(size: number, message?: string): VldMap<K, V>;
|
|
45
|
+
nonempty(message?: string): VldMap<K, V>;
|
|
39
46
|
}
|
package/dist/validators/map.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{getMessages as t}from"../locales/runtime.js";import{V as
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{getMessages as t}from"../locales/runtime.js";import{V as s}from"../chunks/errors-core-CerMg2rq.js";class VldMap extends e{constructor(e,t,s,i=[]){super(r.MAP),this.keyValidator=e,this.valueValidator=t,this.errorMessage=s,this._checks=i,this._simpleKeyMode=this.getSimpleItemMode(e),this._simpleValueMode=this.getSimpleItemMode(t),this._simpleKeyValue="literal"===this._simpleKeyMode?e.literal:void 0,this._simpleValueValue="literal"===this._simpleValueMode?t.literal:void 0}get keySchema(){return this.keyValidator}get valueSchema(){return this.valueValidator}get keyType(){return this.keyValidator}get valueType(){return this.valueValidator}static create(e,r){return new VldMap(e,r)}getSimpleItemMode(e){if(!0===e.isSimple)switch(e.validatorType){case r.STRING:return"string";case r.NUMBER:return"number";case r.BOOLEAN:return"boolean";case r.BIGINT:return"bigint";case r.SYMBOL:return"symbol";case r.NULL:return"null";case r.UNDEFINED:case r.VOID:return"undefinedValue";case r.LITERAL:return"literal";case r.ANY:case r.UNKNOWN:return"passthrough";default:return}}getSimpleItemError(e,r,s){switch(e){case"string":return t().invalidString;case"number":return t().invalidNumber;case"boolean":return t().invalidBoolean;case"bigint":return t().invalidBigint;case"symbol":return t().invalidSymbol;case"null":return"Expected null, received "+typeof s;case"undefinedValue":return t().expectedUndefined;case"literal":return t().literalExpected(JSON.stringify(r),JSON.stringify(s));default:return t().invalidMap}}parseSimpleItem(e,r,t){switch(e){case"string":if("string"!=typeof t)throw new Error(this.getSimpleItemError(e,r,t));return t;case"number":if("number"!=typeof t||isNaN(t))throw new Error(this.getSimpleItemError(e,r,t));return t;case"boolean":if("boolean"!=typeof t)throw new Error(this.getSimpleItemError(e,r,t));return t;case"bigint":if("bigint"!=typeof t)throw new Error(this.getSimpleItemError(e,r,t));return t;case"symbol":if("symbol"!=typeof t)throw new Error(this.getSimpleItemError(e,r,t));return t;case"null":if(null!==t)throw new Error(this.getSimpleItemError(e,r,t));return null;case"undefinedValue":if(void 0!==t)throw new Error(this.getSimpleItemError(e,r,t));return;case"literal":if(t!==r)throw new Error(this.getSimpleItemError(e,r,t));return r;case"passthrough":return t}}parse(e){if(!(e instanceof Map))throw new Error(this.errorMessage||t().invalidMap);return this.parseKnownMap(e)}parseKnownMap(e){const r=new Map,t=this._simpleKeyMode,s=this._simpleValueMode;if("string"===t&&"number"===s)for(const[i,a]of e){if("string"!=typeof i)throw new Error(this.getSimpleItemError(t,this._simpleKeyValue,i));if("number"!=typeof a||isNaN(a))throw new Error(this.getSimpleItemError(s,this._simpleValueValue,a));r.set(i,a)}else if("string"===t&&"string"===s)for(const[i,a]of e){if("string"!=typeof i)throw new Error(this.getSimpleItemError(t,this._simpleKeyValue,i));if("string"!=typeof a)throw new Error(this.getSimpleItemError(s,this._simpleValueValue,a));r.set(i,a)}else if(void 0!==t&&void 0!==s){const i=t,a=s;for(const[t,s]of e){const e=this.parseSimpleItem(i,this._simpleKeyValue,t),n=this.parseSimpleItem(a,this._simpleValueValue,s);r.set(e,n)}}else for(const[i,a]of e)try{const e=void 0===t?this.keyValidator.parse(i):this.parseSimpleItem(t,this._simpleKeyValue,i),n=void 0===s?this.valueValidator.parse(a):this.parseSimpleItem(s,this._simpleValueValue,a);r.set(e,n)}catch(e){throw new Error(e.message)}for(const e of this._checks)if(!e.fn(r))throw new Error(e.message);return r}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:(r=e.message,new s([{code:"invalid_type",path:[],message:r}]))}}var r}min(e,r){return new VldMap(this.keyValidator,this.valueValidator,this.errorMessage,[...this._checks,{fn:r=>r.size>=e,message:r||`Map must contain at least ${e} entries`}])}max(e,r){return new VldMap(this.keyValidator,this.valueValidator,this.errorMessage,[...this._checks,{fn:r=>r.size<=e,message:r||`Map must contain at most ${e} entries`}])}size(e,r){return new VldMap(this.keyValidator,this.valueValidator,this.errorMessage,[...this._checks,{fn:r=>r.size===e,message:r||`Map must contain exactly ${e} entries`}])}nonempty(e){return this.min(1,e||"Map cannot be empty")}}export{VldMap};
|
package/dist/validators/nan.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{V as s}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{V as s}from"../chunks/errors-core-CerMg2rq.js";class VldNan extends e{constructor(){super(r.NAN)}static create(){return new VldNan}parse(e){if("number"!=typeof e||!Number.isNaN(e))throw new Error("Expected NaN, received "+("number"==typeof e?"a valid number":typeof e));return e}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:(r=e.message,new s([{code:"invalid_number",path:[],message:r}]))}}var r}}export{VldNan};
|
package/dist/validators/never.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e}from"./base.js";import{getMessages as r}from"../locales/runtime.js";import{V as s}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as e}from"./base.js";import{getMessages as r}from"../locales/runtime.js";import{V as s}from"../chunks/errors-core-CerMg2rq.js";class VldNever extends e{static create(){return new VldNever}parse(e){throw new Error(r().neverType)}safeParse(e){return{success:!1,error:new s([{code:"invalid_type",path:[],message:r().neverType}])}}}export{VldNever};
|
package/dist/validators/null.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{V as s}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{V as s}from"../chunks/errors-core-CerMg2rq.js";class VldNull extends e{constructor(){super(r.NULL)}static create(){return new VldNull}get isSimple(){return!0}parse(e){if(null!==e)throw new Error("Expected null, received "+typeof e);return null}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:(r=e.message,new s([{code:"invalid_type",path:[],message:r}]))}}var r}}export{VldNull};
|
|
@@ -54,6 +54,11 @@ export declare class VldNumber extends VldBase<number, number> {
|
|
|
54
54
|
* Used by VldObject for optimized fast-path dispatch
|
|
55
55
|
*/
|
|
56
56
|
get isSimple(): boolean;
|
|
57
|
+
get minValue(): number | null;
|
|
58
|
+
get maxValue(): number | null;
|
|
59
|
+
get isInt(): boolean;
|
|
60
|
+
get isFinite(): boolean;
|
|
61
|
+
get format(): string | null;
|
|
57
62
|
/**
|
|
58
63
|
* Create a new number validator
|
|
59
64
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as s,resolveErrorMessage as i}from"./base.js";import{getMessages as n}from"../locales/runtime.js";import{V as t,c,g as r}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as s,resolveErrorMessage as i}from"./base.js";import{getMessages as n}from"../locales/runtime.js";import{V as t,c,g as r}from"../chunks/errors-core-CerMg2rq.js";class VldNumber extends e{constructor(e){super(e?.validatorType||s.NUMBER),this.config={checks:e?.checks||[],errorMessage:e?.errorMessage,jsonSchema:e?.jsonSchema,checkMetas:e?.checkMetas},this._checks=this.config.checks,this._isSimple=0===this._checks.length,this._fastCheckMode=this.detectFastCheckMode(),this._checkMetas=this.config.checkMetas}detectFastCheckMode(){const e=this.config.jsonSchema;return 0===this._checks.length?"none":1===this._checks.length&&0===e?.exclusiveMinimum&&"integer"!==e.type?"positive":2===this._checks.length&&0===e?.exclusiveMinimum&&"integer"===e.type?"positive-int":void 0}get hasCustomChecks(){return!this._isSimple}get isSimple(){return this._isSimple}get minValue(){return this.config.jsonSchema?.minimum??this.config.jsonSchema?.exclusiveMinimum??null}get maxValue(){return this.config.jsonSchema?.maximum??this.config.jsonSchema?.exclusiveMaximum??null}get isInt(){return"integer"===this.config.jsonSchema?.type}get isFinite(){return!0}get format(){return this.config.jsonSchema?.format??null}static create(){return new VldNumber}parse(e){if("number"!=typeof e||!Number.isFinite(e))throw new t([c("number",r(e),this.config.errorMessage)]);switch(this._fastCheckMode){case"none":return e;case"positive":if(e>0)return e;throw new t([this._createCheckIssue("gt",0,this.config.errorMessage)]);case"positive-int":if(e>0&&Number.isInteger(e))return e;throw new t([this._createCheckIssue("int",void 0,this.config.errorMessage)])}return this.parseKnownNumber(e)}_createCheckIssue(e,s,i){switch(e){case"min":return{code:"too_small",path:[],origin:"number",minimum:s,inclusive:!0,message:i||`Too small: expected number to be >=${s}`};case"max":return{code:"too_big",path:[],origin:"number",maximum:s,inclusive:!0,message:i||`Too big: expected number to be <=${s}`};case"gt":return{code:"too_small",path:[],origin:"number",minimum:s,inclusive:!1,message:i||`Too small: expected number to be >${s}`};case"lt":return{code:"too_big",path:[],origin:"number",maximum:s,inclusive:!1,message:i||`Too big: expected number to be <${s}`};case"int":return{code:"invalid_type",path:[],expected:"int",received:"number",message:i||"Invalid input: expected int, received number"};default:return{code:"custom",path:[],message:i||"Invalid number"}}}_findFailingCheck(e){const s=this._checks,i=this._checkMetas;for(let n=0;n<s.length;n++)if(!s[n](e))return i?.[n]??{kind:"other",message:this.config.errorMessage};return null}parseKnownNumber(e){switch(this._fastCheckMode){case"none":return e;case"positive":if(e>0)return e;throw new t([this._createCheckIssue("gt",0,this.config.errorMessage)]);case"positive-int":if(e>0&&Number.isInteger(e))return e;throw new t([this._createCheckIssue("int",void 0,this.config.errorMessage)])}const s=this._findFailingCheck(e);if(s)throw new t([this._createCheckIssue(s.kind,s.value,s.message)]);return e}safeParse(e){if("number"!=typeof e||!Number.isFinite(e))return{success:!1,error:new t([c("number",r(e),this.config.errorMessage)])};try{const s=this._findFailingCheck(e);if(s)return{success:!1,error:new t([this._createCheckIssue(s.kind,s.value,s.message)])}}catch(e){return e instanceof t?{success:!1,error:e}:{success:!1,error:new t([{code:"custom",path:[],message:e.message}])}}return{success:!0,data:e}}min(e,s){return new VldNumber({checks:[...this.config.checks,s=>s>=e],errorMessage:i(s,n().numberMin(e)),jsonSchema:{...this.config.jsonSchema,minimum:e},checkMetas:[...this.config.checkMetas??[],{kind:"min",value:e,inclusive:!0,message:i(s,n().numberMin(e))}]})}max(e,s){return new VldNumber({checks:[...this.config.checks,s=>s<=e],errorMessage:i(s,n().numberMax(e)),jsonSchema:{...this.config.jsonSchema,maximum:e},checkMetas:[...this.config.checkMetas??[],{kind:"max",value:e,inclusive:!0,message:i(s,n().numberMax(e))}]})}int(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isInteger(e)],errorMessage:i(e,n().numberInt),jsonSchema:{...this.config.jsonSchema,type:"integer"},checkMetas:[...this.config.checkMetas??[],{kind:"int",message:i(e,n().numberInt)}]})}positive(e){return new VldNumber({checks:[...this.config.checks,e=>e>0],errorMessage:i(e,n().numberPositive),jsonSchema:{...this.config.jsonSchema,exclusiveMinimum:0},checkMetas:[...this.config.checkMetas??[],{kind:"gt",value:0,inclusive:!1,message:i(e,n().numberPositive)}]})}negative(e){return new VldNumber({checks:[...this.config.checks,e=>e<0],errorMessage:i(e,n().numberNegative),jsonSchema:{...this.config.jsonSchema,exclusiveMaximum:0},checkMetas:[...this.config.checkMetas??[],{kind:"lt",value:0,inclusive:!1,message:i(e,n().numberNegative)}]})}nonnegative(e){return new VldNumber({checks:[...this.config.checks,e=>e>=0],errorMessage:i(e,n().numberNonnegative),jsonSchema:{...this.config.jsonSchema,minimum:0},checkMetas:[...this.config.checkMetas??[],{kind:"min",value:0,inclusive:!0,message:i(e,n().numberNonnegative)}]})}nonpositive(e){return new VldNumber({checks:[...this.config.checks,e=>e<=0],errorMessage:i(e,n().numberNonpositive),jsonSchema:{...this.config.jsonSchema,maximum:0},checkMetas:[...this.config.checkMetas??[],{kind:"max",value:0,inclusive:!0,message:i(e,n().numberNonpositive)}]})}finite(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isFinite(e)],errorMessage:i(e,n().numberFinite),jsonSchema:this.config.jsonSchema})}safe(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isSafeInteger(e)],errorMessage:i(e,n().numberSafe),jsonSchema:{...this.config.jsonSchema,type:"integer"}})}multipleOf(e,s){return new VldNumber({checks:[...this.config.checks,s=>{const i=Math.abs(s%e);return i<Number.EPSILON||Math.abs(i-Math.abs(e))<Number.EPSILON}],errorMessage:i(s,n().numberMultipleOf(e)),jsonSchema:{...this.config.jsonSchema,multipleOf:e}})}step(e,s){return this.multipleOf(e,s)}between(e,s,n){return new VldNumber({checks:[...this.config.checks,i=>i>=e&&i<=s],errorMessage:i(n,`Number must be between ${e} and ${s}`),jsonSchema:{...this.config.jsonSchema,minimum:e,maximum:s}})}even(e){return new VldNumber({checks:[...this.config.checks,e=>!!Number.isInteger(e)&&e%2==0],errorMessage:i(e,"Number must be even"),jsonSchema:{...this.config.jsonSchema,type:"integer",multipleOf:2}})}odd(e){return new VldNumber({checks:[...this.config.checks,e=>!!Number.isInteger(e)&&e%2!=0],errorMessage:i(e,"Number must be odd"),jsonSchema:{...this.config.jsonSchema,type:"integer"}})}gt(e,s){return new VldNumber({checks:[...this.config.checks,s=>s>e],errorMessage:i(s,`Number must be greater than ${e}`),jsonSchema:{...this.config.jsonSchema,exclusiveMinimum:e},checkMetas:[...this.config.checkMetas??[],{kind:"gt",value:e,inclusive:!1,message:i(s,`Number must be greater than ${e}`)}]})}lt(e,s){return new VldNumber({checks:[...this.config.checks,s=>s<e],errorMessage:i(s,`Number must be less than ${e}`),jsonSchema:{...this.config.jsonSchema,exclusiveMaximum:e},checkMetas:[...this.config.checkMetas??[],{kind:"lt",value:e,inclusive:!1,message:i(s,`Number must be less than ${e}`)}]})}gte(e,s){return this.min(e,s)}lte(e,s){return this.max(e,s)}uint32(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isSafeInteger(e)&&e>=0&&e<=4294967295],errorMessage:i(e,"Expected an unsigned 32-bit integer"),jsonSchema:{...this.config.jsonSchema,type:"integer",minimum:0,maximum:4294967295}})}uint64(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isSafeInteger(e)&&e>=0],errorMessage:i(e,"Expected an unsigned 64-bit integer"),jsonSchema:{...this.config.jsonSchema,type:"integer",minimum:0}})}int32(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isSafeInteger(e)&&e>=-2147483648&&e<=2147483647],errorMessage:i(e,"Expected a signed 32-bit integer"),jsonSchema:{...this.config.jsonSchema,type:"integer",minimum:-2147483648,maximum:2147483647}})}int64(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isSafeInteger(e)],errorMessage:i(e,"Expected a signed 64-bit integer"),jsonSchema:{...this.config.jsonSchema,type:"integer"}})}float32(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isFinite(e)&&Math.abs(e)<=34e37],errorMessage:i(e,"Expected a 32-bit float"),jsonSchema:{...this.config.jsonSchema,minimum:-34e37,maximum:34e37}})}float64(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isFinite(e)],errorMessage:i(e,"Expected a 64-bit float"),jsonSchema:this.config.jsonSchema})}}export{VldNumber};
|
|
@@ -109,13 +109,28 @@ export declare class VldObject<T extends Record<string, any>> extends VldBase<un
|
|
|
109
109
|
* Create a new validator with deep partial (nested objects also partial)
|
|
110
110
|
*/
|
|
111
111
|
deepPartial(): VldObject<any>;
|
|
112
|
+
/**
|
|
113
|
+
* Zod 4 `z.exactPartial()` counterpart - same as `partial()` but errors
|
|
114
|
+
* when an explicit `undefined` is provided for an optional field. VLD
|
|
115
|
+
* mirrors Zod's behaviour by rejecting explicit-undefined inputs through
|
|
116
|
+
* `VldExactOptional`.
|
|
117
|
+
*/
|
|
118
|
+
exactPartial(): VldObject<{
|
|
119
|
+
[K in keyof T]?: T[K];
|
|
120
|
+
}>;
|
|
112
121
|
/**
|
|
113
122
|
* Create a new validator with only specified keys
|
|
114
123
|
*/
|
|
124
|
+
pick<Mask extends {
|
|
125
|
+
[k in keyof T]?: true;
|
|
126
|
+
}>(mask: Mask): VldObject<Pick<T, Extract<keyof Mask, keyof T>>>;
|
|
115
127
|
pick<K extends keyof T>(...keys: K[]): VldObject<Pick<T, K>>;
|
|
116
128
|
/**
|
|
117
129
|
* Create a new validator without specified keys
|
|
118
130
|
*/
|
|
131
|
+
omit<Mask extends {
|
|
132
|
+
[k in keyof T]?: true;
|
|
133
|
+
}>(mask: Mask): VldObject<Omit<T, Extract<keyof Mask, keyof T>>>;
|
|
119
134
|
omit<K extends keyof T>(...keys: K[]): VldObject<Omit<T, K>>;
|
|
120
135
|
/**
|
|
121
136
|
* Create a new validator with additional fields
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as t,VldOptional as s}from"./base.js";import{getMessages as r}from"../locales/runtime.js";import{VldEnum as i}from"./enum.js";import{i as n}from"../chunks/security-Dy24T8N7.js";import{V as o}from"../chunks/errors-core-Cqi4-9ew.js";class VldObject extends e{createSafeParseError(e){return new o([{code:"invalid_object",path:[],message:e}])}constructor(s){super(t.OBJECT),this._config=s,this._shapeKeys=Object.keys(s.shape),this._shapeKeysSet=new Set(this._shapeKeys),this._validators=this._shapeKeys.map(e=>this.tryGetFieldValidator(e)),this._validatorTypes=this._shapeKeys.map((e,t)=>this._validators[t]?.validatorType||this.getValidatorType(e)),this._simpleFieldModes=this._validators.map((e,t)=>this.getSimpleFieldMode(e,this._validatorTypes[t])),this._simpleFieldValues=this._validators.map((e,t)=>"literal"===this._simpleFieldModes[t]?e.literal:void 0),this._canUseSimpleObjectFastPath=!s.strict&&!s.passthrough&&!s.catchall&&this._shapeKeys.length>0&&this._simpleFieldModes.every(e=>void 0!==e),this._canUseSafeParseFastPath=this._validators.every(t=>t instanceof e)&&(void 0===s.catchall||s.catchall instanceof e)}tryGetFieldValidator(e){try{const t=Object.getOwnPropertyDescriptor(this._config.shape,e);if(t?.get)return;return this.resolveFieldValidator(e)}catch{return}}resolveFieldValidator(e){try{const t=this._config.shape[e];if(!t||"function"!=typeof t.safeParse)return;return t}catch{return}}getFieldValidator(e,t){const s=(void 0===t?void 0:this._validators[t])||this.resolveFieldValidator(e);if(!s)throw new Error(`Invalid validator for field "${e}"`);return s}getValidatorType(e){try{const s=this._config.shape[e];return s?.validatorType||t.UNKNOWN}catch{return t.UNKNOWN}}getSimpleFieldMode(e,s){if(e&&!0===e.isSimple)switch(s){case t.STRING:return"string";case t.NUMBER:return"number";case t.BOOLEAN:return"boolean";case t.BIGINT:return"bigint";case t.SYMBOL:return"symbol";case t.NULL:return"null";case t.UNDEFINED:case t.VOID:return"undefinedValue";case t.LITERAL:return"literal";case t.ANY:case t.UNKNOWN:return"passthrough";default:return}}getSimpleFieldError(e,t,s){switch(e){case"string":return r().invalidString;case"number":return r().invalidNumber;case"boolean":return r().invalidBoolean;case"bigint":return r().invalidBigint;case"symbol":return r().invalidSymbol;case"null":return"Expected null, received "+typeof s;case"undefinedValue":return r().expectedUndefined;case"literal":return r().literalExpected(JSON.stringify(t),JSON.stringify(s));default:return r().invalidObject}}parseCheckedField(e,s,r){if(s===t.STRING&&"string"==typeof r){const t=e.parseKnownString;if("function"==typeof t)return t.call(e,r)}if(s===t.NUMBER&&"number"==typeof r&&!isNaN(r)){const t=e.parseKnownNumber;if("function"==typeof t)return t.call(e,r)}if(s===t.BOOLEAN&&"boolean"==typeof r){const t=e.parseKnownBoolean;if("function"==typeof t)return t.call(e,r)}if(s===t.BIGINT&&"bigint"==typeof r){const t=e.parseKnownBigInt;if("function"==typeof t)return t.call(e,r)}if(s===t.SYMBOL&&"symbol"==typeof r){const t=e.parseKnownSymbol;if("function"==typeof t)return t.call(e,r)}if(s===t.FUNCTION&&"function"==typeof r){const t=e.parseKnownFunction;if("function"==typeof t)return t.call(e,r)}if(s===t.FILE&&"object"==typeof r&&null!==r&&("size"in r&&"type"in r||"undefined"!=typeof File&&r instanceof File)){const t=e.parseKnownFile;if("function"==typeof t)return t.call(e,r)}if(s===t.DATE&&r instanceof Date){const t=e.parseKnownDate;if("function"==typeof t)return t.call(e,r)}if(s===t.OBJECT&&"object"==typeof r&&null!==r&&!Array.isArray(r)){const t=e.parseKnownObject;if("function"==typeof t)return t.call(e,r)}if(s===t.ARRAY&&Array.isArray(r)){const t=e.parseKnownArray;if("function"==typeof t)return t.call(e,r)}if(s===t.TUPLE&&Array.isArray(r)){const t=e.parseKnownTuple;if("function"==typeof t)return t.call(e,r)}if(s===t.RECORD&&"object"==typeof r&&null!==r&&!Array.isArray(r)){const t=e.parseKnownRecord;if("function"==typeof t)return t.call(e,r)}if(s===t.SET&&r instanceof Set){const t=e.parseKnownSet;if("function"==typeof t)return t.call(e,r)}if(s===t.MAP&&r instanceof Map){const t=e.parseKnownMap;if("function"==typeof t)return t.call(e,r)}return e.parse(r)}parseSimpleObjectValue(e,t,s=!1){if(2===this._shapeKeys.length&&"string"===this._simpleFieldModes[0]&&"number"===this._simpleFieldModes[1]){const t=this._shapeKeys[0],s=e[t];if("string"!=typeof s)throw new Error(r().objectField(t,r().invalidString));const i=this._shapeKeys[1],n=e[i];if("number"!=typeof n||isNaN(n))throw new Error(r().objectField(i,r().invalidNumber));const o={};return o[t]=s,o[i]=n,o}if(3===this._shapeKeys.length&&"literal"===this._simpleFieldModes[0]&&"string"===this._simpleFieldModes[1]&&"number"===this._simpleFieldModes[2]){const i=this._shapeKeys[0],n=e[i],o=this._simpleFieldValues[0];if((!s||i!==t)&&n!==o)throw new Error(r().objectField(i,this.getSimpleFieldError("literal",o,n)));const a=this._shapeKeys[1],c=e[a];if("string"!=typeof c)throw new Error(r().objectField(a,r().invalidString));const l=this._shapeKeys[2],h=e[l];if("number"!=typeof h||isNaN(h))throw new Error(r().objectField(l,r().invalidNumber));const f={};return f[i]=o,f[a]=c,f[l]=h,f}const i={};for(let n=0;n<this._shapeKeys.length;n++){const o=this._shapeKeys[n],a=e[o],c=this._simpleFieldModes[n];switch(c){case"string":if("string"!=typeof a)throw new Error(r().objectField(o,r().invalidString));i[o]=a;break;case"number":if("number"!=typeof a||isNaN(a))throw new Error(r().objectField(o,r().invalidNumber));i[o]=a;break;case"boolean":if("boolean"!=typeof a)throw new Error(r().objectField(o,r().invalidBoolean));i[o]=a;break;case"bigint":if("bigint"!=typeof a)throw new Error(r().objectField(o,r().invalidBigint));i[o]=a;break;case"symbol":if("symbol"!=typeof a)throw new Error(r().objectField(o,r().invalidSymbol));i[o]=a;break;case"null":if(null!==a)throw new Error(r().objectField(o,this.getSimpleFieldError(c,void 0,a)));i[o]=null;break;case"undefinedValue":if(void 0!==a)throw new Error(r().objectField(o,r().expectedUndefined));i[o]=void 0;break;case"literal":if(s&&o===t){i[o]=this._simpleFieldValues[n];break}if(a!==this._simpleFieldValues[n])throw new Error(r().objectField(o,this.getSimpleFieldError(c,this._simpleFieldValues[n],a)));i[o]=this._simpleFieldValues[n];break;case"passthrough":i[o]=a;break;default:throw new Error(r().objectField(o,r().invalidObject))}}return i}get config(){return this._config}get shapeKeys(){return this._shapeKeys}get shapeKeysSet(){return this._shapeKeysSet}static create(e){return new VldObject({shape:e})}parse(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this._config.errorMessage||r().invalidObject);return this.parseObjectValue(e)}parseKnownObject(e,t){return this.parseObjectValue(e,t)}parseTrustedKnownObject(e,t){return this.parseObjectValue(e,t,!0)}parseObjectValue(e,t,s=!1){if(this._canUseSimpleObjectFastPath)return this.parseSimpleObjectValue(e,t,s);const i={};let o="";try{for(let n=0;n<this._shapeKeys.length;n++){if(o=this._shapeKeys[n],s&&o===t&&"literal"===this._simpleFieldModes[n]){i[o]=this._simpleFieldValues[n];continue}const a=this._simpleFieldModes[n];if(void 0!==a){const t=e[o];switch(a){case"string":if("string"!=typeof t)throw new Error(r().invalidString);i[o]=t;continue;case"number":if("number"!=typeof t||isNaN(t))throw new Error(r().invalidNumber);i[o]=t;continue;case"boolean":if("boolean"!=typeof t)throw new Error(r().invalidBoolean);i[o]=t;continue;case"bigint":if("bigint"!=typeof t)throw new Error(r().invalidBigint);i[o]=t;continue;case"symbol":if("symbol"!=typeof t)throw new Error(r().invalidSymbol);i[o]=t;continue;case"null":if(null!==t)throw new Error(this.getSimpleFieldError(a,void 0,t));i[o]=null;continue;case"undefinedValue":if(void 0!==t)throw new Error(r().expectedUndefined);i[o]=void 0;continue;case"literal":if(t!==this._simpleFieldValues[n])throw new Error(this.getSimpleFieldError(a,this._simpleFieldValues[n],t));i[o]=this._simpleFieldValues[n];continue;case"passthrough":i[o]=t;continue}continue}const c=this.getFieldValidator(o,n);i[o]=this.parseCheckedField(c,this._validatorTypes[n],e[o])}}catch(e){throw new Error(r().objectField(o,e.message))}if(this._config.strict||this._config.passthrough||this._config.catchall){const t=Object.keys(e);if(this._config.strict){const e=[];for(let s=0;s<t.length;s++){const r=t[s];this._shapeKeysSet.has(r)||e.push(r)}if(e.length>0)throw new Error(r().unexpectedKeys(e))}if(this._config.passthrough)for(let s=0;s<t.length;s++){const r=t[s];this._shapeKeysSet.has(r)||n(r)||(i[r]=e[r])}if(this._config.catchall)for(let s=0;s<t.length;s++){const o=t[s];if(!this._shapeKeysSet.has(o)&&!n(o))try{i[o]=this._config.catchall.parse(e[o])}catch(e){throw new Error(r().objectField(o,e.message))}}}return i}safeParse(t){if("object"!=typeof t||null===t||Array.isArray(t))return{success:!1,error:this.createSafeParseError(this._config.errorMessage||r().invalidObject)};const s=t;if(this._canUseSimpleObjectFastPath)try{return{success:!0,data:this.parseSimpleObjectValue(s)}}catch(e){return{success:!1,error:this.createSafeParseError(e.message)}}if(this._canUseSafeParseFastPath)try{return{success:!0,data:this.parseObjectValue(s)}}catch(e){return{success:!1,error:this.createSafeParseError(e.message)}}const i={};for(let t=0;t<this._shapeKeys.length;t++){const n=this._shapeKeys[t],o=s[n],a=this._simpleFieldModes[t];if(void 0!==a){if("string"===a&&"string"==typeof o||"number"===a&&"number"==typeof o&&!isNaN(o)||"boolean"===a&&"boolean"==typeof o||"bigint"===a&&"bigint"==typeof o||"symbol"===a&&"symbol"==typeof o||"null"===a&&null===o||"undefinedValue"===a&&void 0===o||"literal"===a&&o===this._simpleFieldValues[t]||"passthrough"===a){i[n]="literal"===a?this._simpleFieldValues[t]:"null"===a?null:o;continue}return{success:!1,error:this.createSafeParseError(r().objectField(n,this.getSimpleFieldError(a,this._simpleFieldValues[t],o)))}}let c;try{c=this.getFieldValidator(n,t)}catch(e){const t=e instanceof Error?e.message:String(e);return{success:!1,error:this.createSafeParseError(r().objectField(n,t))}}try{if(c instanceof e)i[n]=this.parseCheckedField(c,this._validatorTypes[t],o);else{const e=c.safeParse(o);if(!e.success)return{success:!1,error:this.createSafeParseError(r().objectField(n,e.error.message))};i[n]=e.data}}catch(e){const t=e instanceof Error?e.message:String(e);return{success:!1,error:this.createSafeParseError(r().objectField(n,t))}}}if(this._config.strict||this._config.passthrough||this._config.catchall){const t=Object.keys(s);if(this._config.strict){const e=[];for(let s=0;s<t.length;s++){const r=t[s];this._shapeKeysSet.has(r)||e.push(r)}if(e.length>0)return{success:!1,error:this.createSafeParseError(r().unexpectedKeys(e))}}if(this._config.passthrough)for(let e=0;e<t.length;e++){const r=t[e];this._shapeKeysSet.has(r)||n(r)||(i[r]=s[r])}if(this._config.catchall){const o=this._config.catchall;for(let a=0;a<t.length;a++){const c=t[a];if(!this._shapeKeysSet.has(c)&&!n(c))try{if(o instanceof e)i[c]=o.parse(s[c]);else{const e=o.safeParse(s[c]);if(!e.success)return{success:!1,error:this.createSafeParseError(r().objectField(c,e.error.message))};i[c]=e.data}}catch(e){const t=e instanceof Error?e.message:String(e);return{success:!1,error:this.createSafeParseError(r().objectField(c,t))}}}}}return{success:!0,data:i}}encode(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this._config.errorMessage||r().invalidObject);return this.encodeObjectSync(e)}safeEncode(e){try{return{success:!0,data:this.encode(e)}}catch(e){return{success:!1,error:this.createSafeParseError(e.message)}}}async encodeAsync(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this._config.errorMessage||r().invalidObject);return this.encodeObjectAsync(e)}async safeEncodeAsync(e){try{return{success:!0,data:await this.encodeAsync(e)}}catch(e){return{success:!1,error:this.createSafeParseError(e.message)}}}encodeObjectSync(e){const t={};for(let s=0;s<this._shapeKeys.length;s++){const r=this._shapeKeys[s],i=this.getFieldValidator(r,s).encode(e[r]);(void 0!==i||Object.prototype.hasOwnProperty.call(e,r))&&(t[r]=i)}return this.encodeExtraKeysSync(e,t),t}async encodeObjectAsync(e){const t={};for(let s=0;s<this._shapeKeys.length;s++){const r=this._shapeKeys[s],i=await this.getFieldValidator(r,s).encodeAsync(e[r]);(void 0!==i||Object.prototype.hasOwnProperty.call(e,r))&&(t[r]=i)}const s=this.getEncodedExtraKeys(e);for(const r of s)n(r)||(this._config.catchall?t[r]=await this._config.catchall.encodeAsync(e[r]):this._config.passthrough&&(t[r]=e[r]));return t}getEncodedExtraKeys(e){const t=Object.keys(e).filter(e=>!this._shapeKeysSet.has(e));if(this._config.strict&&t.length>0)throw new Error(r().unexpectedKeys(t));return t}encodeExtraKeysSync(e,t){for(const s of this.getEncodedExtraKeys(e))n(s)||(this._config.catchall?t[s]=this._config.catchall.encode(e[s]):this._config.passthrough&&(t[s]=e[s]))}strict(e){return new VldObject({...this._config,strict:!0,passthrough:!1,errorMessage:e})}passthrough(){return new VldObject({...this._config,strict:!1,passthrough:!0})}loose(){return this.passthrough()}strip(){const e={...this._config,strict:!1,passthrough:!1};return delete e.catchall,new VldObject(e)}partial(){const e={};for(const t in this._config.shape)e[t]=new s(this._config.shape[t]);return new VldObject({...this._config,shape:e})}deepPartial(){const e={};for(const t in this._config.shape){const r=this._config.shape[t];e[t]=new s(r instanceof VldObject?r.deepPartial():r)}return new VldObject({...this._config,shape:e})}pick(...e){const t={};for(const s of e)s in this._config.shape&&(t[s]=this._config.shape[s]);return new VldObject({...this._config,shape:t})}omit(...e){const t={},s=new Set(e);for(const e in this._config.shape)s.has(e)||(t[e]=this._config.shape[e]);return new VldObject({...this._config,shape:t})}extend(e){return new VldObject({...this._config,shape:{...this._config.shape,...e}})}merge(e){return new VldObject({...this._config,shape:{...this._config.shape,...e.config.shape}})}required(){const e={};for(const t in this._config.shape){const r=this._config.shape[t];if(r instanceof s){const s=r.baseValidator;if(!s||"function"!=typeof s.parse)throw new Error(`Invalid VldOptional structure for field "${t}": missing or invalid baseValidator`);e[t]=s}else e[t]=r}return new VldObject({...this._config,shape:e})}catchall(e){return new VldObject({...this._config,catchall:e,passthrough:!1})}get shape(){return this._config.shape}keyof(){const e=Object.keys(this._config.shape);if(0===e.length)throw new Error("Cannot create keyof enum from empty object");return i.create(e)}safeExtend(e){const t=new Set(Object.keys(this._config.shape)),s=Object.keys(e),i=[];for(const e of s)t.has(e)&&i.push(e);if(i.length>0)throw new Error(`safeExtend: ${r().safeExtendOverlap(i)}`);return new VldObject({...this._config,shape:{...this._config.shape,...e}})}}export{VldObject};
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as t,VldOptional as s,VldExactOptional as i}from"./base.js";import{getMessages as r}from"../locales/runtime.js";import{VldEnum as n}from"./enum.js";import{i as o}from"../chunks/security-Dy24T8N7.js";import{V as a}from"../chunks/errors-core-CerMg2rq.js";class VldObject extends e{createSafeParseError(e,t){if(e instanceof a)return void 0!==t?new a(e.issues.map(e=>({...e,path:e.path?[t,...e.path]:[t],message:e.message.startsWith("Invalid field")?e.message:r().objectField(String(t),e.message)}))):e;const s=e instanceof Error?e.message:String(e);return new a([{code:"invalid_type",path:void 0!==t?[t]:[],message:void 0===t||s.startsWith("Invalid field")?s:r().objectField(String(t),s)}])}constructor(s){super(t.OBJECT),this._config=s,this._shapeKeys=Object.keys(s.shape),this._shapeKeysSet=new Set(this._shapeKeys),this._validators=this._shapeKeys.map(e=>this.tryGetFieldValidator(e)),this._validatorTypes=this._shapeKeys.map((e,t)=>this._validators[t]?.validatorType||this.getValidatorType(e)),this._simpleFieldModes=this._validators.map((e,t)=>this.getSimpleFieldMode(e,this._validatorTypes[t])),this._simpleFieldValues=this._validators.map((e,t)=>"literal"===this._simpleFieldModes[t]?e.literal:void 0),this._canUseSimpleObjectFastPath=!s.strict&&!s.passthrough&&!s.catchall&&this._shapeKeys.length>0&&this._simpleFieldModes.every(e=>void 0!==e),this._canUseSafeParseFastPath=this._validators.every(t=>t instanceof e)&&(void 0===s.catchall||s.catchall instanceof e)}tryGetFieldValidator(e){try{const t=Object.getOwnPropertyDescriptor(this._config.shape,e);if(t?.get)return;return this.resolveFieldValidator(e)}catch{return}}resolveFieldValidator(e){try{const t=this._config.shape[e];if(!t||"function"!=typeof t.safeParse)return;return t}catch{return}}getFieldValidator(e,t){const s=(void 0===t?void 0:this._validators[t])||this.resolveFieldValidator(e);if(!s)throw new Error(`Invalid validator for field "${e}"`);return s}getValidatorType(e){try{const s=this._config.shape[e];return s?.validatorType||t.UNKNOWN}catch{return t.UNKNOWN}}getSimpleFieldMode(e,s){if(e&&!0===e.isSimple)switch(s){case t.STRING:return"string";case t.NUMBER:return"number";case t.BOOLEAN:return"boolean";case t.BIGINT:return"bigint";case t.SYMBOL:return"symbol";case t.NULL:return"null";case t.UNDEFINED:case t.VOID:return"undefinedValue";case t.LITERAL:return"literal";case t.ANY:case t.UNKNOWN:return"passthrough";default:return}}getSimpleFieldError(e,t,s){switch(e){case"string":return r().invalidString;case"number":return r().invalidNumber;case"boolean":return r().invalidBoolean;case"bigint":return r().invalidBigint;case"symbol":return r().invalidSymbol;case"null":return"Expected null, received "+typeof s;case"undefinedValue":return r().expectedUndefined;case"literal":return r().literalExpected(JSON.stringify(t),JSON.stringify(s));default:return r().invalidObject}}parseCheckedField(e,s,i){if(s===t.STRING&&"string"==typeof i){const t=e.parseKnownString;if("function"==typeof t)return t.call(e,i)}if(s===t.NUMBER&&"number"==typeof i&&!isNaN(i)){const t=e.parseKnownNumber;if("function"==typeof t)return t.call(e,i)}if(s===t.BOOLEAN&&"boolean"==typeof i){const t=e.parseKnownBoolean;if("function"==typeof t)return t.call(e,i)}if(s===t.BIGINT&&"bigint"==typeof i){const t=e.parseKnownBigInt;if("function"==typeof t)return t.call(e,i)}if(s===t.SYMBOL&&"symbol"==typeof i){const t=e.parseKnownSymbol;if("function"==typeof t)return t.call(e,i)}if(s===t.FUNCTION&&"function"==typeof i){const t=e.parseKnownFunction;if("function"==typeof t)return t.call(e,i)}if(s===t.FILE&&"object"==typeof i&&null!==i&&("size"in i&&"type"in i||"undefined"!=typeof File&&i instanceof File)){const t=e.parseKnownFile;if("function"==typeof t)return t.call(e,i)}if(s===t.DATE&&i instanceof Date){const t=e.parseKnownDate;if("function"==typeof t)return t.call(e,i)}if(s===t.OBJECT&&"object"==typeof i&&null!==i&&!Array.isArray(i)){const t=e.parseKnownObject;if("function"==typeof t)return t.call(e,i)}if(s===t.ARRAY&&Array.isArray(i)){const t=e.parseKnownArray;if("function"==typeof t)return t.call(e,i)}if(s===t.TUPLE&&Array.isArray(i)){const t=e.parseKnownTuple;if("function"==typeof t)return t.call(e,i)}if(s===t.RECORD&&"object"==typeof i&&null!==i&&!Array.isArray(i)){const t=e.parseKnownRecord;if("function"==typeof t)return t.call(e,i)}if(s===t.SET&&i instanceof Set){const t=e.parseKnownSet;if("function"==typeof t)return t.call(e,i)}if(s===t.MAP&&i instanceof Map){const t=e.parseKnownMap;if("function"==typeof t)return t.call(e,i)}return e.parse(i)}parseSimpleObjectValue(e,t,s=!1){if(2===this._shapeKeys.length&&"string"===this._simpleFieldModes[0]&&"number"===this._simpleFieldModes[1]){const t=this._shapeKeys[0],s=e[t];if("string"!=typeof s)throw new Error(r().objectField(t,r().invalidString));const i=this._shapeKeys[1],n=e[i];if("number"!=typeof n||isNaN(n))throw new Error(r().objectField(i,r().invalidNumber));const o={};return o[t]=s,o[i]=n,o}if(3===this._shapeKeys.length&&"literal"===this._simpleFieldModes[0]&&"string"===this._simpleFieldModes[1]&&"number"===this._simpleFieldModes[2]){const i=this._shapeKeys[0],n=e[i],o=this._simpleFieldValues[0];if((!s||i!==t)&&n!==o)throw new Error(r().objectField(i,this.getSimpleFieldError("literal",o,n)));const a=this._shapeKeys[1],c=e[a];if("string"!=typeof c)throw new Error(r().objectField(a,r().invalidString));const l=this._shapeKeys[2],h=e[l];if("number"!=typeof h||isNaN(h))throw new Error(r().objectField(l,r().invalidNumber));const f={};return f[i]=o,f[a]=c,f[l]=h,f}const i={};for(let n=0;n<this._shapeKeys.length;n++){const o=this._shapeKeys[n],a=e[o],c=this._simpleFieldModes[n];switch(c){case"string":if("string"!=typeof a)throw new Error(r().objectField(o,r().invalidString));i[o]=a;break;case"number":if("number"!=typeof a||isNaN(a))throw new Error(r().objectField(o,r().invalidNumber));i[o]=a;break;case"boolean":if("boolean"!=typeof a)throw new Error(r().objectField(o,r().invalidBoolean));i[o]=a;break;case"bigint":if("bigint"!=typeof a)throw new Error(r().objectField(o,r().invalidBigint));i[o]=a;break;case"symbol":if("symbol"!=typeof a)throw new Error(r().objectField(o,r().invalidSymbol));i[o]=a;break;case"null":if(null!==a)throw new Error(r().objectField(o,this.getSimpleFieldError(c,void 0,a)));i[o]=null;break;case"undefinedValue":if(void 0!==a)throw new Error(r().objectField(o,r().expectedUndefined));i[o]=void 0;break;case"literal":if(s&&o===t){i[o]=this._simpleFieldValues[n];break}if(a!==this._simpleFieldValues[n])throw new Error(r().objectField(o,this.getSimpleFieldError(c,this._simpleFieldValues[n],a)));i[o]=this._simpleFieldValues[n];break;case"passthrough":i[o]=a;break;default:throw new Error(r().objectField(o,r().invalidObject))}}return i}get config(){return this._config}get shapeKeys(){return this._shapeKeys}get shapeKeysSet(){return this._shapeKeysSet}static create(e){return new VldObject({shape:e})}parse(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this._config.errorMessage||r().invalidObject);return this.parseObjectValue(e)}parseKnownObject(e,t){return this.parseObjectValue(e,t)}parseTrustedKnownObject(e,t){return this.parseObjectValue(e,t,!0)}parseObjectValue(e,t,s=!1){if(this._canUseSimpleObjectFastPath)return this.parseSimpleObjectValue(e,t,s);const i={};let n="";try{for(let o=0;o<this._shapeKeys.length;o++){if(n=this._shapeKeys[o],s&&n===t&&"literal"===this._simpleFieldModes[o]){i[n]=this._simpleFieldValues[o];continue}const a=this._simpleFieldModes[o];if(void 0!==a){const t=e[n];switch(a){case"string":if("string"!=typeof t)throw new Error(r().invalidString);i[n]=t;continue;case"number":if("number"!=typeof t||isNaN(t))throw new Error(r().invalidNumber);i[n]=t;continue;case"boolean":if("boolean"!=typeof t)throw new Error(r().invalidBoolean);i[n]=t;continue;case"bigint":if("bigint"!=typeof t)throw new Error(r().invalidBigint);i[n]=t;continue;case"symbol":if("symbol"!=typeof t)throw new Error(r().invalidSymbol);i[n]=t;continue;case"null":if(null!==t)throw new Error(this.getSimpleFieldError(a,void 0,t));i[n]=null;continue;case"undefinedValue":if(void 0!==t)throw new Error(r().expectedUndefined);i[n]=void 0;continue;case"literal":if(t!==this._simpleFieldValues[o])throw new Error(this.getSimpleFieldError(a,this._simpleFieldValues[o],t));i[n]=this._simpleFieldValues[o];continue;case"passthrough":i[n]=t;continue}continue}const c=this.getFieldValidator(n,o);i[n]=this.parseCheckedField(c,this._validatorTypes[o],e[n])}}catch(e){if(e instanceof a)throw new a(e.issues.map(e=>({...e,path:e.path?[n,...e.path]:[n],message:r().objectField(n,e.message.startsWith("Invalid field")?e.message.replace(/^Invalid field "[^"]+": /,""):e.message)})));const t=e instanceof Error?e.message:String(e);throw new a([{code:"invalid_type",path:[n],message:t.startsWith("Invalid field")?t:r().objectField(n,t)}])}if(this._config.strict||this._config.passthrough||this._config.catchall){const t=Object.keys(e);if(this._config.strict){const e=[];for(let s=0;s<t.length;s++){const i=t[s];this._shapeKeysSet.has(i)||e.push(i)}if(e.length>0)throw new Error(r().unexpectedKeys(e))}if(this._config.passthrough)for(let s=0;s<t.length;s++){const r=t[s];this._shapeKeysSet.has(r)||o(r)||(i[r]=e[r])}if(this._config.catchall)for(let s=0;s<t.length;s++){const n=t[s];if(!this._shapeKeysSet.has(n)&&!o(n))try{i[n]=this._config.catchall.parse(e[n])}catch(e){throw new Error(r().objectField(n,e.message))}}}return i}safeParse(t){if("object"!=typeof t||null===t||Array.isArray(t))return{success:!1,error:this.createSafeParseError(this._config.errorMessage||r().invalidObject)};const s=t;if(this._canUseSimpleObjectFastPath)try{return{success:!0,data:this.parseSimpleObjectValue(s)}}catch{}if(this._canUseSafeParseFastPath)try{return{success:!0,data:this.parseObjectValue(s)}}catch{}const i={},n=[];for(let t=0;t<this._shapeKeys.length;t++){const o=this._shapeKeys[t],a=s[o],c=this._simpleFieldModes[t];if(void 0!==c){if("string"===c&&"string"==typeof a||"number"===c&&"number"==typeof a&&!isNaN(a)||"boolean"===c&&"boolean"==typeof a||"bigint"===c&&"bigint"==typeof a||"symbol"===c&&"symbol"==typeof a||"null"===c&&null===a||"undefinedValue"===c&&void 0===a||"literal"===c&&a===this._simpleFieldValues[t]||"passthrough"===c){i[o]="literal"===c?this._simpleFieldValues[t]:"null"===c?null:a;continue}n.push({code:"invalid_type",path:[o],message:r().objectField(o,this.getSimpleFieldError(c,this._simpleFieldValues[t],a))});continue}let l;try{l=this.getFieldValidator(o,t)}catch(e){const t=this.createSafeParseError(e,o);n.push(...t.issues);continue}try{if(l instanceof e)i[o]=this.parseCheckedField(l,this._validatorTypes[t],a);else{const e=l.safeParse(a);if(e.success)i[o]=e.data;else{const t=this.createSafeParseError(e.error,o);n.push(...t.issues)}}}catch(e){const t=this.createSafeParseError(e,o);n.push(...t.issues)}}if(this._config.strict||this._config.passthrough||this._config.catchall){const t=Object.keys(s);if(this._config.strict){const e=[];for(let s=0;s<t.length;s++){const i=t[s];this._shapeKeysSet.has(i)||e.push(i)}e.length>0&&n.push(...e.map(e=>({code:"unrecognized_keys",path:[e],message:r().unexpectedKeys([e])})))}if(this._config.passthrough)for(let e=0;e<t.length;e++){const r=t[e];this._shapeKeysSet.has(r)||o(r)||(i[r]=s[r])}if(this._config.catchall){const r=this._config.catchall;for(let a=0;a<t.length;a++){const c=t[a];if(!this._shapeKeysSet.has(c)&&!o(c))try{if(r instanceof e)i[c]=r.parse(s[c]);else{const e=r.safeParse(s[c]);if(e.success)i[c]=e.data;else{const t=this.createSafeParseError(e.error,c);n.push(...t.issues)}}}catch(e){const t=this.createSafeParseError(e,c);n.push(...t.issues)}}}}return n.length>0?{success:!1,error:new a(n)}:{success:!0,data:i}}encode(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this._config.errorMessage||r().invalidObject);return this.encodeObjectSync(e)}safeEncode(e){try{return{success:!0,data:this.encode(e)}}catch(e){return{success:!1,error:this.createSafeParseError(e.message)}}}async encodeAsync(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this._config.errorMessage||r().invalidObject);return this.encodeObjectAsync(e)}async safeEncodeAsync(e){try{return{success:!0,data:await this.encodeAsync(e)}}catch(e){return{success:!1,error:this.createSafeParseError(e.message)}}}encodeObjectSync(e){const t={};for(let s=0;s<this._shapeKeys.length;s++){const i=this._shapeKeys[s],r=this.getFieldValidator(i,s).encode(e[i]);(void 0!==r||Object.prototype.hasOwnProperty.call(e,i))&&(t[i]=r)}return this.encodeExtraKeysSync(e,t),t}async encodeObjectAsync(e){const t={};for(let s=0;s<this._shapeKeys.length;s++){const i=this._shapeKeys[s],r=await this.getFieldValidator(i,s).encodeAsync(e[i]);(void 0!==r||Object.prototype.hasOwnProperty.call(e,i))&&(t[i]=r)}const s=this.getEncodedExtraKeys(e);for(const i of s)o(i)||(this._config.catchall?t[i]=await this._config.catchall.encodeAsync(e[i]):this._config.passthrough&&(t[i]=e[i]));return t}getEncodedExtraKeys(e){const t=Object.keys(e).filter(e=>!this._shapeKeysSet.has(e));if(this._config.strict&&t.length>0)throw new Error(r().unexpectedKeys(t));return t}encodeExtraKeysSync(e,t){for(const s of this.getEncodedExtraKeys(e))o(s)||(this._config.catchall?t[s]=this._config.catchall.encode(e[s]):this._config.passthrough&&(t[s]=e[s]))}strict(e){return new VldObject({...this._config,strict:!0,passthrough:!1,errorMessage:e})}passthrough(){return new VldObject({...this._config,strict:!1,passthrough:!0})}loose(){return this.passthrough()}strip(){const e={...this._config,strict:!1,passthrough:!1};return delete e.catchall,new VldObject(e)}partial(){const e={};for(const t in this._config.shape)e[t]=new s(this._config.shape[t]);return new VldObject({...this._config,shape:e})}deepPartial(){const e={};for(const t in this._config.shape){const i=this._config.shape[t];e[t]=new s(i instanceof VldObject?i.deepPartial():i)}return new VldObject({...this._config,shape:e})}exactPartial(){const e={};for(const t in this._config.shape)e[t]=new i(this._config.shape[t]);return new VldObject({...this._config,shape:e})}pick(...e){const t={};let s=[];s=1!==e.length||"object"!=typeof e[0]||null===e[0]||Array.isArray(e[0])?e.flat():Object.keys(e[0]).filter(t=>e[0][t]);for(const e of s)e in this._config.shape&&(t[e]=this._config.shape[e]);return new VldObject({...this._config,shape:t})}omit(...e){let t;t=1!==e.length||"object"!=typeof e[0]||null===e[0]||Array.isArray(e[0])?new Set(e.flat()):new Set(Object.keys(e[0]).filter(t=>e[0][t]));const s={};for(const e in this._config.shape)t.has(e)||(s[e]=this._config.shape[e]);return new VldObject({...this._config,shape:s})}extend(e){return new VldObject({...this._config,shape:{...this._config.shape,...e}})}merge(e){return new VldObject({...this._config,shape:{...this._config.shape,...e.config.shape}})}required(){const e={};for(const t in this._config.shape){const i=this._config.shape[t];if(i instanceof s){const s=i.baseValidator;if(!s||"function"!=typeof s.parse)throw new Error(`Invalid VldOptional structure for field "${t}": missing or invalid baseValidator`);e[t]=s}else e[t]=i}return new VldObject({...this._config,shape:e})}catchall(e){return new VldObject({...this._config,catchall:e,passthrough:!1})}get shape(){return this._config.shape}keyof(){const e=Object.keys(this._config.shape);if(0===e.length)throw new Error("Cannot create keyof enum from empty object");return n.create(e)}safeExtend(e){const t=new Set(Object.keys(this._config.shape)),s=Object.keys(e),i=[];for(const e of s)t.has(e)&&i.push(e);if(i.length>0)throw new Error(`safeExtend: ${r().safeExtendOverlap(i)}`);return new VldObject({...this._config,shape:{...this._config.shape,...e}})}}export{VldObject};
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Promise validator - validates Promise values
|
|
3
3
|
* Validates that the resolved value matches the inner schema
|
|
4
4
|
*/
|
|
5
|
-
import { type ParseResult, type StandardSchemaV1Props } from './base.js';
|
|
5
|
+
import { VldBase, type ParseResult, type StandardSchemaV1Props } from './base.js';
|
|
6
6
|
type PromiseInner<T> = {
|
|
7
7
|
parse(value: unknown): T;
|
|
8
8
|
safeParse(value: unknown): ParseResult<T>;
|
|
@@ -18,11 +18,10 @@ type PromiseInner<T> = {
|
|
|
18
18
|
*
|
|
19
19
|
* Use parseAsync() or safeParseAsync() for proper async handling.
|
|
20
20
|
*/
|
|
21
|
-
export declare class VldPromise<T> {
|
|
21
|
+
export declare class VldPromise<T> extends VldBase<unknown, Promise<T>> {
|
|
22
22
|
private readonly inner;
|
|
23
|
-
readonly validatorType: "promise";
|
|
24
23
|
constructor(inner: PromiseInner<T>);
|
|
25
|
-
get '~standard'(): StandardSchemaV1Props<unknown,
|
|
24
|
+
get '~standard'(): StandardSchemaV1Props<unknown, any>;
|
|
26
25
|
/**
|
|
27
26
|
* Check if value is thenable (Promise-like)
|
|
28
27
|
* Must be called BEFORE wrapping in Promise.resolve
|
|
@@ -36,14 +35,14 @@ export declare class VldPromise<T> {
|
|
|
36
35
|
* @throws {Error} If validation fails when Promise resolves
|
|
37
36
|
*/
|
|
38
37
|
parse(value: unknown): Promise<T>;
|
|
39
|
-
parseAsync(value: unknown): Promise<T
|
|
38
|
+
parseAsync(value: unknown): Promise<Promise<T>>;
|
|
40
39
|
/**
|
|
41
40
|
* Safely parse and validate a Promise value asynchronously
|
|
42
41
|
* @param value The Promise to validate
|
|
43
42
|
* @returns A Promise resolving to ParseResult containing the validated value
|
|
44
43
|
*/
|
|
45
|
-
safeParse(value: unknown):
|
|
46
|
-
safeParseAsync(value: unknown): Promise<ParseResult<T
|
|
44
|
+
safeParse(value: unknown): any;
|
|
45
|
+
safeParseAsync(value: unknown): Promise<ParseResult<Promise<T>>>;
|
|
47
46
|
}
|
|
48
47
|
/**
|
|
49
48
|
* Create a Promise validator
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VLD_VALIDATOR_TYPES as
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as s,ensureVldError as r}from"./base.js";class VldPromise extends e{constructor(e){super(s.PROMISE),this.inner=e}get"~standard"(){return{version:1,vendor:"vld",validate:async e=>{const s=await this.safeParse(e);return s.success?{value:s.data}:{issues:[{message:s.error.message}]}},types:void 0}}_isThenable(e){return null!==e&&"function"==typeof e.then}unwrap(){return this.inner}async parse(e){if(!this._isThenable(e))throw new Error("Expected a Promise value");const s=await Promise.resolve(e);return this.inner.parseAsync?this.inner.parseAsync(s):this.inner.parse(s)}parseAsync(e){return this.parse(e)}safeParse(e){return this._isThenable(e)?(async()=>{try{const s=await Promise.resolve(e);if(this.inner.safeParseAsync)return await this.inner.safeParseAsync(s);const r=this.inner.safeParse(s);return r.success?{success:!0,data:r.data}:r}catch(e){return{success:!1,error:r(e)}}})():Promise.resolve({success:!1,error:r("Expected a Promise value")})}safeParseAsync(e){return this.safeParse(e)}}function n(e){return new VldPromise(e)}export{VldPromise,n as promise};
|
|
@@ -15,6 +15,8 @@ export declare class VldRecord<T, K extends PropertyKey = string> extends VldBas
|
|
|
15
15
|
private readonly _simpleValue;
|
|
16
16
|
get valueSchema(): VldBase<unknown, T>;
|
|
17
17
|
get keySchema(): VldBase<unknown, K> | undefined;
|
|
18
|
+
get valueType(): VldBase<unknown, T>;
|
|
19
|
+
get keyType(): VldBase<unknown, K> | undefined;
|
|
18
20
|
/**
|
|
19
21
|
* Create a new record validator
|
|
20
22
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{getMessages as t}from"../locales/runtime.js";import{i}from"../chunks/security-Dy24T8N7.js";import{V as
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{getMessages as t}from"../locales/runtime.js";import{i}from"../chunks/security-Dy24T8N7.js";import{V as a}from"../chunks/errors-core-CerMg2rq.js";function o(e){return new a([{code:"invalid_object",path:[],message:e}])}class VldRecord extends e{constructor(e,t,i){super(r.RECORD),this.valueValidator=e,this.keyValidator=t,this.errorMessage=i,this._simpleValueMode=this.getSimpleValueMode(e),this._simpleValue="literal"===this._simpleValueMode?e.literal:void 0}get valueSchema(){return this.valueValidator}get keySchema(){return this.keyValidator}get valueType(){return this.valueValidator}get keyType(){return this.keyValidator}static create(e,r){return new VldRecord(e,r)}getSimpleValueMode(e){if(!0===e.isSimple)switch(e.validatorType){case r.STRING:return"string";case r.NUMBER:return"number";case r.BOOLEAN:return"boolean";case r.BIGINT:return"bigint";case r.SYMBOL:return"symbol";case r.NULL:return"null";case r.UNDEFINED:case r.VOID:return"undefinedValue";case r.LITERAL:return"literal";case r.ANY:case r.UNKNOWN:return"passthrough";default:return}}getSimpleValueError(e){switch(this._simpleValueMode){case"string":return t().invalidString;case"number":return t().invalidNumber;case"boolean":return t().invalidBoolean;case"bigint":return t().invalidBigint;case"symbol":return t().invalidSymbol;case"null":return"Expected null, received "+typeof e;case"undefinedValue":return t().expectedUndefined;case"literal":return t().literalExpected(JSON.stringify(this._simpleValue),JSON.stringify(e));default:return t().invalidRecord}}parse(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this.errorMessage||t().invalidRecord);return this.parseKnownRecord(e)}parseKnownRecord(e){if(void 0!==this.keyValidator)return this.parseKeyedRecord(e);const r={},a=Object.keys(e),o=this._simpleValueMode;for(let s=0;s<a.length;s++){const n=a[s];if(i(n))continue;const l=e[n];if(void 0!==o)switch(o){case"string":if("string"!=typeof l)throw new Error(t().objectField(n,t().invalidString));r[n]=l;continue;case"number":if("number"!=typeof l||isNaN(l))throw new Error(t().objectField(n,t().invalidNumber));r[n]=l;continue;case"boolean":if("boolean"!=typeof l)throw new Error(t().objectField(n,t().invalidBoolean));r[n]=l;continue;case"bigint":if("bigint"!=typeof l)throw new Error(t().objectField(n,t().invalidBigint));r[n]=l;continue;case"symbol":if("symbol"!=typeof l)throw new Error(t().objectField(n,t().invalidSymbol));r[n]=l;continue;case"null":if(null!==l)throw new Error(t().objectField(n,this.getSimpleValueError(l)));r[n]=null;continue;case"undefinedValue":if(void 0!==l)throw new Error(t().objectField(n,t().expectedUndefined));r[n]=void 0;continue;case"literal":if(l!==this._simpleValue)throw new Error(t().objectField(n,this.getSimpleValueError(l)));r[n]=this._simpleValue;continue;case"passthrough":r[n]=l;continue}try{r[n]=this.valueValidator.parse(l)}catch(e){throw new Error(t().objectField(n,e.message))}}return r}parseKeyedRecord(e){const r={},o=Reflect.ownKeys(e);for(const s of o){if(!Object.prototype.propertyIsEnumerable.call(e,s))continue;if("string"==typeof s&&i(s))continue;const o=this.keyValidator.safeParse(s);if(!o.success)throw new a([{code:"invalid_key",path:[String(s)],message:o.error.message}]);if("string"!=typeof o.data&&"number"!=typeof o.data&&"symbol"!=typeof o.data)throw new a([{code:"invalid_key",path:[String(s)],message:"Record key transform must return a property key"}]);if("string"!=typeof o.data||!i(o.data))try{r[o.data]=this.valueValidator.parse(e[s])}catch(e){throw new Error(t().objectField(String(s),e.message))}}return r}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return e instanceof a?{success:!1,error:e}:{success:!1,error:o(e.message)}}}partial(){const e=this.valueValidator.optional();return new VldRecord(e,this.keyValidator)}loose(){return new VldLooseRecord(this.valueValidator,this.keyValidator)}}class VldLooseRecord extends e{constructor(e,t){super(r.RECORD),this.valueValidator=e,this.keyValidator=t}get valueSchema(){return this.valueValidator}parse(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(t().invalidRecord);const r={},a=e;for(const e of Reflect.ownKeys(a)){if(!Object.prototype.propertyIsEnumerable.call(a,e))continue;if("string"==typeof e&&i(e))continue;const t=this.keyValidator?.safeParse(e);if(t&&!t.success)continue;const o=t?.data??e;if("string"!=typeof o&&"number"!=typeof o&&"symbol"!=typeof o)continue;if("string"==typeof o&&i(o))continue;const s=this.valueValidator.safeParse(a[e]);s.success&&(r[o]=s.data)}return r}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:o(e.message)}}}partial(){const e=this.valueValidator.optional();return new VldLooseRecord(e,this.keyValidator)}loose(){return this}}export{VldRecord};
|
package/dist/validators/set.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { VldBase, ParseResult } from './base.js';
|
|
|
5
5
|
export declare class VldSet<T> extends VldBase<unknown, Set<T>> {
|
|
6
6
|
private readonly itemValidator;
|
|
7
7
|
private readonly errorMessage?;
|
|
8
|
+
private readonly _checks;
|
|
8
9
|
/**
|
|
9
10
|
* Private constructor to enforce immutability
|
|
10
11
|
*/
|
|
@@ -31,4 +32,8 @@ export declare class VldSet<T> extends VldBase<unknown, Set<T>> {
|
|
|
31
32
|
* Safely parse and validate a Set value
|
|
32
33
|
*/
|
|
33
34
|
safeParse(value: unknown): ParseResult<Set<T>>;
|
|
35
|
+
min(size: number, message?: string): VldSet<T>;
|
|
36
|
+
max(size: number, message?: string): VldSet<T>;
|
|
37
|
+
size(size: number, message?: string): VldSet<T>;
|
|
38
|
+
nonempty(message?: string): VldSet<T>;
|
|
34
39
|
}
|
package/dist/validators/set.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as t}from"./base.js";import{getMessages as r}from"../locales/runtime.js";import{V as s}from"../chunks/errors-core-CerMg2rq.js";class VldSet extends e{constructor(e,r,s=[]){super(t.SET),this.itemValidator=e,this.errorMessage=r,this._checks=s,this._simpleItemMode=this.getSimpleItemMode(e),this._simpleItemValue="literal"===this._simpleItemMode?e.literal:void 0}get itemSchema(){return this.itemValidator}static create(e){return new VldSet(e)}getSimpleItemMode(e){if(!0===e.isSimple)switch(e.validatorType){case t.STRING:return"string";case t.NUMBER:return"number";case t.BOOLEAN:return"boolean";case t.BIGINT:return"bigint";case t.SYMBOL:return"symbol";case t.NULL:return"null";case t.UNDEFINED:case t.VOID:return"undefinedValue";case t.LITERAL:return"literal";case t.ANY:case t.UNKNOWN:return"passthrough";default:return}}getSimpleItemError(e){switch(this._simpleItemMode){case"string":return r().invalidString;case"number":return r().invalidNumber;case"boolean":return r().invalidBoolean;case"bigint":return r().invalidBigint;case"symbol":return r().invalidSymbol;case"null":return"Expected null, received "+typeof e;case"undefinedValue":return r().expectedUndefined;case"literal":return r().literalExpected(JSON.stringify(this._simpleItemValue),JSON.stringify(e));default:return r().invalidSet}}parse(e){if(!(e instanceof Set))throw new Error(this.errorMessage||r().invalidSet);return this.parseKnownSet(e)}parseKnownSet(e){const t=new Set,r=this._simpleItemMode;if("string"===r)for(const r of e){if("string"!=typeof r)throw new Error(this.getSimpleItemError(r));t.add(r)}else if("number"===r)for(const r of e){if("number"!=typeof r||isNaN(r))throw new Error(this.getSimpleItemError(r));t.add(r)}else if("boolean"===r)for(const r of e){if("boolean"!=typeof r)throw new Error(this.getSimpleItemError(r));t.add(r)}else if("bigint"===r)for(const r of e){if("bigint"!=typeof r)throw new Error(this.getSimpleItemError(r));t.add(r)}else if("symbol"===r)for(const r of e){if("symbol"!=typeof r)throw new Error(this.getSimpleItemError(r));t.add(r)}else if("null"===r)for(const r of e){if(null!==r)throw new Error(this.getSimpleItemError(r));t.add(null)}else if("undefinedValue"===r)for(const r of e){if(void 0!==r)throw new Error(this.getSimpleItemError(r));t.add(void 0)}else if("literal"===r)for(const r of e){if(r!==this._simpleItemValue)throw new Error(this.getSimpleItemError(r));t.add(this._simpleItemValue)}else if("passthrough"===r)for(const r of e)t.add(r);else for(const r of e)try{t.add(this.itemValidator.parse(r))}catch(e){throw new Error(e.message)}for(const e of this._checks)if(!e.fn(t))throw new Error(e.message);return t}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:(t=e.message,new s([{code:"invalid_type",path:[],message:t}]))}}var t}min(e,t){return new VldSet(this.itemValidator,this.errorMessage,[...this._checks,{fn:t=>t.size>=e,message:t||`Set must contain at least ${e} elements`}])}max(e,t){return new VldSet(this.itemValidator,this.errorMessage,[...this._checks,{fn:t=>t.size<=e,message:t||`Set must contain at most ${e} elements`}])}size(e,t){return new VldSet(this.itemValidator,this.errorMessage,[...this._checks,{fn:t=>t.size===e,message:t||`Set must contain exactly ${e} elements`}])}nonempty(e){return this.min(1,e||"Set cannot be empty")}}export{VldSet};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as t,VLD_VALIDATOR_TYPES as e}from"./base.js";import{getMessages as
|
|
1
|
+
import{VldBase as t,VLD_VALIDATOR_TYPES as e,ensureVldError as s}from"./base.js";import{getMessages as r}from"../locales/runtime.js";const i=["true","1","yes","on","y","enabled"],o=["false","0","no","off","n","disabled"];class VldStringBool extends t{constructor(t){super(e.STRING_BOOL),this.options=t,this.truthyValues=t.truthy??i,this.falsyValues=t.falsy??o;const s=this.normalizeValues(this.truthyValues),r=this.normalizeValues(this.falsyValues);this.normalizedTruthySet=new Set(s),this.normalizedFalsySet=new Set(r),this.validValuesText=[...s,...r].join(", ")}static create(t={}){return new VldStringBool(t)}normalizeValue(t){return this.options.caseSensitive?t:t.toLowerCase()}normalizeValues(t){return this.options.caseSensitive?t:t.map(t=>t.toLowerCase())}parse(t){if("string"!=typeof t){if("boolean"==typeof t)return t;throw new Error(r().stringExpected(typeof t,"string"))}const e=this.normalizeValue(t);if(this.normalizedTruthySet.has(e))return!0;if(this.normalizedFalsySet.has(e))return!1;throw new Error(r().stringBoolExpected(this.validValuesText,t))}safeParse(t){try{return{success:!0,data:this.parse(t)}}catch(t){return{success:!1,error:s(t)}}}withTruthy(t){return new VldStringBool({...this.options,truthy:t})}withFalsy(t){return new VldStringBool({...this.options,falsy:t})}caseSensitive(){return new VldStringBool({...this.options,caseSensitive:!0})}caseInsensitive(){return new VldStringBool({...this.options,caseSensitive:!1})}}export{VldStringBool};
|
|
@@ -28,6 +28,7 @@ declare function stringRegex(options?: {
|
|
|
28
28
|
declare function macRegex(delimiter?: string): RegExp;
|
|
29
29
|
type StaticRegexName = 'base64' | 'base64url' | 'bigint' | 'boolean' | 'browserEmail' | 'cidrv4' | 'cidrv6' | 'creditCard' | 'cuid' | 'cuid2' | 'date' | 'domain' | 'duration' | 'e164' | 'email' | 'extendedDuration' | 'guid' | 'hex' | 'hostname' | 'html5Email' | 'httpProtocol' | 'httpUrl' | 'idnEmail' | 'integer' | 'ipv4' | 'ipv6' | 'jwt' | 'ksuid' | 'lowercase' | 'md5' | 'md5_base64' | 'md5_base64url' | 'md5_hex' | 'nanoid' | 'null' | 'number' | 'rfc5322Email' | 'sha1' | 'sha1_base64' | 'sha1_base64url' | 'sha1_hex' | 'sha256' | 'sha256_base64' | 'sha256_base64url' | 'sha256_hex' | 'sha384' | 'sha384_base64' | 'sha384_base64url' | 'sha384_hex' | 'sha512' | 'sha512_base64' | 'sha512_base64url' | 'sha512_hex' | 'ulid' | 'undefined' | 'unicodeEmail' | 'uppercase' | 'uuid4' | 'uuid6' | 'uuid7' | 'xid';
|
|
30
30
|
export type RegexNamespace = Readonly<Record<StaticRegexName, RegExp> & {
|
|
31
|
+
nanoidOfLength: (length: number) => RegExp;
|
|
31
32
|
datetime: typeof dateTimeRegex;
|
|
32
33
|
emoji: () => RegExp;
|
|
33
34
|
mac: typeof macRegex;
|