@oxog/vld 3.0.4 → 3.0.5
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 +985 -878
- package/README.md +28 -11
- package/dist/chunks/index-Bn85LHAC.js +1 -0
- package/dist/cjs/chunks/index-DJwZFerZ.cjs +1 -0
- package/dist/cjs/cli/bin.cjs +1 -1
- package/dist/cjs/compile.cjs +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/locales/index.cjs +1 -1
- package/dist/cjs/locales/tg.cjs +1 -0
- 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/base.cjs +1 -1
- package/dist/cjs/validators/custom.cjs +1 -1
- package/dist/cjs/validators/promise.cjs +1 -1
- package/dist/cjs/validators/string-formats.cjs +1 -1
- package/dist/cjs/validators/string.cjs +1 -1
- package/dist/cli/bin.js +1 -1
- package/dist/compile.d.ts +15 -0
- package/dist/compile.js +1 -1
- package/dist/index.d.ts +50 -17
- package/dist/index.js +1 -1
- package/dist/locales/index.js +1 -1
- package/dist/locales/tg.d.ts +2 -0
- package/dist/locales/tg.js +1 -0
- package/dist/utils/json-schema.d.ts +4 -0
- package/dist/v3/index.js +1 -1
- package/dist/v4/core/index.d.ts +12 -2
- package/dist/v4/core/index.js +1 -1
- package/dist/v4/index.js +1 -1
- package/dist/v4/locales/index.d.ts +1 -0
- package/dist/v4/locales/index.js +1 -1
- package/dist/v4/mini/index.js +1 -1
- package/dist/v4-mini/index.d.ts +1 -1
- package/dist/v4-mini/index.js +1 -1
- package/dist/validators/array-v2.d.ts +1 -1
- package/dist/validators/base.d.ts +29 -0
- package/dist/validators/base.js +1 -1
- package/dist/validators/bigint-v2.d.ts +1 -1
- package/dist/validators/custom.d.ts +21 -1
- package/dist/validators/custom.js +1 -1
- package/dist/validators/date-v2.d.ts +1 -1
- package/dist/validators/number-v2.d.ts +1 -1
- package/dist/validators/object-v2.d.ts +5 -5
- package/dist/validators/promise.d.ts +7 -0
- package/dist/validators/promise.js +1 -1
- package/dist/validators/string-formats.d.ts +14 -1
- package/dist/validators/string-formats.js +1 -1
- package/dist/validators/string-v2.d.ts +2 -2
- package/dist/validators/string.d.ts +10 -0
- package/dist/validators/string.js +1 -1
- package/dist/validators/union-v2.d.ts +1 -1
- package/package.json +246 -245
- package/dist/chunks/index-CKPStM3V.js +0 -1
- package/dist/cjs/chunks/index-lejEpLfv.cjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("../registry.cjs"),t=require("../chunks/errors-core-C0mA6tfa.cjs");function s(e){if(e instanceof t.VldError)return e;const s=e instanceof Error?e.message:String(e);return new t.VldError([{code:"custom",path:[],message:s}])}const r={STRING:"string",STRING_FORMAT:"stringFormat",STRING_BOOL:"stringBool",NUMBER:"number",BOOLEAN:"boolean",DATE:"date",BIGINT:"bigint",UNDEFINED:"undefined",NULL:"null",UNKNOWN:"unknown",ANY:"any",VOID:"void",NEVER:"never",SYMBOL:"symbol",NAN:"nan",HEX:"hex",BASE64:"base64",UINT8_ARRAY:"uint8Array",COERCE_STRING:"coerceString",COERCE_NUMBER:"coerceNumber",COERCE_BOOLEAN:"coerceBoolean",COERCE_DATE:"coerceDate",COERCE_BIGINT:"coerceBigint",OBJECT:"object",ARRAY:"array",TUPLE:"tuple",SET:"set",MAP:"map",RECORD:"record",UNION:"union",DISCRIMINATED_UNION:"discriminatedUnion",INTERSECTION:"intersection",XOR:"xor",ENUM:"enum",LITERAL:"literal",LAZY:"lazy",CUSTOM:"custom",FUNCTION:"function",FILE:"file",JSON:"json",TEMPLATE_LITERAL:"templateLiteral",PROMISE:"promise",OPTIONAL:"optional",NULLABLE:"nullable",NULLISH:"nullish",EXACT_OPTIONAL:"exactOptional",DEFAULT:"default",CATCH:"catch",REFINE:"refine",TRANSFORM:"transform",PIPE:"pipe",PREPROCESS:"preprocess",SUPER_REFINE:"superRefine",BRAND:"brand",READONLY:"readonly",META:"meta",PREFAULT:"prefault",PREFault:"prefault",CODEC:"codec"};function a(e,t){if("string"==typeof e)return e;if("function"==typeof e){const s=e(void 0);return"string"==typeof s?s:"object"==typeof s&&s?.message?s.message:t}if("object"==typeof e&&null!==e){if("string"==typeof e.error)return e.error;if("function"==typeof e.error)return e.error({})||t;if("string"==typeof e.message)return e.message}return t}function i(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}let n;function o(e){return"function"==typeof e?e():function(e){if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);if(null!==e&&"object"==typeof e){const t=Object.getPrototypeOf(e);if(t===Object.prototype||null===t)return{...e}}return e}(e)}function h(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";default:return}}function l(e,t){switch(e){case"string":return"string"==typeof t?t:void 0;case"number":return"number"!=typeof t||isNaN(t)?void 0:t;case"boolean":return"boolean"==typeof t?t:void 0;case"bigint":return"bigint"==typeof t?t:void 0;case"symbol":return"symbol"==typeof t?t:void 0;default:return}}class VldBase{constructor(e="unknown"){this.validatorType=e}get type(){return this.validatorType}get _def(){return{typeName:"Zod"+this.validatorType.charAt(0).toUpperCase()+this.validatorType.slice(1),...this.config||{}}}get def(){return this._def}get _zod(){return this._def}get"~standard"(){return{version:1,vendor:"vld",validate:e=>{const t=this.safeParse(e);return t.success?{value:t.data}:{issues:[{message:t.error.message}]}},types:void 0}}async parseAsync(e){return this.parse(e)}async safeParseAsync(e){try{return{success:!0,data:await this.parseAsync(e)}}catch(e){return{success:!1,error:s(e)}}}decode(e){return this.parse(e)}safeDecode(e){return this.safeParse(e)}async decodeAsync(e){return this.parseAsync(e)}async safeDecodeAsync(e){return this.safeParseAsync(e)}encode(e){return this.parse(e)}safeEncode(e){const t=this.safeParse(e);return t.success?{success:!0,data:t.data}:t}async encodeAsync(e){return this.parseAsync(e)}async safeEncodeAsync(e){const t=await this.safeParseAsync(e);return t.success?{success:!0,data:t.data}:t}spa(e){return this.safeParseAsync(e)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}clone(){return this}isValid(e){return this.safeParse(e).success}parseOrDefault(e,t){const s=this.safeParse(e);if(s.success)return s.data;const r=this.safeParse(t);if(!r.success)throw new Error(`Invalid default value provided: ${r.error.message}`);return r.data}refine(e,t){return new VldRefine(this,e,t)}superRefine(e){return new VldSuperRefine(this,e)}transform(e){return new VldTransform(this,e)}default(e){return new VldDefault(this,e)}prefault(e){return new VldPrefault(this,e)}nonoptional(e){return new VldRefine(this,e=>void 0!==e,a(e,"Expected non-optional value"))}array(){return n.array(this)}or(e){return n.union(this,e)}and(e){return n.intersection(this,e)}overwrite(e){return new VldTransform(this,e)}with(...e){return new VldSuperRefine(this,(t,s)=>{const r={value:t,issues:[]},a=[];for(const t of e){const e="function"==typeof t?t:t._zod?.check;if(!e)continue;const s=e(r);i(s)&&a.push(Promise.resolve(s))}const n=()=>{for(const e of r.issues)s.addIssue(void 0===e.code?{message:e.message||"Custom check failed"}:{message:e.message||"Custom check failed",code:e.code})};if(a.length>0)return Promise.all(a).then(n);n()})}toJSONSchema(e){return n.toJSONSchema(this,e)}catch(e){return new VldCatch(this,e)}optional(){return new VldOptional(this)}nullable(){return new VldNullable(this)}nullish(){return new VldNullish(this)}exactOptional(){return new VldExactOptional(this)}pipe(e){return new VldPipe(this,e)}readonly(){return new VldReadonly(this)}brand(){return new VldBrand(this)}apply(e){return e(this)}check(e,t){return this.refine(e,t)}meta(t){if(void 0===t)return e.globalRegistry.get(this)??this.baseValidator?.meta?.()??this.schema?.meta?.()??this.inner?.meta?.();const s=new VldMeta(this,t);return e.globalRegistry.add(s,t),s}register(e,t){return e.add(this,t),this}describe(e){return this.meta({description:e})}get description(){return this.meta()?.description??this.baseValidator?.description??this.schema?.description??this.inner?.description}}class VldMeta extends VldBase{constructor(e,t){super(r.META),this.baseValidator=e,this.metadata=t}parse(e){return this.baseValidator.parse(e)}safeParse(e){return this.baseValidator.safeParse(e)}getMeta(){return{...this.metadata}}meta(t){if(void 0===t)return{...this.metadata,...e.globalRegistry.get(this)};const s=new VldMeta(this.baseValidator,{...this.metadata,...t});return e.globalRegistry.add(s,s.getMeta()),s}describe(e){return this.meta({description:e})}}class VldReadonly extends VldBase{constructor(e){super(r.READONLY),this.baseValidator=e}parse(e){return this.baseValidator.parse(e)}safeParse(e){const t=this.baseValidator.safeParse(e);return t.success?{success:!0,data:t.data}:{success:!1,error:t.error}}}class VldBrand extends VldBase{constructor(e){super(r.BRAND),this.baseValidator=e}parse(e){return this.baseValidator.parse(e)}safeParse(e){const t=this.baseValidator.safeParse(e);return t.success?{success:!0,data:t.data}:{success:!1,error:t.error}}}class VldRefine extends VldBase{constructor(e,t,s){super(r.REFINE),this.baseValidator=e,this.predicate=t,this.customMessage=s??"Refinement check failed","object"==typeof s&&null!==s&&"path"in s&&Array.isArray(s.path)&&(this.refinePath=s.path)}_createIssue(e){if("function"==typeof this.customMessage){const t=this.customMessage(e);return"string"==typeof t?{code:"custom",path:this.refinePath??[],message:t}:{code:"custom",path:t?.path??this.refinePath??[],message:t?.message??"Refinement check failed"}}if("object"==typeof this.customMessage&&null!==this.customMessage){const e=this.customMessage.message??this.customMessage.error,t="function"==typeof e?e({}):"string"==typeof e?e:"Refinement check failed";return{code:"custom",path:this.customMessage.path??this.refinePath??[],message:t}}return{code:"custom",path:this.refinePath??[],message:"string"==typeof this.customMessage?this.customMessage:"Refinement check failed"}}parse(e){const s=this.baseValidator.parse(e),r=this.predicate(s);if(i(r))throw new Error("Use parseAsync for async refinements");if(!r)throw new t.VldError([this._createIssue(s)]);return s}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:s(e)}}}async parseAsync(e){const s=await this.baseValidator.parseAsync(e);if(!await this.predicate(s))throw new t.VldError([this._createIssue(s)]);return s}async safeParseAsync(e){try{return{success:!0,data:await this.parseAsync(e)}}catch(e){return{success:!1,error:s(e)}}}_wrap(e){return new VldRefine(e,this.predicate,this.customMessage)}min(e,t){return this._wrap(this.baseValidator.min?.(e,t)??this.baseValidator)}max(e,t){return this._wrap(this.baseValidator.max?.(e,t)??this.baseValidator)}length(e,t){return this._wrap(this.baseValidator.length?.(e,t)??this.baseValidator)}email(e){return this._wrap(this.baseValidator.email?.(e)??this.baseValidator)}url(e){return this._wrap(this.baseValidator.url?.(e)??this.baseValidator)}uuid(e){return this._wrap(this.baseValidator.uuid?.(e)??this.baseValidator)}regex(e,t){return this._wrap(this.baseValidator.regex?.(e,t)??this.baseValidator)}startsWith(e,t){return this._wrap(this.baseValidator.startsWith?.(e,t)??this.baseValidator)}endsWith(e,t){return this._wrap(this.baseValidator.endsWith?.(e,t)??this.baseValidator)}includes(e,t){return this._wrap(this.baseValidator.includes?.(e,t)??this.baseValidator)}ip(e){return this._wrap(this.baseValidator.ip?.(e)??this.baseValidator)}ipv4(e){return this._wrap(this.baseValidator.ipv4?.(e)??this.baseValidator)}ipv6(e){return this._wrap(this.baseValidator.ipv6?.(e)??this.baseValidator)}nonempty(e){return this._wrap(this.baseValidator.nonempty?.(e)??this.baseValidator)}trim(){return this._wrap(this.baseValidator.trim?.()??this.baseValidator)}toLowerCase(){return this._wrap(this.baseValidator.toLowerCase?.()??this.baseValidator)}lowercase(){return this.toLowerCase()}toUpperCase(){return this._wrap(this.baseValidator.toUpperCase?.()??this.baseValidator)}uppercase(){return this.toUpperCase()}positive(e){return this._wrap(this.baseValidator.positive?.(e)??this.baseValidator)}negative(e){return this._wrap(this.baseValidator.negative?.(e)??this.baseValidator)}nonnegative(e){return this._wrap(this.baseValidator.nonnegative?.(e)??this.baseValidator)}nonpositive(e){return this._wrap(this.baseValidator.nonpositive?.(e)??this.baseValidator)}int(e){return this._wrap(this.baseValidator.int?.(e)??this.baseValidator)}finite(e){return this._wrap(this.baseValidator.finite?.(e)??this.baseValidator)}safe(e){return this._wrap(this.baseValidator.safe?.(e)??this.baseValidator)}multipleOf(e,t){return this._wrap(this.baseValidator.multipleOf?.(e,t)??this.baseValidator)}step(e,t){return this._wrap(this.baseValidator.step?.(e,t)??this.baseValidator)}gt(e,t){return this._wrap(this.baseValidator.gt?.(e,t)??this.baseValidator)}gte(e,t){return this._wrap(this.baseValidator.gte?.(e,t)??this.baseValidator)}lt(e,t){return this._wrap(this.baseValidator.lt?.(e,t)??this.baseValidator)}lte(e,t){return this._wrap(this.baseValidator.lte?.(e,t)??this.baseValidator)}extend(e){return this._wrap(this.baseValidator.extend?.(e)??this.baseValidator)}merge(e){return this._wrap(this.baseValidator.merge?.(e)??this.baseValidator)}pick(...e){return this._wrap(this.baseValidator.pick?.(...e)??this.baseValidator)}omit(...e){return this._wrap(this.baseValidator.omit?.(...e)??this.baseValidator)}partial(){return this._wrap(this.baseValidator.partial?.()??this.baseValidator)}required(){return this._wrap(this.baseValidator.required?.()??this.baseValidator)}strict(e){return this._wrap(this.baseValidator.strict?.(e)??this.baseValidator)}passthrough(){return this._wrap(this.baseValidator.passthrough?.()??this.baseValidator)}strip(){return this._wrap(this.baseValidator.strip?.()??this.baseValidator)}catchall(e){return this._wrap(this.baseValidator.catchall?.(e)??this.baseValidator)}get shape(){return this.baseValidator.shape}get keyof(){return this.baseValidator.keyof}unwrap(){return this.baseValidator.unwrap?this.baseValidator.unwrap():this.baseValidator}get element(){return this.baseValidator.element}}class VldTransform extends VldBase{constructor(e,t){super(r.TRANSFORM),this.baseValidator=e,this.transformer=t}parse(e){const t=this.baseValidator.parse(e);try{const e=this.transformer(t);if(i(e))throw new Error("Use parseAsync for async transforms");return e}catch(e){throw new Error(`Transform failed: ${e.message}`)}}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:s(e)}}}async parseAsync(e){const t=await this.baseValidator.parseAsync(e);try{return await this.transformer(t)}catch(e){throw new Error(`Transform failed: ${e.message}`)}}}class VldDefault extends VldBase{constructor(e,t){super(r.DEFAULT),this.baseValidator=e,this.defaultValue=t}parse(e){return void 0===e?o(this.defaultValue):this.baseValidator.parse(e)}safeParse(e){return void 0===e?{success:!0,data:o(this.defaultValue)}:this.baseValidator.safeParse(e)}prefault(e){return new VldPrefault(this.baseValidator,void 0===e?this.defaultValue:e)}unwrap(){return this.baseValidator}removeDefault(){return this.baseValidator}}class VldPrefault extends VldBase{constructor(e,t){super(r.PREFAULT),this.baseValidator=e,this.defaultValue=t}parse(e){return void 0===e?this.baseValidator.parse(o(this.defaultValue)):this.baseValidator.parse(e)}safeParse(e){return void 0===e?this.baseValidator.safeParse(o(this.defaultValue)):this.baseValidator.safeParse(e)}prefault(e){return void 0===e?this:new VldPrefault(this.baseValidator,e)}unwrap(){return this.baseValidator}}class VldCatch extends VldBase{constructor(e,t){super(r.CATCH),this.baseValidator=e,this.fallbackValue=t,this.simpleMode=h(e);const s=e.safeParse(t);if(!s.success)throw new Error(`Invalid fallback value: ${s.error.message}`)}parse(e){const t=l(this.simpleMode,e);if(void 0!==t)return t;if(void 0!==this.simpleMode)return this.fallbackValue;try{return this.baseValidator.parse(e)}catch{return this.fallbackValue}}safeParse(e){const t=l(this.simpleMode,e);if(void 0!==t)return{success:!0,data:t};if(void 0!==this.simpleMode)return{success:!0,data:this.fallbackValue};const s=this.baseValidator.safeParse(e);return s.success?s:{success:!0,data:this.fallbackValue}}}class VldOptional extends VldBase{constructor(e){super(r.OPTIONAL),this.baseValidator=e,this.simpleMode=h(e)}parseSimpleValue(e){return l(this.simpleMode,e)}static create(e){return new VldOptional(e)}parse(e){if(void 0===e)return;const t=this.parseSimpleValue(e);return void 0!==t?t:this.baseValidator.parse(e)}safeParse(e){if(void 0===e)return{success:!0,data:void 0};const t=this.parseSimpleValue(e);return void 0!==t?{success:!0,data:t}:this.baseValidator.safeParse(e)}unwrap(){return this.baseValidator}}class VldExactOptional extends VldBase{constructor(e){super(r.EXACT_OPTIONAL),this.baseValidator=e,this.simpleMode=h(e)}static create(e){return new VldExactOptional(e)}parse(e){if(void 0===e)return;const t=l(this.simpleMode,e);return void 0!==t?t:this.baseValidator.parse(e)}safeParse(e){if(void 0===e)return{success:!0,data:void 0};const t=l(this.simpleMode,e);return void 0!==t?{success:!0,data:t}:this.baseValidator.safeParse(e)}unwrap(){return this.baseValidator}}class VldNullable extends VldBase{constructor(e){super(r.NULLABLE),this.baseValidator=e,this.simpleMode=h(e)}static create(e){return new VldNullable(e)}parse(e){if(null===e)return null;const t=l(this.simpleMode,e);return void 0!==t?t:this.baseValidator.parse(e)}safeParse(e){if(null===e)return{success:!0,data:null};const t=l(this.simpleMode,e);return void 0!==t?{success:!0,data:t}:this.baseValidator.safeParse(e)}unwrap(){return this.baseValidator}}class VldNullish extends VldBase{constructor(e){super(r.NULLISH),this.baseValidator=e,this.simpleMode=h(e)}static create(e){return new VldNullish(e)}parse(e){if(null==e)return e;const t=l(this.simpleMode,e);return void 0!==t?t:this.baseValidator.parse(e)}safeParse(e){if(null==e)return{success:!0,data:e};const t=l(this.simpleMode,e);return void 0!==t?{success:!0,data:t}:this.baseValidator.safeParse(e)}unwrap(){return this.baseValidator}}class VldPipe extends VldBase{constructor(e,t){super(r.PIPE),this.first=e,this.second=t}parse(e){const t=this.first.parse(e);return this.second.parse(t)}safeParse(e){const t=this.first.safeParse(e);return t.success?this.second.safeParse(t.data):{success:!1,error:t.error}}}class VldSuperRefine extends VldBase{constructor(e,t){super(r.SUPER_REFINE),this._inner=e,this._refinement=t}parse(e){const s=this._inner.parse(e),r=[],a={addIssue:e=>{r.push({code:e.code||"custom",path:e.path??[],message:e.message||"Validation error"})},path:[]};if(this._refinement(s,a)instanceof Promise)throw new Error("Use parseAsync for async refinements");if(r.length>0)throw new t.VldError(r,r.map(e=>e.message).join("; "));return s}safeParse(e){const r=this._inner.safeParse(e);if(!r.success)return{success:!1,error:s(r.error)};const a=[],i={addIssue:e=>{a.push({code:e.code||"custom",path:e.path??[],message:e.message||"Validation error"})},path:[]};if(this._refinement(r.data,i)instanceof Promise)throw new Error("Use safeParseAsync for async refinements");return a.length>0?{success:!1,error:new t.VldError(a,a.map(e=>e.message).join("; "))}:r}async parseAsync(e){const s=await this._inner.parseAsync(e),r=[],a={addIssue:e=>{r.push({code:e.code||"custom",path:e.path??[],message:e.message||"Validation error"})},path:[]};if(await this._refinement(s,a),r.length>0)throw new t.VldError(r,r.map(e=>e.message).join("; "));return s}async safeParseAsync(e){try{return{success:!0,data:await this.parseAsync(e)}}catch(e){return{success:!1,error:s(e)}}}_wrap(e){return new VldSuperRefine(e,this._refinement)}min(e,t){return this._wrap(this._inner.min?.(e,t)??this._inner)}max(e,t){return this._wrap(this._inner.max?.(e,t)??this._inner)}length(e,t){return this._wrap(this._inner.length?.(e,t)??this._inner)}email(e){return this._wrap(this._inner.email?.(e)??this._inner)}url(e){return this._wrap(this._inner.url?.(e)??this._inner)}uuid(e){return this._wrap(this._inner.uuid?.(e)??this._inner)}regex(e,t){return this._wrap(this._inner.regex?.(e,t)??this._inner)}startsWith(e,t){return this._wrap(this._inner.startsWith?.(e,t)??this._inner)}endsWith(e,t){return this._wrap(this._inner.endsWith?.(e,t)??this._inner)}includes(e,t){return this._wrap(this._inner.includes?.(e,t)??this._inner)}ip(e){return this._wrap(this._inner.ip?.(e)??this._inner)}ipv4(e){return this._wrap(this._inner.ipv4?.(e)??this._inner)}ipv6(e){return this._wrap(this._inner.ipv6?.(e)??this._inner)}nonempty(e){return this._wrap(this._inner.nonempty?.(e)??this._inner)}trim(){return this._wrap(this._inner.trim?.()??this._inner)}toLowerCase(){return this._wrap(this._inner.toLowerCase?.()??this._inner)}lowercase(){return this.toLowerCase()}toUpperCase(){return this._wrap(this._inner.toUpperCase?.()??this._inner)}uppercase(){return this.toUpperCase()}positive(e){return this._wrap(this._inner.positive?.(e)??this._inner)}negative(e){return this._wrap(this._inner.negative?.(e)??this._inner)}nonnegative(e){return this._wrap(this._inner.nonnegative?.(e)??this._inner)}nonpositive(e){return this._wrap(this._inner.nonpositive?.(e)??this._inner)}int(e){return this._wrap(this._inner.int?.(e)??this._inner)}finite(e){return this._wrap(this._inner.finite?.(e)??this._inner)}safe(e){return this._wrap(this._inner.safe?.(e)??this._inner)}multipleOf(e,t){return this._wrap(this._inner.multipleOf?.(e,t)??this._inner)}step(e,t){return this._wrap(this._inner.step?.(e,t)??this._inner)}gt(e,t){return this._wrap(this._inner.gt?.(e,t)??this._inner)}gte(e,t){return this._wrap(this._inner.gte?.(e,t)??this._inner)}lt(e,t){return this._wrap(this._inner.lt?.(e,t)??this._inner)}lte(e,t){return this._wrap(this._inner.lte?.(e,t)??this._inner)}extend(e){return this._wrap(this._inner.extend?.(e)??this._inner)}merge(e){return this._wrap(this._inner.merge?.(e)??this._inner)}pick(...e){return this._wrap(this._inner.pick?.(...e)??this._inner)}omit(...e){return this._wrap(this._inner.omit?.(...e)??this._inner)}partial(){return this._wrap(this._inner.partial?.()??this._inner)}required(){return this._wrap(this._inner.required?.()??this._inner)}strict(e){return this._wrap(this._inner.strict?.(e)??this._inner)}passthrough(){return this._wrap(this._inner.passthrough?.()??this._inner)}strip(){return this._wrap(this._inner.strip?.()??this._inner)}catchall(e){return this._wrap(this._inner.catchall?.(e)??this._inner)}get shape(){return this._inner.shape}get keyof(){return this._inner.keyof}unwrap(){return this._inner.unwrap?this._inner.unwrap():this._inner}get element(){return this._inner.element}}class VldPreprocess extends VldBase{constructor(e,t){super(r.PREPROCESS),this._preprocessor=e,this._schema=t}static create(e,t){return new VldPreprocess(e,t)}parse(e){const t=this._preprocessor(e);return this._schema.parse(t)}safeParse(e){try{const t=this._preprocessor(e);return this._schema.safeParse(t)}catch(e){return{success:!1,error:s(e)}}}}exports.VLD_VALIDATOR_TYPES=r,exports.VldBase=VldBase,exports.VldBrand=VldBrand,exports.VldCatch=VldCatch,exports.VldDefault=VldDefault,exports.VldExactOptional=VldExactOptional,exports.VldMeta=VldMeta,exports.VldNullable=VldNullable,exports.VldNullish=VldNullish,exports.VldOptional=VldOptional,exports.VldPipe=VldPipe,exports.VldPrefault=VldPrefault,exports.VldPreprocess=VldPreprocess,exports.VldReadonly=VldReadonly,exports.VldRefine=VldRefine,exports.VldSuperRefine=VldSuperRefine,exports.VldTransform=VldTransform,exports.configureSchemaCompositionFactories=function(e){n=e},exports.ensureVldError=s,exports.isPromiseLike=i,exports.resolveErrorMessage=a;
|
|
1
|
+
"use strict";var e=require("../registry.cjs"),t=require("../chunks/errors-core-C0mA6tfa.cjs");function s(e){if(e instanceof t.VldError)return e;const s=e instanceof Error?e.message:String(e);return new t.VldError([{code:"custom",path:[],message:s}])}const r=Symbol.for("@oxog/vld/compile-invalid");function a(e){let t=null;try{const s=globalThis?.["@oxog/vld/lazy-validate-compiler"];t=(s?s(e):null)??null}catch{t=null}return Object.defineProperty(e,"__vldValidateFn",{value:t,enumerable:!1,configurable:!0}),t}const i={STRING:"string",STRING_FORMAT:"stringFormat",STRING_BOOL:"stringBool",NUMBER:"number",BOOLEAN:"boolean",DATE:"date",BIGINT:"bigint",UNDEFINED:"undefined",NULL:"null",UNKNOWN:"unknown",ANY:"any",VOID:"void",NEVER:"never",SYMBOL:"symbol",NAN:"nan",HEX:"hex",BASE64:"base64",UINT8_ARRAY:"uint8Array",COERCE_STRING:"coerceString",COERCE_NUMBER:"coerceNumber",COERCE_BOOLEAN:"coerceBoolean",COERCE_DATE:"coerceDate",COERCE_BIGINT:"coerceBigint",OBJECT:"object",ARRAY:"array",TUPLE:"tuple",SET:"set",MAP:"map",RECORD:"record",UNION:"union",DISCRIMINATED_UNION:"discriminatedUnion",INTERSECTION:"intersection",XOR:"xor",ENUM:"enum",LITERAL:"literal",LAZY:"lazy",CUSTOM:"custom",FUNCTION:"function",FILE:"file",JSON:"json",TEMPLATE_LITERAL:"templateLiteral",PROMISE:"promise",OPTIONAL:"optional",NULLABLE:"nullable",NULLISH:"nullish",EXACT_OPTIONAL:"exactOptional",DEFAULT:"default",CATCH:"catch",REFINE:"refine",TRANSFORM:"transform",PIPE:"pipe",PREPROCESS:"preprocess",SUPER_REFINE:"superRefine",BRAND:"brand",READONLY:"readonly",META:"meta",PREFAULT:"prefault",PREFault:"prefault",CODEC:"codec"};function n(e,t){if("string"==typeof e)return e;if("function"==typeof e){const s=e(void 0);return"string"==typeof s?s:"object"==typeof s&&s?.message?s.message:t}if("object"==typeof e&&null!==e){if("string"==typeof e.error)return e.error;if("function"==typeof e.error)return e.error({})||t;if("string"==typeof e.message)return e.message}return t}function o(e){return null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}let l;function h(e){return"function"==typeof e?e():function(e){if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);if(null!==e&&"object"==typeof e){const t=Object.getPrototypeOf(e);if(t===Object.prototype||null===t)return{...e}}return e}(e)}function u(e){if(!0===e.isSimple)switch(e.validatorType){case i.STRING:return"string";case i.NUMBER:return"number";case i.BOOLEAN:return"boolean";case i.BIGINT:return"bigint";case i.SYMBOL:return"symbol";default:return}}function d(e,t){switch(e){case"string":return"string"==typeof t?t:void 0;case"number":return"number"!=typeof t||isNaN(t)?void 0:t;case"boolean":return"boolean"==typeof t?t:void 0;case"bigint":return"bigint"==typeof t?t:void 0;case"symbol":return"symbol"==typeof t?t:void 0;default:return}}class VldBase{constructor(e="unknown"){this.validatorType=e}get type(){return this.validatorType}get _def(){return{typeName:"Zod"+this.validatorType.charAt(0).toUpperCase()+this.validatorType.slice(1),...this.config||{}}}get def(){return this._def}get _zod(){return this._def}get"~standard"(){return{version:1,vendor:"vld",validate:e=>{const t=this.safeParse(e);return t.success?{value:t.data}:{issues:[{message:t.error.message}]}},types:void 0}}async parseAsync(e){return this.parse(e)}async safeParseAsync(e){try{return{success:!0,data:await this.parseAsync(e)}}catch(e){return{success:!1,error:s(e)}}}decode(e){return this.parse(e)}safeDecode(e){return this.safeParse(e)}async decodeAsync(e){return this.parseAsync(e)}async safeDecodeAsync(e){return this.safeParseAsync(e)}encode(e){return this.parse(e)}safeEncode(e){const t=this.safeParse(e);return t.success?{success:!0,data:t.data}:t}async encodeAsync(e){return this.parseAsync(e)}async safeEncodeAsync(e){const t=await this.safeParseAsync(e);return t.success?{success:!0,data:t.data}:t}spa(e){return this.safeParseAsync(e)}validate(e){const t=this.__vldValidateFn;return void 0!==t?null!==t?t(e)!==r:this.validateWithRuntimeParser(e):this.initValidate(e)}validateWithRuntimeParser(e){let t=this.__vldSafeFn;return void 0===t&&(t=this.__vldSafeFn=this.safeParse.bind(this)),Boolean(t(e).success)}initValidate(e){const t=this,s=t._zod?.bag,i=s?.validatorValidate??s?.validator;if(void 0!==i)return Object.defineProperty(t,"__vldValidateFn",{value:i,enumerable:!1,configurable:!0}),i(e)!==r;const n=a(t);return null!==n?n(e)!==r:this.validateWithRuntimeParser(e)}async validateAsync(e){const t=this.__vldValidateFn;if(null!=t)return t(e)!==r;if(void 0===t){this.initValidate(e);const t=this.__vldValidateFn;if(null!=t)return t(e)!==r}return(await this.safeParseAsync(e)).success}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}clone(){return this}isValid(e){return this.validate(e)}parseOrDefault(e,t){const s=this.safeParse(e);if(s.success)return s.data;const r=this.safeParse(t);if(!r.success)throw new Error(`Invalid default value provided: ${r.error.message}`);return r.data}refine(e,t){return new VldRefine(this,e,t)}superRefine(e){return new VldSuperRefine(this,e)}transform(e){return new VldTransform(this,e)}default(e){return new VldDefault(this,e)}prefault(e){return new VldPrefault(this,e)}nonoptional(e){return new VldRefine(this,e=>void 0!==e,n(e,"Expected non-optional value"))}array(){return l.array(this)}or(e){return l.union(this,e)}and(e){return l.intersection(this,e)}overwrite(e){return new VldTransform(this,e)}with(...e){return new VldSuperRefine(this,(t,s)=>{const r={value:t,issues:[]},a=[];for(const t of e){const e="function"==typeof t?t:t._zod?.check;if(!e)continue;const s=e(r);o(s)&&a.push(Promise.resolve(s))}const i=()=>{for(const e of r.issues)s.addIssue(void 0===e.code?{message:e.message||"Custom check failed"}:{message:e.message||"Custom check failed",code:e.code})};if(a.length>0)return Promise.all(a).then(i);i()})}toJSONSchema(e){return l.toJSONSchema(this,e)}catch(e){return new VldCatch(this,e)}optional(){return new VldOptional(this)}nullable(){return new VldNullable(this)}nullish(){return new VldNullish(this)}exactOptional(){return new VldExactOptional(this)}pipe(e){return new VldPipe(this,e)}readonly(){return new VldReadonly(this)}brand(){return new VldBrand(this)}apply(e){return e(this)}check(e,t){return this.refine(e,t)}meta(t){if(void 0===t)return e.globalRegistry.get(this)??this.baseValidator?.meta?.()??this.schema?.meta?.()??this.inner?.meta?.();const s=new VldMeta(this,t);return e.globalRegistry.add(s,t),s}register(e,t){return e.add(this,t),this}describe(e){return this.meta({description:e})}get description(){return this.meta()?.description??this.baseValidator?.description??this.schema?.description??this.inner?.description}}class VldMeta extends VldBase{constructor(e,t){super(i.META),this.baseValidator=e,this.metadata=t}parse(e){return this.baseValidator.parse(e)}safeParse(e){return this.baseValidator.safeParse(e)}getMeta(){return{...this.metadata}}meta(t){if(void 0===t)return{...this.metadata,...e.globalRegistry.get(this)};const s=new VldMeta(this.baseValidator,{...this.metadata,...t});return e.globalRegistry.add(s,s.getMeta()),s}describe(e){return this.meta({description:e})}}class VldReadonly extends VldBase{constructor(e){super(i.READONLY),this.baseValidator=e}parse(e){return this.baseValidator.parse(e)}safeParse(e){const t=this.baseValidator.safeParse(e);return t.success?{success:!0,data:t.data}:{success:!1,error:t.error}}}class VldBrand extends VldBase{constructor(e){super(i.BRAND),this.baseValidator=e}parse(e){return this.baseValidator.parse(e)}safeParse(e){const t=this.baseValidator.safeParse(e);return t.success?{success:!0,data:t.data}:{success:!1,error:t.error}}}class VldRefine extends VldBase{constructor(e,t,s){super(i.REFINE),this.baseValidator=e,this.predicate=t,this.customMessage=s??"Refinement check failed","object"==typeof s&&null!==s&&"path"in s&&Array.isArray(s.path)&&(this.refinePath=s.path)}_createIssue(e){if("function"==typeof this.customMessage){const t=this.customMessage(e);return"string"==typeof t?{code:"custom",path:this.refinePath??[],message:t}:{code:"custom",path:t?.path??this.refinePath??[],message:t?.message??"Refinement check failed"}}if("object"==typeof this.customMessage&&null!==this.customMessage){const e=this.customMessage.message??this.customMessage.error,t="function"==typeof e?e({}):"string"==typeof e?e:"Refinement check failed";return{code:"custom",path:this.customMessage.path??this.refinePath??[],message:t}}return{code:"custom",path:this.refinePath??[],message:"string"==typeof this.customMessage?this.customMessage:"Refinement check failed"}}parse(e){const s=this.baseValidator.parse(e),r=this.predicate(s);if(o(r))throw new Error("Use parseAsync for async refinements");if(!r)throw new t.VldError([this._createIssue(s)]);return s}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:s(e)}}}async parseAsync(e){const s=await this.baseValidator.parseAsync(e);if(!await this.predicate(s))throw new t.VldError([this._createIssue(s)]);return s}async safeParseAsync(e){try{return{success:!0,data:await this.parseAsync(e)}}catch(e){return{success:!1,error:s(e)}}}_wrap(e){return new VldRefine(e,this.predicate,this.customMessage)}min(e,t){return this._wrap(this.baseValidator.min?.(e,t)??this.baseValidator)}max(e,t){return this._wrap(this.baseValidator.max?.(e,t)??this.baseValidator)}length(e,t){return this._wrap(this.baseValidator.length?.(e,t)??this.baseValidator)}email(e){return this._wrap(this.baseValidator.email?.(e)??this.baseValidator)}url(e){return this._wrap(this.baseValidator.url?.(e)??this.baseValidator)}uuid(e){return this._wrap(this.baseValidator.uuid?.(e)??this.baseValidator)}regex(e,t){return this._wrap(this.baseValidator.regex?.(e,t)??this.baseValidator)}startsWith(e,t){return this._wrap(this.baseValidator.startsWith?.(e,t)??this.baseValidator)}endsWith(e,t){return this._wrap(this.baseValidator.endsWith?.(e,t)??this.baseValidator)}includes(e,t){return this._wrap(this.baseValidator.includes?.(e,t)??this.baseValidator)}ip(e){return this._wrap(this.baseValidator.ip?.(e)??this.baseValidator)}ipv4(e){return this._wrap(this.baseValidator.ipv4?.(e)??this.baseValidator)}ipv6(e){return this._wrap(this.baseValidator.ipv6?.(e)??this.baseValidator)}nonempty(e){return this._wrap(this.baseValidator.nonempty?.(e)??this.baseValidator)}trim(){return this._wrap(this.baseValidator.trim?.()??this.baseValidator)}toLowerCase(){return this._wrap(this.baseValidator.toLowerCase?.()??this.baseValidator)}lowercase(){return this.toLowerCase()}toUpperCase(){return this._wrap(this.baseValidator.toUpperCase?.()??this.baseValidator)}uppercase(){return this.toUpperCase()}positive(e){return this._wrap(this.baseValidator.positive?.(e)??this.baseValidator)}negative(e){return this._wrap(this.baseValidator.negative?.(e)??this.baseValidator)}nonnegative(e){return this._wrap(this.baseValidator.nonnegative?.(e)??this.baseValidator)}nonpositive(e){return this._wrap(this.baseValidator.nonpositive?.(e)??this.baseValidator)}int(e){return this._wrap(this.baseValidator.int?.(e)??this.baseValidator)}finite(e){return this._wrap(this.baseValidator.finite?.(e)??this.baseValidator)}safe(e){return this._wrap(this.baseValidator.safe?.(e)??this.baseValidator)}multipleOf(e,t){return this._wrap(this.baseValidator.multipleOf?.(e,t)??this.baseValidator)}step(e,t){return this._wrap(this.baseValidator.step?.(e,t)??this.baseValidator)}gt(e,t){return this._wrap(this.baseValidator.gt?.(e,t)??this.baseValidator)}gte(e,t){return this._wrap(this.baseValidator.gte?.(e,t)??this.baseValidator)}lt(e,t){return this._wrap(this.baseValidator.lt?.(e,t)??this.baseValidator)}lte(e,t){return this._wrap(this.baseValidator.lte?.(e,t)??this.baseValidator)}extend(e){return this._wrap(this.baseValidator.extend?.(e)??this.baseValidator)}merge(e){return this._wrap(this.baseValidator.merge?.(e)??this.baseValidator)}pick(...e){return this._wrap(this.baseValidator.pick?.(...e)??this.baseValidator)}omit(...e){return this._wrap(this.baseValidator.omit?.(...e)??this.baseValidator)}partial(){return this._wrap(this.baseValidator.partial?.()??this.baseValidator)}required(){return this._wrap(this.baseValidator.required?.()??this.baseValidator)}strict(e){return this._wrap(this.baseValidator.strict?.(e)??this.baseValidator)}passthrough(){return this._wrap(this.baseValidator.passthrough?.()??this.baseValidator)}strip(){return this._wrap(this.baseValidator.strip?.()??this.baseValidator)}catchall(e){return this._wrap(this.baseValidator.catchall?.(e)??this.baseValidator)}get shape(){return this.baseValidator.shape}get keyof(){return this.baseValidator.keyof}unwrap(){return this.baseValidator.unwrap?this.baseValidator.unwrap():this.baseValidator}get element(){return this.baseValidator.element}}class VldTransform extends VldBase{constructor(e,t){super(i.TRANSFORM),this.baseValidator=e,this.transformer=t}parse(e){const t=this.baseValidator.parse(e);try{const e=this.transformer(t);if(o(e))throw new Error("Use parseAsync for async transforms");return e}catch(e){throw new Error(`Transform failed: ${e.message}`)}}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:s(e)}}}async parseAsync(e){const t=await this.baseValidator.parseAsync(e);try{return await this.transformer(t)}catch(e){throw new Error(`Transform failed: ${e.message}`)}}}class VldDefault extends VldBase{constructor(e,t){super(i.DEFAULT),this.baseValidator=e,this.defaultValue=t}parse(e){return void 0===e?h(this.defaultValue):this.baseValidator.parse(e)}safeParse(e){return void 0===e?{success:!0,data:h(this.defaultValue)}:this.baseValidator.safeParse(e)}prefault(e){return new VldPrefault(this.baseValidator,void 0===e?this.defaultValue:e)}unwrap(){return this.baseValidator}removeDefault(){return this.baseValidator}}class VldPrefault extends VldBase{constructor(e,t){super(i.PREFAULT),this.baseValidator=e,this.defaultValue=t}parse(e){return void 0===e?this.baseValidator.parse(h(this.defaultValue)):this.baseValidator.parse(e)}safeParse(e){return void 0===e?this.baseValidator.safeParse(h(this.defaultValue)):this.baseValidator.safeParse(e)}prefault(e){return void 0===e?this:new VldPrefault(this.baseValidator,e)}unwrap(){return this.baseValidator}}class VldCatch extends VldBase{constructor(e,t){super(i.CATCH),this.baseValidator=e,this.fallbackValue=t,this.simpleMode=u(e);const s=e.safeParse(t);if(!s.success)throw new Error(`Invalid fallback value: ${s.error.message}`)}parse(e){const t=d(this.simpleMode,e);if(void 0!==t)return t;if(void 0!==this.simpleMode)return this.fallbackValue;try{return this.baseValidator.parse(e)}catch{return this.fallbackValue}}safeParse(e){const t=d(this.simpleMode,e);if(void 0!==t)return{success:!0,data:t};if(void 0!==this.simpleMode)return{success:!0,data:this.fallbackValue};const s=this.baseValidator.safeParse(e);return s.success?s:{success:!0,data:this.fallbackValue}}}class VldOptional extends VldBase{constructor(e){super(i.OPTIONAL),this.baseValidator=e,this.simpleMode=u(e)}parseSimpleValue(e){return d(this.simpleMode,e)}static create(e){return new VldOptional(e)}parse(e){if(void 0===e)return;const t=this.parseSimpleValue(e);return void 0!==t?t:this.baseValidator.parse(e)}safeParse(e){if(void 0===e)return{success:!0,data:void 0};const t=this.parseSimpleValue(e);return void 0!==t?{success:!0,data:t}:this.baseValidator.safeParse(e)}unwrap(){return this.baseValidator}}class VldExactOptional extends VldBase{constructor(e){super(i.EXACT_OPTIONAL),this.baseValidator=e,this.simpleMode=u(e)}static create(e){return new VldExactOptional(e)}parse(e){if(void 0===e)return;const t=d(this.simpleMode,e);return void 0!==t?t:this.baseValidator.parse(e)}safeParse(e){if(void 0===e)return{success:!0,data:void 0};const t=d(this.simpleMode,e);return void 0!==t?{success:!0,data:t}:this.baseValidator.safeParse(e)}unwrap(){return this.baseValidator}}class VldNullable extends VldBase{constructor(e){super(i.NULLABLE),this.baseValidator=e,this.simpleMode=u(e)}static create(e){return new VldNullable(e)}parse(e){if(null===e)return null;const t=d(this.simpleMode,e);return void 0!==t?t:this.baseValidator.parse(e)}safeParse(e){if(null===e)return{success:!0,data:null};const t=d(this.simpleMode,e);return void 0!==t?{success:!0,data:t}:this.baseValidator.safeParse(e)}unwrap(){return this.baseValidator}}class VldNullish extends VldBase{constructor(e){super(i.NULLISH),this.baseValidator=e,this.simpleMode=u(e)}static create(e){return new VldNullish(e)}parse(e){if(null==e)return e;const t=d(this.simpleMode,e);return void 0!==t?t:this.baseValidator.parse(e)}safeParse(e){if(null==e)return{success:!0,data:e};const t=d(this.simpleMode,e);return void 0!==t?{success:!0,data:t}:this.baseValidator.safeParse(e)}unwrap(){return this.baseValidator}}class VldPipe extends VldBase{constructor(e,t){super(i.PIPE),this.first=e,this.second=t}parse(e){const t=this.first.parse(e);return this.second.parse(t)}safeParse(e){const t=this.first.safeParse(e);return t.success?this.second.safeParse(t.data):{success:!1,error:t.error}}}class VldSuperRefine extends VldBase{constructor(e,t){super(i.SUPER_REFINE),this._inner=e,this._refinement=t}parse(e){const s=this._inner.parse(e),r=[],a={addIssue:e=>{r.push({code:e.code||"custom",path:e.path??[],message:e.message||"Validation error"})},path:[]};if(this._refinement(s,a)instanceof Promise)throw new Error("Use parseAsync for async refinements");if(r.length>0)throw new t.VldError(r,r.map(e=>e.message).join("; "));return s}safeParse(e){const r=this._inner.safeParse(e);if(!r.success)return{success:!1,error:s(r.error)};const a=[],i={addIssue:e=>{a.push({code:e.code||"custom",path:e.path??[],message:e.message||"Validation error"})},path:[]};if(this._refinement(r.data,i)instanceof Promise)throw new Error("Use safeParseAsync for async refinements");return a.length>0?{success:!1,error:new t.VldError(a,a.map(e=>e.message).join("; "))}:r}async parseAsync(e){const s=await this._inner.parseAsync(e),r=[],a={addIssue:e=>{r.push({code:e.code||"custom",path:e.path??[],message:e.message||"Validation error"})},path:[]};if(await this._refinement(s,a),r.length>0)throw new t.VldError(r,r.map(e=>e.message).join("; "));return s}async safeParseAsync(e){try{return{success:!0,data:await this.parseAsync(e)}}catch(e){return{success:!1,error:s(e)}}}_wrap(e){return new VldSuperRefine(e,this._refinement)}min(e,t){return this._wrap(this._inner.min?.(e,t)??this._inner)}max(e,t){return this._wrap(this._inner.max?.(e,t)??this._inner)}length(e,t){return this._wrap(this._inner.length?.(e,t)??this._inner)}email(e){return this._wrap(this._inner.email?.(e)??this._inner)}url(e){return this._wrap(this._inner.url?.(e)??this._inner)}uuid(e){return this._wrap(this._inner.uuid?.(e)??this._inner)}regex(e,t){return this._wrap(this._inner.regex?.(e,t)??this._inner)}startsWith(e,t){return this._wrap(this._inner.startsWith?.(e,t)??this._inner)}endsWith(e,t){return this._wrap(this._inner.endsWith?.(e,t)??this._inner)}includes(e,t){return this._wrap(this._inner.includes?.(e,t)??this._inner)}ip(e){return this._wrap(this._inner.ip?.(e)??this._inner)}ipv4(e){return this._wrap(this._inner.ipv4?.(e)??this._inner)}ipv6(e){return this._wrap(this._inner.ipv6?.(e)??this._inner)}nonempty(e){return this._wrap(this._inner.nonempty?.(e)??this._inner)}trim(){return this._wrap(this._inner.trim?.()??this._inner)}toLowerCase(){return this._wrap(this._inner.toLowerCase?.()??this._inner)}lowercase(){return this.toLowerCase()}toUpperCase(){return this._wrap(this._inner.toUpperCase?.()??this._inner)}uppercase(){return this.toUpperCase()}positive(e){return this._wrap(this._inner.positive?.(e)??this._inner)}negative(e){return this._wrap(this._inner.negative?.(e)??this._inner)}nonnegative(e){return this._wrap(this._inner.nonnegative?.(e)??this._inner)}nonpositive(e){return this._wrap(this._inner.nonpositive?.(e)??this._inner)}int(e){return this._wrap(this._inner.int?.(e)??this._inner)}finite(e){return this._wrap(this._inner.finite?.(e)??this._inner)}safe(e){return this._wrap(this._inner.safe?.(e)??this._inner)}multipleOf(e,t){return this._wrap(this._inner.multipleOf?.(e,t)??this._inner)}step(e,t){return this._wrap(this._inner.step?.(e,t)??this._inner)}gt(e,t){return this._wrap(this._inner.gt?.(e,t)??this._inner)}gte(e,t){return this._wrap(this._inner.gte?.(e,t)??this._inner)}lt(e,t){return this._wrap(this._inner.lt?.(e,t)??this._inner)}lte(e,t){return this._wrap(this._inner.lte?.(e,t)??this._inner)}extend(e){return this._wrap(this._inner.extend?.(e)??this._inner)}merge(e){return this._wrap(this._inner.merge?.(e)??this._inner)}pick(...e){return this._wrap(this._inner.pick?.(...e)??this._inner)}omit(...e){return this._wrap(this._inner.omit?.(...e)??this._inner)}partial(){return this._wrap(this._inner.partial?.()??this._inner)}required(){return this._wrap(this._inner.required?.()??this._inner)}strict(e){return this._wrap(this._inner.strict?.(e)??this._inner)}passthrough(){return this._wrap(this._inner.passthrough?.()??this._inner)}strip(){return this._wrap(this._inner.strip?.()??this._inner)}catchall(e){return this._wrap(this._inner.catchall?.(e)??this._inner)}get shape(){return this._inner.shape}get keyof(){return this._inner.keyof}unwrap(){return this._inner.unwrap?this._inner.unwrap():this._inner}get element(){return this._inner.element}}class VldPreprocess extends VldBase{constructor(e,t){super(i.PREPROCESS),this._preprocessor=e,this._schema=t}static create(e,t){return new VldPreprocess(e,t)}parse(e){const t=this._preprocessor(e);return this._schema.parse(t)}safeParse(e){try{const t=this._preprocessor(e);return this._schema.safeParse(t)}catch(e){return{success:!1,error:s(e)}}}}exports.VLD_VALIDATOR_TYPES=i,exports.VldBase=VldBase,exports.VldBrand=VldBrand,exports.VldCatch=VldCatch,exports.VldDefault=VldDefault,exports.VldExactOptional=VldExactOptional,exports.VldMeta=VldMeta,exports.VldNullable=VldNullable,exports.VldNullish=VldNullish,exports.VldOptional=VldOptional,exports.VldPipe=VldPipe,exports.VldPrefault=VldPrefault,exports.VldPreprocess=VldPreprocess,exports.VldReadonly=VldReadonly,exports.VldRefine=VldRefine,exports.VldSuperRefine=VldSuperRefine,exports.VldTransform=VldTransform,exports.configureSchemaCompositionFactories=function(e){l=e},exports.ensureVldError=s,exports.isPromiseLike=o,exports.resolveErrorMessage=n;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var s=require("./base.cjs")
|
|
1
|
+
"use strict";var s=require("./base.cjs"),e=require("../chunks/errors-core-C0mA6tfa.cjs");require("../registry.cjs");class VldCustom extends s.VldBase{constructor(e){super(s.VLD_VALIDATOR_TYPES.CUSTOM),this._parseFn=e.parse,this._parseAsyncFn=e.parseAsync||(s=>Promise.resolve(this._parseFn(s))),this._safeParseFn=e.safeParse?r=>{const t=e.safeParse(r);return t.success?{success:!0,data:t.data}:{success:!1,error:s.ensureVldError(t.error)}}:e=>{try{return{success:!0,data:this._parseFn(e)}}catch(e){return{success:!1,error:s.ensureVldError(e)}}},this._safeParseAsyncFn=e.safeParseAsync?async r=>{const t=await e.safeParseAsync(r);return t.success?{success:!0,data:t.data}:{success:!1,error:s.ensureVldError(t.error)}}:async e=>{try{return{success:!0,data:await this._parseAsyncFn(e)}}catch(e){return{success:!1,error:s.ensureVldError(e)}}}}static create(s){return new VldCustom(s)}parse(s){return this._parseFn(s)}safeParse(s){return this._safeParseFn(s)}async parseAsync(s){return this._parseAsyncFn(s)}async safeParseAsync(s){return this._safeParseAsyncFn(s)}}function r(e,r){if("function"==typeof e){const t=e;return VldCustom.create({parse:e=>{if(!t(e))throw s.ensureVldError(s.resolveErrorMessage(r,"Custom validation failed"));return e}})}return e?VldCustom.create(e):VldCustom.create({parse:s=>s})}exports.VldCustom=VldCustom,exports.VldInstance=class extends VldCustom{constructor(s,r){super({parse:t=>{if(!(t instanceof s))throw new e.VldError([{code:"custom",path:[],message:r||`Expected instance of ${s.name||"provided constructor"}`}]);return t}}),this._cls=s,this._instanceMessage=r}properties(s,r){const t=this._cls,a=r?.message??this._instanceMessage,c=Object.entries(s);return VldCustom.create({parse:s=>{if(!(s instanceof t))throw new e.VldError([{code:"custom",path:[],message:a||`Expected instance of ${t.name||"provided constructor"}`}]);for(const[r,t]of c){const a=t.safeParse(s[r]);if(!a.success){const s=a.error.issues??[];throw new e.VldError(s.length>0?s.map(s=>({...s,path:[r,...s.path]})):[{code:"custom",path:[r],message:a.error.message}])}}return s}})}},exports.custom=r,exports.customFn=r;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./base.cjs");require("../registry.cjs"),require("../chunks/errors-core-C0mA6tfa.cjs");class VldPromise extends e.VldBase{constructor(s){super(e.VLD_VALIDATOR_TYPES.PROMISE),this.inner=s}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(s){return this._isThenable(s)?(async()=>{try{const e=await Promise.resolve(s);if(this.inner.safeParseAsync)return await this.inner.safeParseAsync(e);const r=this.inner.safeParse(e);return r.success?{success:!0,data:r.data}:r}catch(s){return{success:!1,error:e.ensureVldError(s)}}})():Promise.resolve({success:!1,error:e.ensureVldError("Expected a Promise value")})}safeParseAsync(e){return this.safeParse(e)}}exports.VldPromise=VldPromise,exports.promise=function(e){return new VldPromise(e)};
|
|
1
|
+
"use strict";var e=require("./base.cjs");require("../registry.cjs"),require("../chunks/errors-core-C0mA6tfa.cjs");class VldPromise extends e.VldBase{constructor(s){super(e.VLD_VALIDATOR_TYPES.PROMISE),this.inner=s}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(s){return this._isThenable(s)?(async()=>{try{const e=await Promise.resolve(s);if(this.inner.safeParseAsync)return await this.inner.safeParseAsync(e);const r=this.inner.safeParse(e);return r.success?{success:!0,data:r.data}:r}catch(s){return{success:!1,error:e.ensureVldError(s)}}})():Promise.resolve({success:!1,error:e.ensureVldError("Expected a Promise value")})}safeParseAsync(e){return this.safeParse(e)}validate(e){throw new Error("Promise schemas validate asynchronously; use validateAsync instead")}async validateAsync(e){return(await this.safeParseAsync(e)).success}}exports.VldPromise=VldPromise,exports.promise=function(e){return new VldPromise(e)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./base.cjs"),t=require("../locales/runtime.cjs"),r=require("../chunks/ip-validation-BZqPamPC.cjs"),a=require("../chunks/errors-core-C0mA6tfa.cjs");require("../registry.cjs"),require("../locales/en.cjs");const i="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function d(e,t){return e.lastIndex=0,e.test(t)}function s(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function o(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}function n(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"!=typeof e.precision?`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`:-1===e.precision?t:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`}function c(e){return void 0===e?/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/:new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)}const u={cuid:/^[cC][0-9a-z]{6,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid:/^[0-9a-vA-V]{20}$/,ksuid:/^[A-Za-z0-9]{27}$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,nanoidOfLength:e=>new RegExp(`^[a-zA-Z0-9_-]{${e}}$`),duration:/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,extendedDuration:/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,guid:/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,creditCard:/^\d(?:[ -]?\d){11,18}$/,uuid:c,uuid4:c(4),uuid6:c(6),uuid7:c(7),email:/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+.-]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/,html5Email:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,rfc5322Email:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}))$/,unicodeEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,idnEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,browserEmail:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,emoji:()=>/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,mac:function(e=":"){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},cidrv4:/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6:/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url:/^[A-Za-z0-9_-]*$/,hostname:/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,domain:/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,httpProtocol:/^https?$/,e164:/^\+[1-9]\d{6,14}$/,date:new RegExp(`^${i}$`),time:function(e={}){return new RegExp(`^${n(e)}$`)},datetime:function(e={}){const t=["Z"];return e.local&&t.push(""),e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)"),new RegExp(`^${i}T${n(e)}(?:${t.join("|")})$`)},string:function(e){const t=e?`[\\s\\S]{${e.minimum??0},${e.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},bigint:/^-?\d+n?$/,integer:/^-?\d+$/,number:/^-?\d+(?:\.\d+)?$/,boolean:/^(?:true|false)$/i,null:/^null$/i,undefined:/^undefined$/i,lowercase:/^[^A-Z]*$/,uppercase:/^[^a-z]*$/,hex:/^[0-9a-fA-F]*$/,md5_hex:/^[0-9a-fA-F]{32}$/,md5_base64:s(22,"=="),md5_base64url:o(22),sha1_hex:/^[0-9a-fA-F]{40}$/,sha1_base64:s(27,"="),sha1_base64url:o(27),sha256_hex:/^[0-9a-fA-F]{64}$/,sha256_base64:s(43,"="),sha256_base64url:o(43),sha384_hex:/^[0-9a-fA-F]{96}$/,sha384_base64:s(64,""),sha384_base64url:o(64),sha512_hex:/^[0-9a-fA-F]{128}$/,sha512_base64:s(86,"=="),sha512_base64url:o(86),jwt:/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/,httpUrl:/^https?:\/\/[^\s/$.?#].[^\s]*$/,md5:/^[a-f0-9]{32}$/i,sha1:/^[a-f0-9]{40}$/i,sha256:/^[a-f0-9]{64}$/i,sha384:/^[a-f0-9]{96}$/i,sha512:/^[a-f0-9]{128}$/i};class VldStringFormat extends e.VldBase{constructor(t,r,a,i=e=>e,d){super(e.VLD_VALIDATOR_TYPES.STRING_FORMAT),this._format=t,this._validator=r,this._errorMessage=a,this._normalize=i,this._patternSource=d}static create(e,t,r,a,i){return new VldStringFormat(e,t,r,a,i)}_createFormatIssue(){const e={code:"invalid_format",path:[],origin:"string",format:this._format,message:this._errorMessage||`Invalid ${this._format}`};return this._patternSource&&(e.pattern=this._patternSource),new a.VldError([e])}parse(e){if("string"!=typeof e)throw new a.VldError([a.createInvalidTypeIssue("string",a.getTypeName(e),t.getMessages().invalidString)]);if(!this._validator(e))throw this._createFormatIssue();return this._normalize(e)}safeParse(e){return"string"!=typeof e?{success:!1,error:new a.VldError([a.createInvalidTypeIssue("string",a.getTypeName(e),t.getMessages().invalidString)])}:this._validator(e)?{success:!0,data:this._normalize(e)}:{success:!1,error:this._createFormatIssue()}}}const l=/[ -]/g;function m(e){return!!u.creditCard.test(e)&&function(e){let t=0,r=!1;for(let a=e.length-1;a>=0;a--){let i=e.charCodeAt(a)-48;r&&(i*=2,i>9&&(i-=9)),t+=i,r=!r}return t%10==0}(e.replace(l,""))}const f={ZodISODate:VldStringFormat,ZodISODateTime:VldStringFormat,ZodISODuration:VldStringFormat,ZodISOTime:VldStringFormat,date:()=>VldStringFormat.create("date",e=>d(u.date,e)),time:(e={})=>{const t=u.time(e);return VldStringFormat.create("time",e=>d(t,e))},datetime:(e={})=>{const t=u.datetime(e);return VldStringFormat.create("datetime",e=>d(t,e))},dateTime:(e={local:!0})=>{const t=u.datetime(e);return VldStringFormat.create("datetime",e=>d(t,e))},duration:()=>VldStringFormat.create("duration",e=>d(u.duration,e))};exports.VldStringFormat=VldStringFormat,exports.base64=()=>VldStringFormat.create("base64",e=>d(u.base64,e)),exports.base64url=()=>VldStringFormat.create("base64url",e=>d(u.base64url,e)),exports.cidrv4=()=>VldStringFormat.create("cidrv4",e=>d(u.cidrv4,e)),exports.cidrv6=()=>VldStringFormat.create("cidrv6",e=>{const t=e.lastIndexOf("/");if(t<=0)return!1;const a=Number(e.slice(t+1));return Number.isInteger(a)&&a>=0&&a<=128&&r.isValidIPv6(e.slice(0,t))}),exports.creditCard=e=>VldStringFormat.create("credit_card",m,e?.message,void 0,u.creditCard.source),exports.cuid=()=>VldStringFormat.create("cuid",e=>d(u.cuid,e)),exports.cuid2=()=>VldStringFormat.create("cuid2",e=>d(u.cuid2,e)),exports.e164=()=>VldStringFormat.create("e164",e=>d(u.e164,e)),exports.email=e=>{const t=e?.pattern??u.email;return VldStringFormat.create("email",e=>d(t,e),void 0,void 0,t.source)},exports.emoji=()=>VldStringFormat.create("emoji",e=>d(u.emoji(),e)),exports.guid=()=>VldStringFormat.create("guid",e=>d(u.guid,e)),exports.hash=e=>VldStringFormat.create("hash",t=>u[e]?.test(t)??!1,`Invalid ${e} hash`),exports.hex=()=>VldStringFormat.create("hex",e=>d(u.hex,e)),exports.hostname=()=>VldStringFormat.create("hostname",e=>d(u.hostname,e)),exports.httpUrl=()=>VldStringFormat.create("httpUrl",e=>d(u.httpUrl,e)),exports.ipv4=()=>VldStringFormat.create("ipv4",e=>d(u.ipv4,e)),exports.ipv6=()=>VldStringFormat.create("ipv6",e=>d(u.ipv6,e)),exports.isValidCreditCard=m,exports.iso=f,exports.jwt=()=>VldStringFormat.create("jwt",e=>d(u.jwt,e)),exports.ksuid=()=>VldStringFormat.create("ksuid",e=>d(u.ksuid,e)),exports.mac=e=>{const t=u.mac(e?.delimiter);return VldStringFormat.create("mac",e=>d(t,e))},exports.nanoid=()=>VldStringFormat.create("nanoid",e=>d(u.nanoid,e)),exports.regexes=u,exports.stringFormat=(e,t)=>{const r=t instanceof RegExp?e=>d(t,e):t;return VldStringFormat.create(e,r)},exports.ulid=()=>VldStringFormat.create("ulid",e=>d(u.ulid,e)),exports.url=(e={})=>VldStringFormat.create("url",t=>{const r=(e=>{try{return new URL(e)}catch{return}})(t);return void 0!==r&&(!e.hostname||d(e.hostname,r.hostname))&&(!e.protocol||d(e.protocol,r.protocol.slice(0,-1)))},void 0,e.normalize?e=>new URL(e).href:void 0),exports.uuid=e=>{const t=c(void 0===e?.version?void 0:Number(e.version.slice(1)));return VldStringFormat.create("uuid",e=>d(t,e))},exports.uuidv4=()=>VldStringFormat.create("uuid",e=>d(u.uuid4,e)),exports.uuidv6=()=>VldStringFormat.create("uuid",e=>d(u.uuid6,e)),exports.uuidv7=()=>VldStringFormat.create("uuid",e=>d(u.uuid7,e)),exports.xid=()=>VldStringFormat.create("xid",e=>d(u.xid,e));
|
|
1
|
+
"use strict";var e=require("./base.cjs"),t=require("../locales/runtime.cjs"),r=require("../chunks/ip-validation-BZqPamPC.cjs"),a=require("../chunks/errors-core-C0mA6tfa.cjs");require("../registry.cjs"),require("../locales/en.cjs");const i="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function d(e,t){return e.lastIndex=0,e.test(t)}function o(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function s(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}function n(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"!=typeof e.precision?`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`:-1===e.precision?t:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`}function c(e){return void 0===e?/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/:new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)}const u={cuid:/^[cC][0-9a-z]{6,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid:/^[0-9a-vA-V]{20}$/,ksuid:/^[A-Za-z0-9]{27}$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,nanoidOfLength:e=>new RegExp(`^[a-zA-Z0-9_-]{${e}}$`),duration:/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,extendedDuration:/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,guid:/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,iban:/^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/,currencyCode:/^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/,anyString:/^[\s\S]{0,}$/,creditCard:/^\d(?:[ -]?\d){11,18}$/,uuid:c,uuid4:c(4),uuid6:c(6),uuid7:c(7),email:/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+.-]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/,html5Email:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,rfc5322Email:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}))$/,unicodeEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,idnEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,browserEmail:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,emoji:()=>/^(?=[\s\S]*[\p{Extended_Pictographic}\p{Regional_Indicator}\u20E3])[\p{Extended_Pictographic}\p{Emoji_Component}]+$/u,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,mac:function(e=":"){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},cidrv4:/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6:/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url:/^[A-Za-z0-9_-]*$/,hostname:/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,domain:/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,httpProtocol:/^https?$/,e164:/^\+[1-9]\d{6,14}$/,date:new RegExp(`^${i}$`),time:function(e={}){return new RegExp(`^${n(e)}$`)},datetime:function(e={}){const t=["Z"];return e.local&&t.push(""),e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)"),new RegExp(`^${i}T${n(e)}(?:${t.join("|")})$`)},string:function(e){const t=e?`[\\s\\S]{${e.minimum??0},${e.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},bigint:/^-?\d+n?$/,integer:/^-?\d+$/,number:/^-?\d+(?:\.\d+)?$/,boolean:/^(?:true|false)$/i,null:/^null$/i,undefined:/^undefined$/i,lowercase:/^[^A-Z]*$/,uppercase:/^[^a-z]*$/,hex:/^[0-9a-fA-F]*$/,md5_hex:/^[0-9a-fA-F]{32}$/,md5_base64:o(22,"=="),md5_base64url:s(22),sha1_hex:/^[0-9a-fA-F]{40}$/,sha1_base64:o(27,"="),sha1_base64url:s(27),sha256_hex:/^[0-9a-fA-F]{64}$/,sha256_base64:o(43,"="),sha256_base64url:s(43),sha384_hex:/^[0-9a-fA-F]{96}$/,sha384_base64:o(64,""),sha384_base64url:s(64),sha512_hex:/^[0-9a-fA-F]{128}$/,sha512_base64:o(86,"=="),sha512_base64url:s(86),jwt:/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/,httpUrl:/^https?:\/\/[^\s/$.?#].[^\s]*$/,md5:/^[a-f0-9]{32}$/i,sha1:/^[a-f0-9]{40}$/i,sha256:/^[a-f0-9]{64}$/i,sha384:/^[a-f0-9]{96}$/i,sha512:/^[a-f0-9]{128}$/i};class VldStringFormat extends e.VldBase{constructor(t,r,a,i=e=>e,d){super(e.VLD_VALIDATOR_TYPES.STRING_FORMAT),this._format=t,this._validator=r,this._errorMessage=a,this._normalize=i,this._patternSource=d}static create(e,t,r,a,i){return new VldStringFormat(e,t,r,a,i)}_createFormatIssue(){const e={code:"invalid_format",path:[],origin:"string",format:this._format,message:this._errorMessage||`Invalid ${this._format}`};return this._patternSource&&(e.pattern=this._patternSource),new a.VldError([e])}parse(e){if("string"!=typeof e)throw new a.VldError([a.createInvalidTypeIssue("string",a.getTypeName(e),t.getMessages().invalidString)]);if(!this._validator(e))throw this._createFormatIssue();return this._normalize(e)}safeParse(e){return"string"!=typeof e?{success:!1,error:new a.VldError([a.createInvalidTypeIssue("string",a.getTypeName(e),t.getMessages().invalidString)])}:this._validator(e)?{success:!0,data:this._normalize(e)}:{success:!1,error:this._createFormatIssue()}}}const l=/[ -]/g;function A(e){return!!u.creditCard.test(e)&&function(e){let t=0,r=!1;for(let a=e.length-1;a>=0;a--){let i=e.charCodeAt(a)-48;r&&(i*=2,i>9&&(i-=9)),t+=i,r=!r}return t%10==0}(e.replace(l,""))}function m(e){return!!u.iban.test(e)&&function(e){let t=0;const r=e.length;for(let a=4;a<r;a++){const r=e.charCodeAt(a);t=(r>=65?100*t+(r-55):10*t+(r-48))%97}for(let r=0;r<4;r++){const a=e.charCodeAt(r);t=(a>=65?100*t+(a-55):10*t+(a-48))%97}return 1===t}(e)}const f={ZodISODate:VldStringFormat,ZodISODateTime:VldStringFormat,ZodISODuration:VldStringFormat,ZodISOTime:VldStringFormat,date:()=>VldStringFormat.create("date",e=>d(u.date,e)),time:(e={})=>{const t=u.time(e);return VldStringFormat.create("time",e=>d(t,e))},datetime:(e={})=>{const t=u.datetime(e);return VldStringFormat.create("datetime",e=>d(t,e))},dateTime:(e={local:!0})=>{const t=u.datetime(e);return VldStringFormat.create("datetime",e=>d(t,e))},duration:()=>VldStringFormat.create("duration",e=>d(u.duration,e))};exports.VldStringFormat=VldStringFormat,exports.base64=()=>VldStringFormat.create("base64",e=>d(u.base64,e)),exports.base64Charset=/^[0-9a-zA-Z+/]*={0,2}$/,exports.base64url=()=>VldStringFormat.create("base64url",e=>d(u.base64url,e)),exports.base64urlCharset=/^[A-Za-z0-9_-]*$/,exports.cidrv4=()=>VldStringFormat.create("cidrv4",e=>d(u.cidrv4,e)),exports.cidrv6=()=>VldStringFormat.create("cidrv6",e=>{const t=e.lastIndexOf("/");if(t<=0)return!1;const a=Number(e.slice(t+1));return Number.isInteger(a)&&a>=0&&a<=128&&r.isValidIPv6(e.slice(0,t))}),exports.creditCard=e=>VldStringFormat.create("credit_card",A,e?.message,void 0,u.creditCard.source),exports.cuid=()=>VldStringFormat.create("cuid",e=>d(u.cuid,e)),exports.cuid2=()=>VldStringFormat.create("cuid2",e=>d(u.cuid2,e)),exports.currencyCode=e=>VldStringFormat.create("currency_code",e=>d(u.currencyCode,e),e?.message,void 0,u.currencyCode.source),exports.e164=()=>VldStringFormat.create("e164",e=>d(u.e164,e)),exports.email=e=>{const t=e?.pattern??u.email;return VldStringFormat.create("email",e=>d(t,e),void 0,void 0,t.source)},exports.emoji=()=>VldStringFormat.create("emoji",e=>d(u.emoji(),e)),exports.guid=()=>VldStringFormat.create("guid",e=>d(u.guid,e)),exports.hash=e=>VldStringFormat.create("hash",t=>u[e]?.test(t)??!1,`Invalid ${e} hash`),exports.hex=()=>VldStringFormat.create("hex",e=>d(u.hex,e)),exports.hostname=()=>VldStringFormat.create("hostname",e=>d(u.hostname,e)),exports.httpUrl=()=>VldStringFormat.create("httpUrl",e=>d(u.httpUrl,e)),exports.iban=e=>VldStringFormat.create("iban",m,e?.message,void 0,u.iban.source),exports.ipv4=()=>VldStringFormat.create("ipv4",e=>d(u.ipv4,e)),exports.ipv6=()=>VldStringFormat.create("ipv6",e=>d(u.ipv6,e)),exports.isValidCreditCard=A,exports.isValidIBAN=m,exports.iso=f,exports.jwt=()=>VldStringFormat.create("jwt",e=>d(u.jwt,e)),exports.ksuid=()=>VldStringFormat.create("ksuid",e=>d(u.ksuid,e)),exports.mac=e=>{const t=u.mac(e?.delimiter);return VldStringFormat.create("mac",e=>d(t,e))},exports.nanoid=()=>VldStringFormat.create("nanoid",e=>d(u.nanoid,e)),exports.regexes=u,exports.stringFormat=(e,t)=>{const r=t instanceof RegExp?e=>d(t,e):t;return VldStringFormat.create(e,r)},exports.ulid=()=>VldStringFormat.create("ulid",e=>d(u.ulid,e)),exports.url=(e={})=>VldStringFormat.create("url",t=>{const r=(e=>{try{return new URL(e)}catch{return}})(t);return void 0!==r&&(!e.hostname||d(e.hostname,r.hostname))&&(!e.protocol||d(e.protocol,r.protocol.slice(0,-1)))},void 0,e.normalize?e=>new URL(e).href:void 0),exports.uuid=e=>{const t=c(void 0===e?.version?void 0:Number(e.version.slice(1)));return VldStringFormat.create("uuid",e=>d(t,e))},exports.uuidv4=()=>VldStringFormat.create("uuid",e=>d(u.uuid4,e)),exports.uuidv6=()=>VldStringFormat.create("uuid",e=>d(u.uuid6,e)),exports.uuidv7=()=>VldStringFormat.create("uuid",e=>d(u.uuid7,e)),exports.xid=()=>VldStringFormat.create("xid",e=>d(u.xid,e));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./base.cjs"),s=require("../locales/runtime.cjs"),r=require("../chunks/ip-validation-BZqPamPC.cjs"),t=require("../chunks/errors-core-C0mA6tfa.cjs");require("../registry.cjs"),require("../locales/en.cjs");const i={email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,url:/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,uuidv4:/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,uuidv6:/^[0-9a-f]{8}-[0-9a-f]{4}-6[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,uuidv7:/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,emoji:/^(?:\p{Emoji_Presentation}|\p{Emoji}\uFE0F)(?:\u200D(?:\p{Emoji_Presentation}|\p{Emoji}\uFE0F))*$/u,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,base64url:/^[A-Za-z0-9_-]*$/,jwt:/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/,nanoid:/^[A-Za-z0-9_-]{21}$/,cuid:/^c[^\s-]{8,}$/i,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,cidrv4:/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/(?:3[0-2]|[12]?[0-9])$/,cidrv6:/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$|^::(?:[0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$|^(?:[0-9a-fA-F]{1,4}:){1,7}:\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,e164:/^\+[1-9]\d{1,14}$/,xid:/^[A-HJKMNP-TV-Z0-9]{20}$/,guid:/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i,ksuid:/^[0-9A-Za-z]{27}$/,isoDate:/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/,isoTime:/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?$/,isoDateTime:/^\d{4}-(?: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?$/,isoDuration:/^-?P(?!$)(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?=\d)(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/};class VldString extends e.VldBase{constructor(s){super(s?.validatorType||e.VLD_VALIDATOR_TYPES.STRING),this.config={checks:s?.checks||[],transforms:s?.transforms||[],errorMessage:s?.errorMessage,jsonSchema:s?.jsonSchema,checkMetas:s?.checkMetas},this._checks=this.config.checks,this._transforms=this.config.transforms,this._isSimple=0===this._checks.length&&0===this._transforms.length,this._checkMetas=this.config.checkMetas}static create(){return new VldString}get isSimple(){return this._isSimple}get minLength(){return this.config.jsonSchema?.minLength??null}get maxLength(){return this.config.jsonSchema?.maxLength??null}_createCheckIssue(e){switch(e.kind){case"min":return{code:"too_small",path:[],origin:"string",minimum:e.value,inclusive:!0,message:e.message||`Too small: expected string to have >=${e.value} characters`};case"max":return{code:"too_big",path:[],origin:"string",maximum:e.value,inclusive:!0,message:e.message||`Too big: expected string to have <=${e.value} characters`};case"length":return{code:"too_big",path:[],origin:"string",exact:e.value,message:e.message||`Too big: expected string to have exactly ${e.value} characters`};case"format":{const s={code:"invalid_format",path:[],origin:"string",format:e.format,message:e.message||`Invalid ${e.format}`};return void 0!==e.pattern&&(s.pattern=e.pattern),s}case"regex":{const s={code:"invalid_format",path:[],origin:"string",format:"regex",message:e.message||"Invalid string: does not match pattern"};return void 0!==e.pattern&&(s.pattern=e.pattern),s}default:return{code:"custom",path:[],message:e.message||"Invalid string"}}}_runChecks(e){const s=this._checks,r=this._checkMetas;for(let t=0;t<s.length;t++)if(!s[t](e))return r?.[t]??this._fallbackMeta();return null}_fallbackMeta(){return{kind:"other",message:this.config.errorMessage}}parse(e){if("string"!=typeof e)throw new t.VldError([t.createInvalidTypeIssue("string",t.getTypeName(e),this.config.errorMessage)]);return this._isSimple?e:this.parseKnownString(e)}parseKnownString(e){if(this._isSimple)return e;const s=this._transforms;let r=e;switch(s.length){case 0:break;case 1:r=s[0](r);break;case 2:r=s[1](s[0](r));break;case 3:r=s[2](s[1](s[0](r)));break;default:for(let e=0;e<s.length;e++)r=s[e](r)}const i=this._runChecks(r);if(i)throw new t.VldError([this._createCheckIssue(i)]);return r}safeParse(e){if("string"!=typeof e)return{success:!1,error:new t.VldError([t.createInvalidTypeIssue("string",t.getTypeName(e),this.config.errorMessage)])};if(this._isSimple)return{success:!0,data:e};try{return{success:!0,data:this.parseKnownString(e)}}catch(e){return e instanceof t.VldError?{success:!1,error:e}:{success:!1,error:(s=e.message,new t.VldError([{code:"invalid_string",path:[],message:s}]))}}var s}min(r,t){return new VldString({checks:[...this.config.checks,e=>e.length>=r],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringMin(r)),jsonSchema:{...this.config.jsonSchema,minLength:r},checkMetas:[...this.config.checkMetas??[],{kind:"min",value:r,message:e.resolveErrorMessage(t,s.getMessages().stringMin(r))}]})}max(r,t){return new VldString({checks:[...this.config.checks,e=>e.length<=r],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringMax(r)),jsonSchema:{...this.config.jsonSchema,maxLength:r},checkMetas:[...this.config.checkMetas??[],{kind:"max",value:r,message:e.resolveErrorMessage(t,s.getMessages().stringMax(r))}]})}length(r,t){return new VldString({checks:[...this.config.checks,e=>e.length===r],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringLength(r)),jsonSchema:{...this.config.jsonSchema,exactLength:r},checkMetas:[...this.config.checkMetas??[],{kind:"length",value:r,message:e.resolveErrorMessage(t,s.getMessages().stringLength(r))}]})}email(r){return new VldString({checks:[...this.config.checks,e=>i.email.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringEmail),jsonSchema:{...this.config.jsonSchema,format:"email"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"email",message:e.resolveErrorMessage(r,s.getMessages().stringEmail)}]})}url(r){return new VldString({checks:[...this.config.checks,e=>i.url.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringUrl),jsonSchema:{...this.config.jsonSchema,format:"uri"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"url",message:e.resolveErrorMessage(r,s.getMessages().stringUrl)}]})}uuid(r){return new VldString({checks:[...this.config.checks,e=>i.uuid.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringUuid),jsonSchema:{...this.config.jsonSchema,format:"uuid"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"uuid",message:e.resolveErrorMessage(r,s.getMessages().stringUuid)}]})}format(s,r,t){return new VldString({checks:[...this.config.checks,e=>s.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,`Invalid ${r}`),jsonSchema:{...this.config.jsonSchema,format:r,pattern:s.source},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:r,pattern:s.source,message:e.resolveErrorMessage(t,`Invalid ${r}`)}]})}uuidv4(e){return this.format(i.uuidv4,"uuid",e)}uuidv6(e){return this.format(i.uuidv6,"uuid",e)}uuidv7(e){return this.format(i.uuidv7,"uuid",e)}emoji(e){return this.format(i.emoji,"emoji",e)}base64(e){return this.format(i.base64,"base64",e)}base64url(e){return this.format(i.base64url,"base64url",e)}jwt(e){return this.format(i.jwt,"jwt",e)}nanoid(e){return this.format(i.nanoid,"nanoid",e)}cuid(e){return this.format(i.cuid,"cuid",e)}cuid2(e){return this.format(i.cuid2,"cuid2",e)}ulid(e){return this.format(i.ulid,"ulid",e)}cidrv4(e){return this.format(i.cidrv4,"cidrv4",e)}cidrv6(e){return this.format(i.cidrv6,"cidrv6",e)}e164(e){return this.format(i.e164,"e164",e)}xid(e){return this.format(i.xid,"xid",e)}guid(e){return this.format(i.guid,"guid",e)}ksuid(e){return this.format(i.ksuid,"ksuid",e)}date(e){return this.format(i.isoDate,"date",e)}time(e){return this.format(i.isoTime,"time",e)}datetime(e){return this.format(i.isoDateTime,"datetime",e)}duration(e){return this.format(i.isoDuration,"duration",e)}regex(r,t){return new VldString({checks:[...this.config.checks,e=>r.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringRegex),jsonSchema:{...this.config.jsonSchema,pattern:r.source},checkMetas:[...this.config.checkMetas??[],{kind:"regex",pattern:r.source,message:e.resolveErrorMessage(t,s.getMessages().stringRegex)}]})}trim(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.trim()],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}toLowerCase(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toLowerCase()],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}lowercase(){return this.toLowerCase()}toUpperCase(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toUpperCase()],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}uppercase(){return this.toUpperCase()}normalize(e){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,s=>s.normalize(e)],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}slugify(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}startsWith(r,t){return new VldString({checks:[...this.config.checks,e=>e.startsWith(r)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringStartsWith(r)),jsonSchema:this.config.jsonSchema})}endsWith(r,t){return new VldString({checks:[...this.config.checks,e=>e.endsWith(r)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringEndsWith(r)),jsonSchema:this.config.jsonSchema})}includes(r,t){return new VldString({checks:[...this.config.checks,e=>e.includes(r)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringIncludes(r)),jsonSchema:this.config.jsonSchema})}ip(t){return new VldString({checks:[...this.config.checks,e=>!(e.length>100)&&(i.ipv4.test(e)||r.isValidIPv6(e))],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringIp),jsonSchema:{...this.config.jsonSchema,format:"ip"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"ip",message:e.resolveErrorMessage(t,s.getMessages().stringIp)}]})}ipv4(r){return new VldString({checks:[...this.config.checks,e=>i.ipv4.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringIpv4),jsonSchema:{...this.config.jsonSchema,format:"ipv4"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"ipv4",message:e.resolveErrorMessage(r,s.getMessages().stringIpv4)}]})}ipv6(t){return new VldString({checks:[...this.config.checks,e=>r.isValidIPv6(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringIpv6),jsonSchema:{...this.config.jsonSchema,format:"ipv6"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"ipv6",message:e.resolveErrorMessage(t,s.getMessages().stringIpv6)}]})}nonempty(r){return new VldString({checks:[...this.config.checks,e=>e.length>0],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringEmpty),jsonSchema:{...this.config.jsonSchema,minLength:Math.max(this.config.jsonSchema?.minLength||0,1)},checkMetas:[...this.config.checkMetas??[],{kind:"min",value:1,message:e.resolveErrorMessage(r,s.getMessages().stringEmpty)}]})}}exports.VldString=VldString;
|
|
1
|
+
"use strict";var e=require("./base.cjs"),s=require("../locales/runtime.cjs"),r=require("../chunks/ip-validation-BZqPamPC.cjs"),t=require("../chunks/errors-core-C0mA6tfa.cjs");require("../registry.cjs"),require("../locales/en.cjs");const i=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,a={email:i,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,url:/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,uuidv4:/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,uuidv6:/^[0-9a-f]{8}-[0-9a-f]{4}-6[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,uuidv7:/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,emoji:/^(?=[\s\S]*[\p{Extended_Pictographic}\p{Regional_Indicator}\u20E3])[\p{Extended_Pictographic}\p{Emoji_Component}]+$/u,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,base64url:/^[A-Za-z0-9_-]*$/,jwt:/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/,nanoid:/^[A-Za-z0-9_-]{21}$/,cuid:/^c[^\s-]{8,}$/i,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,cidrv4:/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/(?:3[0-2]|[12]?[0-9])$/,cidrv6:/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$|^::(?:[0-9a-fA-F]{1,4}:){0,6}[0-9a-fA-F]{1,4}\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$|^(?:[0-9a-fA-F]{1,4}:){1,7}:\/(?:12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,e164:/^\+[1-9]\d{1,14}$/,xid:/^[A-HJKMNP-TV-Z0-9]{20}$/,guid:/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i,ksuid:/^[0-9A-Za-z]{27}$/,isoDate:/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/,isoTime:/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?$/,isoDateTime:/^\d{4}-(?: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?$/,isoDuration:/^-?P(?!$)(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?=\d)(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/},n={email:{source:i.source,flags:i.flags},url:{source:a.url.source,flags:a.url.flags},uuid:{source:a.uuid.source,flags:a.uuid.flags}};class VldString extends e.VldBase{constructor(s){super(s?.validatorType||e.VLD_VALIDATOR_TYPES.STRING),this.config={checks:s?.checks||[],transforms:s?.transforms||[],errorMessage:s?.errorMessage,jsonSchema:s?.jsonSchema,checkMetas:s?.checkMetas},this._checks=this.config.checks,this._transforms=this.config.transforms,this._isSimple=0===this._checks.length&&0===this._transforms.length,this._checkMetas=this.config.checkMetas}static create(){return new VldString}get isSimple(){return this._isSimple}get minLength(){return this.config.jsonSchema?.minLength??null}get maxLength(){return this.config.jsonSchema?.maxLength??null}_createCheckIssue(e){switch(e.kind){case"min":return{code:"too_small",path:[],origin:"string",minimum:e.value,inclusive:!0,message:e.message||`Too small: expected string to have >=${e.value} characters`};case"max":return{code:"too_big",path:[],origin:"string",maximum:e.value,inclusive:!0,message:e.message||`Too big: expected string to have <=${e.value} characters`};case"length":return{code:"too_big",path:[],origin:"string",exact:e.value,message:e.message||`Too big: expected string to have exactly ${e.value} characters`};case"format":{const s={code:"invalid_format",path:[],origin:"string",format:e.format,message:e.message||`Invalid ${e.format}`};return void 0!==e.pattern&&(s.pattern=e.pattern),s}case"regex":{const s={code:"invalid_format",path:[],origin:"string",format:"regex",message:e.message||"Invalid string: does not match pattern"};return void 0!==e.pattern&&(s.pattern=e.pattern),s}default:return{code:"custom",path:[],message:e.message||"Invalid string"}}}_runChecks(e){const s=this._checks,r=this._checkMetas;for(let t=0;t<s.length;t++)if(!s[t](e))return r?.[t]??this._fallbackMeta();return null}_fallbackMeta(){return{kind:"other",message:this.config.errorMessage}}parse(e){if("string"!=typeof e)throw new t.VldError([t.createInvalidTypeIssue("string",t.getTypeName(e),this.config.errorMessage)]);return this._isSimple?e:this.parseKnownString(e)}parseKnownString(e){if(this._isSimple)return e;const s=this._transforms;let r=e;switch(s.length){case 0:break;case 1:r=s[0](r);break;case 2:r=s[1](s[0](r));break;case 3:r=s[2](s[1](s[0](r)));break;default:for(let e=0;e<s.length;e++)r=s[e](r)}const i=this._runChecks(r);if(i)throw new t.VldError([this._createCheckIssue(i)]);return r}safeParse(e){if("string"!=typeof e)return{success:!1,error:new t.VldError([t.createInvalidTypeIssue("string",t.getTypeName(e),this.config.errorMessage)])};if(this._isSimple)return{success:!0,data:e};try{return{success:!0,data:this.parseKnownString(e)}}catch(e){return e instanceof t.VldError?{success:!1,error:e}:{success:!1,error:(s=e.message,new t.VldError([{code:"invalid_string",path:[],message:s}]))}}var s}min(r,t){return new VldString({checks:[...this.config.checks,e=>e.length>=r],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringMin(r)),jsonSchema:{...this.config.jsonSchema,minLength:r},checkMetas:[...this.config.checkMetas??[],{kind:"min",value:r,message:e.resolveErrorMessage(t,s.getMessages().stringMin(r))}]})}max(r,t){return new VldString({checks:[...this.config.checks,e=>e.length<=r],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringMax(r)),jsonSchema:{...this.config.jsonSchema,maxLength:r},checkMetas:[...this.config.checkMetas??[],{kind:"max",value:r,message:e.resolveErrorMessage(t,s.getMessages().stringMax(r))}]})}length(r,t){return new VldString({checks:[...this.config.checks,e=>e.length===r],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringLength(r)),jsonSchema:{...this.config.jsonSchema,exactLength:r},checkMetas:[...this.config.checkMetas??[],{kind:"length",value:r,message:e.resolveErrorMessage(t,s.getMessages().stringLength(r))}]})}email(r){return new VldString({checks:[...this.config.checks,e=>a.email.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringEmail),jsonSchema:{...this.config.jsonSchema,format:"email"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"email",message:e.resolveErrorMessage(r,s.getMessages().stringEmail)}]})}url(r){return new VldString({checks:[...this.config.checks,e=>a.url.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringUrl),jsonSchema:{...this.config.jsonSchema,format:"uri"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"url",message:e.resolveErrorMessage(r,s.getMessages().stringUrl)}]})}uuid(r){return new VldString({checks:[...this.config.checks,e=>a.uuid.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringUuid),jsonSchema:{...this.config.jsonSchema,format:"uuid"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"uuid",message:e.resolveErrorMessage(r,s.getMessages().stringUuid)}]})}format(s,r,t){return new VldString({checks:[...this.config.checks,e=>s.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,`Invalid ${r}`),jsonSchema:{...this.config.jsonSchema,format:r,pattern:s.source},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:r,pattern:s.source,flags:s.flags,message:e.resolveErrorMessage(t,`Invalid ${r}`)}]})}uuidv4(e){return this.format(a.uuidv4,"uuid",e)}uuidv6(e){return this.format(a.uuidv6,"uuid",e)}uuidv7(e){return this.format(a.uuidv7,"uuid",e)}emoji(e){return this.format(a.emoji,"emoji",e)}base64(e){return this.format(a.base64,"base64",e)}base64url(e){return this.format(a.base64url,"base64url",e)}jwt(e){return this.format(a.jwt,"jwt",e)}nanoid(e){return this.format(a.nanoid,"nanoid",e)}cuid(e){return this.format(a.cuid,"cuid",e)}cuid2(e){return this.format(a.cuid2,"cuid2",e)}ulid(e){return this.format(a.ulid,"ulid",e)}cidrv4(e){return this.format(a.cidrv4,"cidrv4",e)}cidrv6(e){return this.format(a.cidrv6,"cidrv6",e)}e164(e){return this.format(a.e164,"e164",e)}xid(e){return this.format(a.xid,"xid",e)}guid(e){return this.format(a.guid,"guid",e)}ksuid(e){return this.format(a.ksuid,"ksuid",e)}date(e){return this.format(a.isoDate,"date",e)}time(e){return this.format(a.isoTime,"time",e)}datetime(e){return this.format(a.isoDateTime,"datetime",e)}duration(e){return this.format(a.isoDuration,"duration",e)}regex(r,t){return new VldString({checks:[...this.config.checks,e=>r.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringRegex),jsonSchema:{...this.config.jsonSchema,pattern:r.source},checkMetas:[...this.config.checkMetas??[],{kind:"regex",pattern:r.source,flags:r.flags,message:e.resolveErrorMessage(t,s.getMessages().stringRegex)}]})}trim(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.trim()],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}toLowerCase(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toLowerCase()],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}lowercase(){return this.toLowerCase()}toUpperCase(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toUpperCase()],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}uppercase(){return this.toUpperCase()}normalize(e){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,s=>s.normalize(e)],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}slugify(){return new VldString({checks:this.config.checks,transforms:[...this.config.transforms,e=>e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")],errorMessage:this.config.errorMessage,jsonSchema:this.config.jsonSchema})}startsWith(r,t){return new VldString({checks:[...this.config.checks,e=>e.startsWith(r)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringStartsWith(r)),jsonSchema:this.config.jsonSchema})}endsWith(r,t){return new VldString({checks:[...this.config.checks,e=>e.endsWith(r)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringEndsWith(r)),jsonSchema:this.config.jsonSchema})}includes(r,t){return new VldString({checks:[...this.config.checks,e=>e.includes(r)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringIncludes(r)),jsonSchema:this.config.jsonSchema})}ip(t){return new VldString({checks:[...this.config.checks,e=>!(e.length>100)&&(a.ipv4.test(e)||r.isValidIPv6(e))],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringIp),jsonSchema:{...this.config.jsonSchema,format:"ip"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"ip",message:e.resolveErrorMessage(t,s.getMessages().stringIp)}]})}ipv4(r){return new VldString({checks:[...this.config.checks,e=>a.ipv4.test(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringIpv4),jsonSchema:{...this.config.jsonSchema,format:"ipv4"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"ipv4",message:e.resolveErrorMessage(r,s.getMessages().stringIpv4)}]})}ipv6(t){return new VldString({checks:[...this.config.checks,e=>r.isValidIPv6(e)],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(t,s.getMessages().stringIpv6),jsonSchema:{...this.config.jsonSchema,format:"ipv6"},checkMetas:[...this.config.checkMetas??[],{kind:"format",format:"ipv6",message:e.resolveErrorMessage(t,s.getMessages().stringIpv6)}]})}nonempty(r){return new VldString({checks:[...this.config.checks,e=>e.length>0],transforms:this.config.transforms,errorMessage:e.resolveErrorMessage(r,s.getMessages().stringEmpty),jsonSchema:{...this.config.jsonSchema,minLength:Math.max(this.config.jsonSchema?.minLength||0,1)},checkMetas:[...this.config.checkMetas??[],{kind:"min",value:1,message:e.resolveErrorMessage(r,s.getMessages().stringEmpty)}]})}}exports.COMPILABLE_FORMATS=n,exports.VldString=VldString;
|
package/dist/cli/bin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{vldCli as e}from"./index.js";import*as o from"fs";import{readFileSync as s}from"fs";import*as r from"path";import a from"../pigment.js";import{prettifyError as t,prettifyErrorColored as n}from"../errors.js";import i from"../index.js";function c(e,o,s){const a=process.cwd();if(!e.startsWith(a+r.sep)&&e!==a)throw new Error(`${o} path escapes allowed directory: ${s}`)}const l={name:"validate",description:"Validate JSON data against a VLD schema",aliases:["v"],arguments:[{name:"schema",description:"Path to schema file (.ts or .js)",required:!0},{name:"data",description:"Path to JSON data file or JSON string",required:!0}],options:[{name:"strict",short:"s",description:"Enable strict mode (no extra keys)",type:"boolean",default:!1},{name:"quiet",short:"q",description:"Only output errors",type:"boolean",default:!1},{name:"json",short:"j",description:"Output as JSON",type:"boolean",default:!1},{name:"no-color",description:"Disable colored output",type:"boolean",default:!1}],action:async(e,s)=>{const i=e.schema,l=e.data,m=s.quiet,p=s.json,d=s["no-color"];let u,f;try{const e=r.resolve(process.cwd(),i);if(c(e,"Schema",i),!o.existsSync(e))throw new Error(`Schema file not found: ${i}`);const s=await
|
|
2
|
+
import{vldCli as e}from"./index.js";import*as o from"fs";import{readFileSync as s}from"fs";import*as r from"path";import a from"../pigment.js";import{prettifyError as t,prettifyErrorColored as n}from"../errors.js";import i from"../index.js";function c(e,o,s){const a=process.cwd();if(!e.startsWith(a+r.sep)&&e!==a)throw new Error(`${o} path escapes allowed directory: ${s}`)}const l={name:"validate",description:"Validate JSON data against a VLD schema",aliases:["v"],arguments:[{name:"schema",description:"Path to schema file (.ts or .js)",required:!0},{name:"data",description:"Path to JSON data file or JSON string",required:!0}],options:[{name:"strict",short:"s",description:"Enable strict mode (no extra keys)",type:"boolean",default:!1},{name:"quiet",short:"q",description:"Only output errors",type:"boolean",default:!1},{name:"json",short:"j",description:"Output as JSON",type:"boolean",default:!1},{name:"no-color",description:"Disable colored output",type:"boolean",default:!1}],action:async(e,s)=>{const i=e.schema,l=e.data,m=s.quiet,p=s.json,d=s["no-color"];let u,f;try{const e=r.resolve(process.cwd(),i);if(c(e,"Schema",i),!o.existsSync(e))throw new Error(`Schema file not found: ${i}`);const s=await import(e);if(u=s.default||s.schema||s,!u||"function"!=typeof u.parse)throw new Error("Schema must export a VLD validator with parse() method")}catch(e){return p?console.log(JSON.stringify({success:!1,error:e.message})):console.error(a.red("Schema Error:"),e.message),void(process.exitCode=1)}try{if(l.startsWith("{")||l.startsWith("["))f=JSON.parse(l);else{const e=r.resolve(process.cwd(),l);if(c(e,"Data",l),!o.existsSync(e))throw new Error(`Data file not found: ${l}`);const s=o.readFileSync(e,"utf-8");f=JSON.parse(s)}}catch(e){return p?console.log(JSON.stringify({success:!1,error:e.message})):console.error(a.red("Data Error:"),e.message),void(process.exitCode=1)}const g=u.safeParse(f);if(p)if(g.success)console.log(JSON.stringify({success:!0,data:g.data}));else{const e=g.error,o={success:!1,error:e?.message,issues:e?.issues};console.log(JSON.stringify(o))}else if(g.success)m||(console.log(a.green("Validation passed")),console.log(""),console.log(a.dim("Data:")),console.log(JSON.stringify(g.data,null,2)));else{if(console.error(a.red("Validation failed")),console.error(""),g.error&&"issues"in g.error){const e=d?t(g.error,{colored:!1}):n(g.error);console.error(e)}else console.error(g.error?.message||"Unknown error");process.exitCode=1}}};function m(e,o,s){for(let e=0;e<Math.min(100,s/10);e++)o();const r=performance.now();for(let e=0;e<s;e++)o();const a=performance.now()-r,t=a/s;return{name:e,iterations:s,totalMs:a,avgMs:t,opsPerSec:1e3/t}}function p(e){return e.toLocaleString("en-US",{maximumFractionDigits:2})}function d(e,o){return`${o?a.cyan(e.name.padEnd(30)):e.name.padEnd(30)} ${o?a.green(p(e.opsPerSec).padStart(12)):p(e.opsPerSec).padStart(12)} ops/sec ${o?a.yellow(e.avgMs.toFixed(6).padStart(12)):e.avgMs.toFixed(6).padStart(12)} ms/op`}const u={name:"benchmark",description:"Run performance benchmarks",aliases:["bench","b"],options:[{name:"iterations",short:"n",description:"Number of iterations",type:"number",default:1e4},{name:"suite",short:"s",description:"Benchmark suite to run (all, primitives, objects, arrays)",type:"string",default:"all"},{name:"json",short:"j",description:"Output as JSON",type:"boolean",default:!1},{name:"no-color",description:"Disable colored output",type:"boolean",default:!1}],action:async(e,o)=>{const s=o.iterations,r=o.suite,t=o.json,n=!o["no-color"],c=[],l=i.string(),u=i.number(),f=i.boolean(),g=i.date(),h=i.object({name:i.string(),email:i.string(),age:i.number(),active:i.boolean()}),b=i.array(i.number()),S=i.object({user:i.object({name:i.string(),email:i.string()}),items:i.array(i.object({id:i.number(),name:i.string(),price:i.number()}))}),y="hello world",v=new Date,j={name:"John",email:"john@example.com",age:30,active:!0},w=[1,2,3,4,5,6,7,8,9,10],O={user:{name:"John",email:"john@example.com"},items:[{id:1,name:"Item 1",price:10.99},{id:2,name:"Item 2",price:20.99},{id:3,name:"Item 3",price:30.99}]};if(t||(console.log(a.bold("VLD Performance Benchmark")),console.log(a.dim(`Running ${p(s)} iterations per test`)),console.log("")),("all"===r||"primitives"===r)&&(t||console.log(a.bold("Primitives:")),c.push(m("string.parse()",()=>l.parse(y),s)),c.push(m("number.parse()",()=>u.parse(42),s)),c.push(m("boolean.parse()",()=>f.parse(true),s)),c.push(m("date.parse()",()=>g.parse(v),s)),c.push(m("string.safeParse()",()=>l.safeParse(y),s)),!t)){for(const e of c.slice(-5))console.log(" "+d(e,n));console.log("")}if(("all"===r||"objects"===r)&&(t||console.log(a.bold("Objects:")),c.push(m("object.parse()",()=>h.parse(j),s)),c.push(m("object.safeParse()",()=>h.safeParse(j),s)),c.push(m("nested.parse()",()=>S.parse(O),s)),!t)){for(const e of c.slice(-3))console.log(" "+d(e,n));console.log("")}if(("all"===r||"arrays"===r)&&(t||console.log(a.bold("Arrays:")),c.push(m("array.parse()",()=>b.parse(w),s)),c.push(m("array.safeParse()",()=>b.safeParse(w),s)),!t)){for(const e of c.slice(-2))console.log(" "+d(e,n));console.log("")}if(t)console.log(JSON.stringify({iterations:s,suite:r,results:c.map(e=>({name:e.name,iterations:e.iterations,totalMs:e.totalMs,avgMs:e.avgMs,opsPerSec:e.opsPerSec}))}));else{const e=c.reduce((e,o)=>e+o.opsPerSec,0)/c.length;console.log(a.bold("Summary:")),console.log(` Total benchmarks: ${c.length}`),console.log(` Average ops/sec: ${p(e)}`)}}},f=JSON.parse(s(new URL("../../package.json",import.meta.url),"utf-8")).version||"0.0.0";e.version=f,e.command(l),e.command(u),e.command({name:"help",description:"Show help information",aliases:["h"],action:()=>{console.log(e.help())}}),e.command({name:"version",description:"Show version information",action:()=>{console.log(`vld v${f}`)}}),e.run(process.argv.slice(2)).catch(e=>{console.error("Fatal error:",e),process.exitCode=1});
|
package/dist/compile.d.ts
CHANGED
|
@@ -71,6 +71,21 @@ export declare function applyCompiled<T extends VldBase<any, any>>(schema: T, co
|
|
|
71
71
|
export declare function compile<T extends VldBase<any, any>>(schema: T, options?: {
|
|
72
72
|
JITless?: boolean;
|
|
73
73
|
}): T;
|
|
74
|
+
/**
|
|
75
|
+
* Zod 4.6 `z.withParser()`: install an externally generated parser as a
|
|
76
|
+
* schema's fast path. Returns a clone; the original schema is unchanged.
|
|
77
|
+
*
|
|
78
|
+
* The parser takes the input and returns the parsed value, or `INVALID`
|
|
79
|
+
* (the exported sentinel) to hand the parse to the runtime. It must be
|
|
80
|
+
* synchronous and forward-direction, and it must build fresh output rather
|
|
81
|
+
* than return its input - vld cannot check either, and a wrong *success*
|
|
82
|
+
* is returned to the caller as-is.
|
|
83
|
+
*
|
|
84
|
+
* This is the escape hatch for build-time or native compilers in CSP
|
|
85
|
+
* environments where `new Function` (and therefore `z.compile()`) is
|
|
86
|
+
* unavailable.
|
|
87
|
+
*/
|
|
88
|
+
export declare function withParser<T extends VldBase<any, any>>(schema: T, parser: (input: unknown) => unknown): T;
|
|
74
89
|
export declare function validate(schema: VldBase<any, any>, value: unknown): boolean;
|
|
75
90
|
export declare function validateAsync(schema: VldBase<any, any>, value: unknown): Promise<boolean>;
|
|
76
91
|
export declare function properties<T extends Record<string, VldBase<any, any>>>(shape: T): VldObject<Partial<{
|
package/dist/compile.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as t}from"./validators/base.js";import{VldString as e}from"./validators/string.js";import{VldNumber as i}from"./validators/number.js";import{VldBoolean as r}from"./validators/boolean.js";import{VldBigInt as n}from"./validators/bigint.js";import{VldUndefined as s}from"./validators/undefined.js";import{VldNull as o}from"./validators/null.js";import{VldObject as a}from"./validators/object.js";import{VldArray as u}from"./validators/array.js";import{VldUnknown as l}from"./validators/unknown.js";class h extends Error{constructor(t){super(t),this.name="ZodCompileError"}}class c extends h{constructor(t="Cannot compile async schema"){super(t),this.name="ZodCompileAsyncError"}}class f extends h{constructor(t="Schema node is not supported by the AOT compiler"){super(t),this.name="ZodCompileUnsupportedError"}}const $=Symbol.for("@oxog/vld/compile-invalid");const d=t=>{const e=new WeakMap;return i=>{const r=e.get(i);if(void 0!==r)return r;const n=t(i);return e.set(i,n),n}};function v(t){return t&&t.constructor&&t.constructor.name||""}function p(t,e){return`__${e}${t.scratch++}`}function _(t,e,i){if(!i.failed){if("VldString"===v(t)){const r=t._checks,n=t._checkMetas,s=[];if(n)for(const t of n)switch(t.kind){case"min":s.push(`__v.length >= ${t.value}`);break;case"max":s.push(`__v.length <= ${t.value}`);break;case"length":s.push(`__v.length === ${t.value}`);break;case"regex":{const e=(t.pattern??t.value?.source??String(t.value)).replace(/\\/g,"\\\\").replace(/\//g,"\\/");s.push(`/${e}/.test(__v)`);break}case"startsWith":s.push(`__v.startsWith(${JSON.stringify(t.value)})`);break;case"endsWith":s.push(`__v.endsWith(${JSON.stringify(t.value)})`);break;case"includes":s.push(`__v.includes(${JSON.stringify(t.value)})`);break;case"email":case"url":case"uuid":case"ip":break;default:if(r&&r.length>0)return void(i.failed=!0)}else if(r&&r.length>0)return void(i.failed=!0);return void(0===s.length?i.hoist.push(`if (typeof ${e} !== "string") ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+e};`):i.hoist.push(`{ const __v = ${e}; if (typeof __v !== "string" || !(${s.join(" && ")})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = __v; }`))}if("VldNumber"===v(t)){const r=t._checks,n=t._checkMetas,s=[];if(n)for(const t of n)switch(t.kind){case"int":s.push("Number.isInteger(__v)");break;case"finite":s.push("Number.isFinite(__v)");break;case"min":s.push(!1!==t.inclusive?`__v >= ${t.value}`:`__v > ${t.value}`);break;case"max":s.push(!1!==t.inclusive?`__v <= ${t.value}`:`__v < ${t.value}`);break;case"gt":s.push(`__v > ${t.value}`);break;case"gte":s.push(`__v >= ${t.value}`);break;case"lt":s.push(`__v < ${t.value}`);break;case"lte":s.push(`__v <= ${t.value}`);break;case"multipleOf":s.push(`__v % ${t.value} === 0`);break;case"positive":s.push("__v > 0");break;case"negative":s.push("__v < 0");break;case"nonnegative":s.push("__v >= 0");break;case"nonpositive":s.push("__v <= 0");break;case"safe":s.push("Number.isSafeInteger(__v)");break;default:if(r&&r.length>0)return void(i.failed=!0)}else if(r&&r.length>0)return void(i.failed=!0);const o=['typeof __v === "number"',"!Number.isNaN(__v)",...s];return void i.hoist.push(`{ const __v = ${e}; if (!(${o.join(" && ")})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = __v; }`)}if("VldBoolean"!==v(t)){if("VldBigInt"===v(t)){const r=t._checks,n=t._checkMetas,s=[];if(n)for(const t of n)switch(t.kind){case"min":s.push(`__v >= ${t.value}n`);break;case"max":s.push(`__v <= ${t.value}n`);break;case"positive":s.push("__v > 0n");break;case"negative":s.push("__v < 0n");break;case"nonnegative":s.push("__v >= 0n");break;case"nonpositive":s.push("__v <= 0n");break;default:if(r&&r.length>0)return void(i.failed=!0)}else if(r&&r.length>0)return void(i.failed=!0);const o=['typeof __v === "bigint"',...s];return void i.hoist.push(`{ const __v = ${e}; if (!(${o.join(" && ")})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = __v; }`)}if("VldDate"!==v(t))if("VldNull"!==v(t))if("VldUndefined"!==v(t))if("VldAny"!==v(t)&&"VldUnknown"!==v(t)){if("VldLiteral"===v(t)){const r=t._values||[];if(0===r.length)return void i.hoist.push(`${i.throwOnFail?"throw":"return"} ${i.invalid};`);if(1===r.length){const t=r[0],n="number"==typeof t&&Number.isNaN(t)?"NaN":JSON.stringify(t);return void i.hoist.push(`if (!Object.is(${n}, ${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+e};`)}const n=p(i,"set");return i.hoist.push(`const ${n} = new Set([${r.map(t=>"number"==typeof t&&Number.isNaN(t)?"NaN":JSON.stringify(t)).join(",")}]);`),void i.hoist.push(`if (!${n}.has(${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+e};`)}if("VldEnum"===v(t)){const r=t._values||[],n=p(i,"set");return i.hoist.push(`const ${n} = new Set([${r.map(t=>JSON.stringify(t)).join(",")}]);`),void i.hoist.push(`if (!${n}.has(${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+e};`)}if("VldOptional"===v(t)){const r=t.baseValidator;return i.hoist.push(`if (${e} === undefined) { ${i.outParam} = undefined; } else {`),_(r,e,i),void i.hoist.push("}")}if("VldArray"===v(t)){const r=t.config?.itemValidator??t.config?.element;if(!r)return void(i.failed=!0);const n=p(i,"arr"),s=p(i,"i");if("VldObject"===v(r)){if(i.hoist.push(`if (!Array.isArray(${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid};`),i.validateOnly){if(i.hoist.push(`for (let ${s} = 0; ${s} < ${e}.length; ${s}++) {`),_(r,`${e}[${s}]`,i),i.failed)return;return i.hoist.push("}"),void i.hoist.push(`${i.outParam} = true;`)}i.hoist.push(`const ${n} = new Array(${e}.length);`);const t={invalid:i.invalid,outParam:"__slot",scratch:0,hoist:[],failed:!1,skipOutAssign:!0};return t.hoist.push(`for (let ${s} = 0; ${s} < ${e}.length; ${s}++) {`," let __slot;"),_(r,`${e}[${s}]`,t),t.failed?void(i.failed=!0):(t.hoist.push(` ${n}[${s}] = __slot;`,"}"),i.hoist.push(...t.hoist),void i.hoist.push(`${i.outParam} = ${n};`))}const o=p(i,"it");if(i.hoist.push(`if (!Array.isArray(${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid};`),i.validateOnly)return i.hoist.push(`for (let ${s} = 0; ${s} < ${e}.length; ${s}++) {`,` const ${o} = ${e}[${s}];`),_(r,o,i),i.hoist.push("}"),void i.hoist.push(`${i.outParam} = true;`);if(i.hoist.push(`const ${n} = new Array(${e}.length);`,`for (let ${s} = 0; ${s} < ${e}.length; ${s}++) {`),_(r,`${e}[${s}]`,i),i.failed)return;return void i.hoist.push(` ${n}[${s}] = ${e}[${s}];`,"}",`${i.outParam} = ${n};`)}if("VldTuple"===v(t)){const r=t.validators.filter(t=>Boolean(t)),n=t.restValidator,s=p(i,"tup"),o=n?`${e}.length < ${r.length}`:`${e}.length !== ${r.length}`;if(i.hoist.push(`if (!Array.isArray(${e}) || ${o}) ${i.throwOnFail?"throw":"return"} ${i.invalid};`),i.validateOnly){for(let t=0;t<r.length;t++){const n=r[t];if(!n)return void(i.failed=!0);if(_(n,`${e}[${t}]`,i),i.failed)return}if(n){const t=p(i,"i");i.hoist.push(`for (let ${t} = ${r.length}; ${t} < ${e}.length; ${t}++) {`),_(n,`${e}[${t}]`,i),i.hoist.push("}")}return void i.hoist.push(`${i.outParam} = true;`)}i.hoist.push(`const ${s} = new Array(${e}.length);`);for(let t=0;t<r.length;t++){const n=r[t];if(!n)return void(i.failed=!0);const o=p(i,"it");i.hoist.push(`{ const ${o} = ${e}[${t}];`);const a=i.skipOutAssign??!1;i.skipOutAssign=!0,_(n,o,i),i.skipOutAssign=a,i.hoist.push(` ${s}[${t}] = ${o}; }`)}if(n){const t=p(i,"i"),o=p(i,"it");i.hoist.push(`for (let ${t} = ${r.length}; ${t} < ${e}.length; ${t}++) {`,` const ${o} = ${e}[${t}];`);const a=i.skipOutAssign??!1;i.skipOutAssign=!0,_(n,o,i),i.skipOutAssign=a,i.hoist.push(` ${s}[${t}] = ${o}; }`)}return void i.hoist.push(`${i.outParam} = ${s};`)}if("VldObject"===v(t)){const r=t._config?.shape;if(!r)return void(i.failed=!0);const n=p(i,"o");if(i.hoist.push(`if (typeof ${e} !== "object" || ${e} === null || Array.isArray(${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid};`),i.validateOnly){for(const t of Object.keys(r)){const n=r[t];if(!n)return void(i.failed=!0);if(_(n,`${e}${/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`.${t}`:`[${JSON.stringify(t)}]`}`,i),i.failed)return}return void i.hoist.push(`${i.outParam} = true;`)}i.hoist.push(`const ${n} = {};`);for(const t of Object.keys(r)){const s=r[t];if(!s)return void(i.failed=!0);const o=/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`.${t}`:`[${JSON.stringify(t)}]`,a=p(i,"p");i.hoist.push(`{ const ${a} = ${e}${o};`);const u=i.skipOutAssign??!1;i.skipOutAssign=!0,_(s,a,i),i.skipOutAssign=u,i.hoist.push(` ${n}${o} = ${a}; }`)}return void i.hoist.push(`${i.outParam} = ${n};`)}if("VldRecord"===v(t)){const r=t.keyValidator,n=t.valueValidator,s=p(i,"rec"),o=p(i,"ks"),a=p(i,"i"),u=p(i,"k"),l=p(i,"v");return i.hoist.push(`if (typeof ${e} !== "object" || ${e} === null || Array.isArray(${e})) ${i.throwOnFail?"throw":"return"} ${i.invalid};`,`const ${s} = {};`,`const ${o} = Object.keys(${e});`,`for (let ${a} = 0; ${a} < ${o}.length; ${a}++) {`,` let ${u} = ${o}[${a}];`),_(r,u,i),i.hoist.push(` let ${l} = ${e}[${o}[${a}]];`),_(n,l,i),void i.hoist.push(` ${s}[${u}] = ${l};`,"}",""+(i.validateOnly?i.outParam+" = true; ":i.outParam+" = "+s+";"))}if("VldUnion"===v(t)){const e=t.validators.filter(t=>Boolean(t));if(0===e.length)return void(i.failed=!0);const r=p(i,"u");i.hoist.push(`let ${r} = ${i.invalid};`);for(let t=0;t<e.length;t++){const n=e[t],s=v(n);if("VldString"===s){i.hoist.push(`if (typeof value === "string") { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through to next option */ }`);continue}if("VldNumber"===s){i.hoist.push(`if (typeof value === "number" && value === value) { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}if("VldBoolean"===s){i.hoist.push(`if (typeof value === "boolean") { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}if("VldNull"===s){i.hoist.push(`if (value === null) { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}if("VldUndefined"===s){i.hoist.push(`if (value === undefined) { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}if("VldLiteral"===s){const t=n._values||[];if(1===t.length){const e=t[0],n="number"==typeof e&&Number.isNaN(e)?"NaN":JSON.stringify(e);i.hoist.push(`if (Object.is(${n}, value)) { ${r} = value; }`,`else if (${r} === ${i.invalid}) { /* fall through */ }`);continue}}const o={invalid:i.invalid,outParam:r,scratch:0,hoist:[],failed:!1,skipOutAssign:!0};if(_(n,"value",o),o.failed)return void(i.failed=!0);i.hoist.push(`${r} = ((value) => {`,...o.hoist.map(t=>" "+t)," return value;","})(value);",`if (${r} !== ${i.invalid}) { /* matched */ }`)}return void i.hoist.push(`if (${r} === ${i.invalid}) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = ${r};`)}i.failed=!0}else i.hoist.push((i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+e)+";");else i.hoist.push(`if (${e} !== undefined) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = undefined;`);else i.hoist.push(`if (${e} !== null) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = null;`);else i.hoist.push(`{ const __v = ${e}; if (!(__v instanceof Date) || __v.getTime() !== __v.getTime()) ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.outParam} = __v; }`)}else i.hoist.push(`if (typeof ${e} !== "boolean") ${i.throwOnFail?"throw":"return"} ${i.invalid}; ${i.validateOnly?i.outParam+" = true; ":(i.skipOutAssign?"":i.outParam+" = ")+e};`)}}function g(t,e){if(!t||"function"!=typeof t.parse)return null;const i=!!e?.validateOnly,r={invalid:"__INV",outParam:i?"__ok":"__out",scratch:0,hoist:[],failed:!1,validateOnly:i};if(r.hoist.push(i?"let __ok;":"let __out;"),_(t,"value",r),r.failed)return"1"===process.env.VLD_COMPILE_DEBUG&&console.error("[compile] failed to lower schema; partial body:\n"+r.hoist.join("\n")),null;r.hoist.push(i?"return __ok;":"return __out;");const n=r.hoist.join("\n"),s=new Function("value",r.invalid,n),o=t=>s(t,$);return Object.defineProperty(o,"__vld_compiled",{value:!0,enumerable:!1}),o}function m(t){return g(t,{validateOnly:!0})}function b(t,e,i){const r=t.parse.bind(t),n=t.safeParse.bind(t),s=$,o=i??e;return t.parse=t=>o(t)===s?r(t):t,t.safeParse=t=>o(t)===s?n(t):{success:!0,data:t},Object.defineProperty(t,"_zod",{value:{bag:{validator:e,validatorValidate:i}},enumerable:!1,configurable:!0}),t}function y(t,e){const i=t?._zod?.bag?.validator;if(i)return t;const r=function(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}(t);if(e?.JITless)return Object.defineProperty(r,"_zod",{value:{bag:{}},enumerable:!1,configurable:!0}),r;const n=m(r);return n?b(r,n,n):r}function O(t,e){const i=t?._zod?.bag?.validatorValidate??t?._zod?.bag?.validator;if(i)try{return i(e)!==$}catch{return!1}const r=t.safeParse(e);return Boolean(r?.success)}async function k(t,e){const i=t?._zod?.bag?.validatorValidate??t?._zod?.bag?.validator;if(i)try{return i(e)!==$}catch{return!1}const r=await t.safeParseAsync(e);return Boolean(r?.success)}function w(t){const e={};for(const i of Object.keys(t))e[i]=t[i].optional();return a.create(e)}function A(t,e,i){if(null===i||"object"!=typeof i||Array.isArray(i))return;const r=i[t];for(const i of e){const e=i._config?.shape;if(!e)continue;const n=e[t];if(!n)continue;const s=n._values||[];for(const t of s)if(Object.is(t,r))return i}}function P(h){if(h instanceof t)return h;if(null===h)return o.create();switch(null===h?"null":Array.isArray(h)?"array":typeof h){case"string":return e.create();case"number":return i.create();case"boolean":return r.create();case"bigint":return n.create();case"undefined":return s.create();case"array":return u.create(l.create());case"object":return a.create(h);default:return l.create()}}export{$ as COMPILE_INVALID,c as ZodCompileAsyncError,h as ZodCompileError,f as ZodCompileUnsupportedError,c as _ZodCompileAsyncError,f as _ZodCompileUnsupportedError,b as applyCompiled,y as compile,g as compileFn,m as compileFnValidate,A as getDiscriminatedOption,d as memoizer,w as properties,P as toZod,O as validate,k as validateAsync};
|
|
1
|
+
import{VldBase as t}from"./validators/base.js";import{VldString as e,COMPILABLE_FORMATS as i}from"./validators/string.js";import{VldNumber as r}from"./validators/number.js";import{VldBoolean as n}from"./validators/boolean.js";import{VldBigInt as a}from"./validators/bigint.js";import{VldUndefined as s}from"./validators/undefined.js";import{VldNull as o}from"./validators/null.js";import{VldObject as u}from"./validators/object.js";import{VldArray as l}from"./validators/array.js";import{VldUnknown as h}from"./validators/unknown.js";class f extends Error{constructor(t){super(t),this.name="ZodCompileError"}}class c extends f{constructor(t="Cannot compile async schema"){super(t),this.name="ZodCompileAsyncError"}}class $ extends f{constructor(t="Schema node is not supported by the AOT compiler"){super(t),this.name="ZodCompileUnsupportedError"}}const d=Symbol.for("@oxog/vld/compile-invalid");function v(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}const p=t=>{const e=new WeakMap;return i=>{const r=e.get(i);if(void 0!==r)return r;const n=t(i);return e.set(i,n),n}};function _(t){return t&&t.constructor&&t.constructor.name||""}function g(t,e,i){const r=`__re${t.regexTable.length}`;return t.regexTable.push({source:e,flags:i}),r}function m(t,e){return`__${e}${t.scratch++}`}function b(t,e,r){if(!r.failed){if("VldString"===_(t)){const n=t._checks,a=t._checkMetas;if(t._transforms?.length)return void(r.failed=!0);const s=[];if(a)for(const t of a)switch(t.kind){case"min":s.push(`__v.length >= ${t.value}`);break;case"max":s.push(`__v.length <= ${t.value}`);break;case"length":s.push(`__v.length === ${t.value}`);break;case"regex":{const e=t.pattern??t.value?.source??String(t.value);s.push(`${g(r,e,t.flags??"")}.test(__v)`);break}case"startsWith":s.push(`__v.startsWith(${JSON.stringify(t.value)})`);break;case"endsWith":s.push(`__v.endsWith(${JSON.stringify(t.value)})`);break;case"includes":s.push(`__v.includes(${JSON.stringify(t.value)})`);break;case"email":case"url":case"uuid":{const e=i[t.kind];s.push(`${g(r,e.source,e.flags)}.test(__v)`);break}case"format":if("email"===t.format||"url"===t.format||"uuid"===t.format){const e=i[t.format];s.push(`${g(r,e.source,e.flags)}.test(__v)`)}else{if(void 0===t.pattern)return void(r.failed=!0);s.push(`${g(r,t.pattern,t.flags??"")}.test(__v)`)}break;default:return void(r.failed=!0)}else if(n&&n.length>0)return void(r.failed=!0);return void(0===s.length?r.hoist.push(`if (typeof ${e} !== "string") ${r.throwOnFail?"throw":"return"} ${r.invalid}; ${r.validateOnly?r.outParam+" = true; ":(r.skipOutAssign?"":r.outParam+" = ")+e};`):r.hoist.push(`{ const __v = ${e}; if (typeof __v !== "string" || !(${s.join(" && ")})) ${r.throwOnFail?"throw":"return"} ${r.invalid}; ${r.outParam} = __v; }`))}if("VldNumber"===_(t)){const i=t._checks,n=t._checkMetas,a=[];if(n)for(const t of n)switch(t.kind){case"int":a.push("Number.isInteger(__v)");break;case"finite":a.push("Number.isFinite(__v)");break;case"min":a.push(!1!==t.inclusive?`__v >= ${t.value}`:`__v > ${t.value}`);break;case"max":a.push(!1!==t.inclusive?`__v <= ${t.value}`:`__v < ${t.value}`);break;case"gt":a.push(`__v > ${t.value}`);break;case"gte":a.push(`__v >= ${t.value}`);break;case"lt":a.push(`__v < ${t.value}`);break;case"lte":a.push(`__v <= ${t.value}`);break;case"multipleOf":a.push(`__v % ${t.value} === 0`);break;case"positive":a.push("__v > 0");break;case"negative":a.push("__v < 0");break;case"nonnegative":a.push("__v >= 0");break;case"nonpositive":a.push("__v <= 0");break;case"safe":a.push("Number.isSafeInteger(__v)");break;default:if(i&&i.length>0)return void(r.failed=!0)}else if(i&&i.length>0)return void(r.failed=!0);const s=['typeof __v === "number"',"!Number.isNaN(__v)",...a];return void r.hoist.push(`{ const __v = ${e}; if (!(${s.join(" && ")})) ${r.throwOnFail?"throw":"return"} ${r.invalid}; ${r.outParam} = __v; }`)}if("VldBoolean"!==_(t)){if("VldBigInt"===_(t)){const i=t._checks,n=t._checkMetas,a=[];if(n)for(const t of n)switch(t.kind){case"min":a.push(`__v >= ${t.value}n`);break;case"max":a.push(`__v <= ${t.value}n`);break;case"positive":a.push("__v > 0n");break;case"negative":a.push("__v < 0n");break;case"nonnegative":a.push("__v >= 0n");break;case"nonpositive":a.push("__v <= 0n");break;default:if(i&&i.length>0)return void(r.failed=!0)}else if(i&&i.length>0)return void(r.failed=!0);const s=['typeof __v === "bigint"',...a];return void r.hoist.push(`{ const __v = ${e}; if (!(${s.join(" && ")})) ${r.throwOnFail?"throw":"return"} ${r.invalid}; ${r.outParam} = __v; }`)}if("VldDate"!==_(t))if("VldNull"!==_(t))if("VldUndefined"!==_(t))if("VldAny"!==_(t)&&"VldUnknown"!==_(t)){if("VldLiteral"===_(t)){const i=t._values||[];if(0===i.length)return void r.hoist.push(`${r.throwOnFail?"throw":"return"} ${r.invalid};`);if(1===i.length){const t=i[0],n="number"==typeof t&&Number.isNaN(t)?"NaN":JSON.stringify(t);return void r.hoist.push(`if (!Object.is(${n}, ${e})) ${r.throwOnFail?"throw":"return"} ${r.invalid}; ${r.validateOnly?r.outParam+" = true; ":(r.skipOutAssign?"":r.outParam+" = ")+e};`)}const n=m(r,"set");return r.hoist.push(`const ${n} = new Set([${i.map(t=>"number"==typeof t&&Number.isNaN(t)?"NaN":JSON.stringify(t)).join(",")}]);`),void r.hoist.push(`if (!${n}.has(${e})) ${r.throwOnFail?"throw":"return"} ${r.invalid}; ${r.validateOnly?r.outParam+" = true; ":(r.skipOutAssign?"":r.outParam+" = ")+e};`)}if("VldEnum"===_(t)){const i=t._values||[],n=m(r,"set");return r.hoist.push(`const ${n} = new Set([${i.map(t=>JSON.stringify(t)).join(",")}]);`),void r.hoist.push(`if (!${n}.has(${e})) ${r.throwOnFail?"throw":"return"} ${r.invalid}; ${r.validateOnly?r.outParam+" = true; ":(r.skipOutAssign?"":r.outParam+" = ")+e};`)}if("VldOptional"===_(t)){const i=t.baseValidator;return r.hoist.push(`if (${e} === undefined) { ${r.outParam} = undefined; } else {`),b(i,e,r),void r.hoist.push("}")}if("VldDefault"===_(t)){if(!r.validateOnly)return void(r.failed=!0);const i=t.baseValidator;return r.hoist.push(`if (${e} === undefined) { ${r.outParam} = true; } else {`),b(i,e,r),void r.hoist.push("}")}if("VldArray"===_(t)){const i=t.config;if(i?.unique)return void(r.failed=!0);const n=i?.itemValidator??t.config?.element;if(!n)return void(r.failed=!0);const a=[];"number"==typeof i?.exactLength?a.push(`if (${e}.length !== ${i.exactLength}) ${r.throwOnFail?"throw":"return"} ${r.invalid};`):("number"==typeof i?.minLength&&a.push(`if (${e}.length < ${i.minLength}) ${r.throwOnFail?"throw":"return"} ${r.invalid};`),"number"==typeof i?.maxLength&&a.push(`if (${e}.length > ${i.maxLength}) ${r.throwOnFail?"throw":"return"} ${r.invalid};`));const s=m(r,"arr"),o=m(r,"i");if("VldObject"===_(n)){if(r.hoist.push(`if (!Array.isArray(${e})) ${r.throwOnFail?"throw":"return"} ${r.invalid};`,...a),r.validateOnly){if(r.hoist.push(`for (let ${o} = 0; ${o} < ${e}.length; ${o}++) {`),b(n,`${e}[${o}]`,r),r.failed)return;return r.hoist.push("}"),void r.hoist.push(`${r.outParam} = true;`)}r.hoist.push(`const ${s} = new Array(${e}.length);`);const t={invalid:r.invalid,outParam:"__slot",scratch:0,hoist:[],failed:!1,skipOutAssign:!0,regexTable:r.regexTable};return t.hoist.push(`for (let ${o} = 0; ${o} < ${e}.length; ${o}++) {`," let __slot;"),b(n,`${e}[${o}]`,t),t.failed?void(r.failed=!0):(t.hoist.push(` ${s}[${o}] = __slot;`,"}"),r.hoist.push(...t.hoist),void r.hoist.push(`${r.outParam} = ${s};`))}const u=m(r,"it");if(r.hoist.push(`if (!Array.isArray(${e})) ${r.throwOnFail?"throw":"return"} ${r.invalid};`,...a),r.validateOnly)return r.hoist.push(`for (let ${o} = 0; ${o} < ${e}.length; ${o}++) {`,` const ${u} = ${e}[${o}];`),b(n,u,r),r.hoist.push("}"),void r.hoist.push(`${r.outParam} = true;`);if(r.hoist.push(`const ${s} = new Array(${e}.length);`,`for (let ${o} = 0; ${o} < ${e}.length; ${o}++) {`),b(n,`${e}[${o}]`,r),r.failed)return;return void r.hoist.push(` ${s}[${o}] = ${e}[${o}];`,"}",`${r.outParam} = ${s};`)}if("VldTuple"===_(t)){const i=t.validators.filter(t=>Boolean(t)),n=t.restValidator,a=m(r,"tup"),s=n?`${e}.length < ${i.length}`:`${e}.length !== ${i.length}`;if(r.hoist.push(`if (!Array.isArray(${e}) || ${s}) ${r.throwOnFail?"throw":"return"} ${r.invalid};`),r.validateOnly){for(let t=0;t<i.length;t++){const n=i[t];if(!n)return void(r.failed=!0);if(b(n,`${e}[${t}]`,r),r.failed)return}if(n){const t=m(r,"i");r.hoist.push(`for (let ${t} = ${i.length}; ${t} < ${e}.length; ${t}++) {`),b(n,`${e}[${t}]`,r),r.hoist.push("}")}return void r.hoist.push(`${r.outParam} = true;`)}r.hoist.push(`const ${a} = new Array(${e}.length);`);for(let t=0;t<i.length;t++){const n=i[t];if(!n)return void(r.failed=!0);const s=m(r,"it");r.hoist.push(`{ const ${s} = ${e}[${t}];`);const o=r.skipOutAssign??!1;r.skipOutAssign=!0,b(n,s,r),r.skipOutAssign=o,r.hoist.push(` ${a}[${t}] = ${s}; }`)}if(n){const t=m(r,"i"),s=m(r,"it");r.hoist.push(`for (let ${t} = ${i.length}; ${t} < ${e}.length; ${t}++) {`,` const ${s} = ${e}[${t}];`);const o=r.skipOutAssign??!1;r.skipOutAssign=!0,b(n,s,r),r.skipOutAssign=o,r.hoist.push(` ${a}[${t}] = ${s}; }`)}return void r.hoist.push(`${r.outParam} = ${a};`)}if("VldObject"===_(t)){const i=t._config?.shape;if(!i)return void(r.failed=!0);const n=t._config;if(n?.strict||n?.passthrough||n?.catchall)return void(r.failed=!0);const a=m(r,"o");if(r.hoist.push(`if (typeof ${e} !== "object" || ${e} === null || Array.isArray(${e})) ${r.throwOnFail?"throw":"return"} ${r.invalid};`),r.validateOnly){for(const t of Object.keys(i)){const n=i[t];if(!n)return void(r.failed=!0);if(b(n,`${e}${/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`.${t}`:`[${JSON.stringify(t)}]`}`,r),r.failed)return}return void r.hoist.push(`${r.outParam} = true;`)}r.hoist.push(`const ${a} = {};`);for(const t of Object.keys(i)){const n=i[t];if(!n)return void(r.failed=!0);const s=/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`.${t}`:`[${JSON.stringify(t)}]`,o=m(r,"p");r.hoist.push(`{ const ${o} = ${e}${s};`);const u=r.skipOutAssign??!1;r.skipOutAssign=!0,b(n,o,r),r.skipOutAssign=u,r.hoist.push(` ${a}${s} = ${o}; }`)}return void r.hoist.push(`${r.outParam} = ${a};`)}if("VldRecord"===_(t)){const i=t.keyValidator,n=t.valueValidator,a=m(r,"rec"),s=m(r,"ks"),o=m(r,"i"),u=m(r,"k"),l=m(r,"v");return r.hoist.push(`if (typeof ${e} !== "object" || ${e} === null || Array.isArray(${e})) ${r.throwOnFail?"throw":"return"} ${r.invalid};`,`const ${a} = {};`,`const ${s} = Object.keys(${e});`,`for (let ${o} = 0; ${o} < ${s}.length; ${o}++) {`,` let ${u} = ${s}[${o}];`),b(i,u,r),r.hoist.push(` let ${l} = ${e}[${s}[${o}]];`),b(n,l,r),void r.hoist.push(` ${a}[${u}] = ${l};`,"}",""+(r.validateOnly?r.outParam+" = true; ":r.outParam+" = "+a+";"))}if("VldUnion"===_(t)){const e=t.validators.filter(t=>Boolean(t));if(0===e.length)return void(r.failed=!0);const i=m(r,"u");r.hoist.push(`let ${i} = ${r.invalid};`);for(let t=0;t<e.length;t++){const n=e[t],a=_(n);if("VldString"===a){r.hoist.push(`if (typeof value === "string") { ${i} = value; }`,`else if (${i} === ${r.invalid}) { /* fall through to next option */ }`);continue}if("VldNumber"===a){r.hoist.push(`if (typeof value === "number" && value === value) { ${i} = value; }`,`else if (${i} === ${r.invalid}) { /* fall through */ }`);continue}if("VldBoolean"===a){r.hoist.push(`if (typeof value === "boolean") { ${i} = value; }`,`else if (${i} === ${r.invalid}) { /* fall through */ }`);continue}if("VldNull"===a){r.hoist.push(`if (value === null) { ${i} = value; }`,`else if (${i} === ${r.invalid}) { /* fall through */ }`);continue}if("VldUndefined"===a){r.hoist.push(`if (value === undefined) { ${i} = value; }`,`else if (${i} === ${r.invalid}) { /* fall through */ }`);continue}if("VldLiteral"===a){const t=n._values||[];if(1===t.length){const e=t[0],n="number"==typeof e&&Number.isNaN(e)?"NaN":JSON.stringify(e);r.hoist.push(`if (Object.is(${n}, value)) { ${i} = value; }`,`else if (${i} === ${r.invalid}) { /* fall through */ }`);continue}}const s={invalid:r.invalid,outParam:i,scratch:0,hoist:[],failed:!1,skipOutAssign:!0,regexTable:r.regexTable};if(b(n,"value",s),s.failed)return void(r.failed=!0);r.hoist.push(`${i} = ((value) => {`,...s.hoist.map(t=>" "+t)," return value;","})(value);",`if (${i} !== ${r.invalid}) { /* matched */ }`)}return void r.hoist.push(`if (${i} === ${r.invalid}) ${r.throwOnFail?"throw":"return"} ${r.invalid}; ${r.outParam} = ${i};`)}r.failed=!0}else r.hoist.push((r.validateOnly?r.outParam+" = true; ":(r.skipOutAssign?"":r.outParam+" = ")+e)+";");else r.hoist.push(`if (${e} !== undefined) ${r.throwOnFail?"throw":"return"} ${r.invalid}; ${r.outParam} = undefined;`);else r.hoist.push(`if (${e} !== null) ${r.throwOnFail?"throw":"return"} ${r.invalid}; ${r.outParam} = null;`);else r.hoist.push(`{ const __v = ${e}; if (!(__v instanceof Date) || __v.getTime() !== __v.getTime()) ${r.throwOnFail?"throw":"return"} ${r.invalid}; ${r.outParam} = __v; }`)}else r.hoist.push(`if (typeof ${e} !== "boolean") ${r.throwOnFail?"throw":"return"} ${r.invalid}; ${r.validateOnly?r.outParam+" = true; ":(r.skipOutAssign?"":r.outParam+" = ")+e};`)}}function y(t,e){if(!t||"function"!=typeof t.parse)return null;const i=!!e?.validateOnly,r={invalid:"__INV",outParam:i?"__ok":"__out",scratch:0,hoist:[],failed:!1,validateOnly:i,regexTable:[]};if(r.hoist.push(i?"let __ok;":"let __out;"),b(t,"value",r),r.failed)return"1"===process.env.VLD_COMPILE_DEBUG&&console.error("[compile] failed to lower schema; partial body:\n"+r.hoist.join("\n")),null;r.hoist.push(i?"return __ok;":"return __out;");const n=[...r.regexTable.map((t,e)=>`const __re${e} = __re[${e}];`),...r.hoist].join("\n"),a=new Function("value",r.invalid,"__re",n),s=r.regexTable.map(t=>new RegExp(t.source,t.flags)),o=t=>a(t,d,s);return Object.defineProperty(o,"__vld_compiled",{value:!0,enumerable:!1}),o}function O(t){return y(t,{validateOnly:!0})}function k(t,e,i){const r=t.parse.bind(t),n=t.safeParse.bind(t),a=d,s=i??e;return t.parse=t=>s(t)===a?r(t):t,t.safeParse=t=>s(t)===a?n(t):{success:!0,data:t},Object.defineProperty(t,"_zod",{value:{bag:{validator:e,validatorValidate:i}},enumerable:!1,configurable:!0}),t}function w(t,e){const i=t?._zod?.bag?.validator;if(i)return t;const r=v(t);if(e?.JITless)return Object.defineProperty(r,"_zod",{value:{bag:{}},enumerable:!1,configurable:!0}),r;const n=O(r);return n?k(r,n,n):r}function P(t,e){const i=v(t),r=i.parse.bind(i),n=i.safeParse.bind(i);return i.parse=t=>{const i=e(t);return i===d?r(t):i},i.safeParse=t=>{const i=e(t);return i===d?n(t):{success:!0,data:i}},Object.defineProperty(i,"_zod",{value:{bag:{validator:e}},enumerable:!1,configurable:!0}),i}function A(t,e){const i=t?._zod?.bag?.validatorValidate??t?._zod?.bag?.validator;if(i)try{return i(e)!==d}catch{return!1}const r=t.safeParse(e);return Boolean(r?.success)}async function j(t,e){const i=t?._zod?.bag?.validatorValidate??t?._zod?.bag?.validator;if(i)try{return i(e)!==d}catch{return!1}const r=await t.safeParseAsync(e);return Boolean(r?.success)}function V(t){const e={};for(const i of Object.keys(t))e[i]=t[i].optional();return u.create(e)}function N(t,e,i){if(null===i||"object"!=typeof i||Array.isArray(i))return;const r=i[t];for(const i of e){const e=i._config?.shape;if(!e)continue;const n=e[t];if(!n)continue;const a=n._values||[];for(const t of a)if(Object.is(t,r))return i}}function x(i){if(i instanceof t)return i;if(null===i)return o.create();switch(null===i?"null":Array.isArray(i)?"array":typeof i){case"string":return e.create();case"number":return r.create();case"boolean":return n.create();case"bigint":return a.create();case"undefined":return s.create();case"array":return l.create(h.create());case"object":return u.create(i);default:return h.create()}}globalThis["@oxog/vld/lazy-validate-compiler"]=t=>O(t);export{d as COMPILE_INVALID,c as ZodCompileAsyncError,f as ZodCompileError,$ as ZodCompileUnsupportedError,c as _ZodCompileAsyncError,$ as _ZodCompileUnsupportedError,k as applyCompiled,w as compile,y as compileFn,O as compileFnValidate,N as getDiscriminatedOption,p as memoizer,V as properties,x as toZod,A as validate,j as validateAsync,P as withParser};
|