@cleverbrush/schema 3.0.1 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -2
- package/dist/builders/AnySchemaBuilder.js +1 -1
- package/dist/builders/ArraySchemaBuilder.js +1 -1
- package/dist/builders/BooleanSchemaBuilder.js +1 -1
- package/dist/builders/DateSchemaBuilder.js +1 -1
- package/dist/builders/ExternSchemaBuilder.js +1 -1
- package/dist/builders/FunctionSchemaBuilder.js +1 -1
- package/dist/builders/NumberSchemaBuilder.js +1 -1
- package/dist/builders/ObjectSchemaBuilder.js +1 -1
- package/dist/builders/ParseStringSchemaBuilder.d.ts +9 -0
- package/dist/builders/ParseStringSchemaBuilder.js +1 -1
- package/dist/builders/PromiseSchemaBuilder.js +1 -1
- package/dist/builders/RecordSchemaBuilder.js +1 -1
- package/dist/builders/SchemaBuilder.d.ts +13 -7
- package/dist/builders/StringSchemaBuilder.js +1 -1
- package/dist/builders/TupleSchemaBuilder.js +1 -1
- package/dist/builders/UnionSchemaBuilder.js +1 -1
- package/dist/{chunk-NUW3VXZV.js → chunk-3K7MOEPS.js} +2 -2
- package/dist/{chunk-K6Z47OQY.js → chunk-4RMOR7SV.js} +2 -2
- package/dist/{chunk-ZFI27R3L.js → chunk-57AZDIBB.js} +2 -2
- package/dist/chunk-C4LSLV6T.js +2 -0
- package/dist/chunk-C4LSLV6T.js.map +1 -0
- package/dist/{chunk-WQDYWDOE.js → chunk-EBGC6ZBF.js} +2 -2
- package/dist/{chunk-CFIJQ4GP.js → chunk-ETJPB3TR.js} +2 -2
- package/dist/{chunk-WDMJBGBD.js → chunk-FTA66XZT.js} +2 -2
- package/dist/{chunk-3JMDGYDT.js → chunk-G6HTNXRO.js} +1 -1
- package/dist/chunk-G6HTNXRO.js.map +1 -0
- package/dist/{chunk-ZC6YBKCP.js → chunk-OJJHAZZ4.js} +2 -2
- package/dist/{chunk-BUEVZ3KA.js → chunk-PUWIYD4T.js} +2 -2
- package/dist/{chunk-YQZHDMRF.js → chunk-QG254RGI.js} +2 -2
- package/dist/{chunk-PHE4LIAN.js → chunk-QWYVMYJ2.js} +2 -2
- package/dist/chunk-SY5EYKF2.js +2 -0
- package/dist/chunk-SY5EYKF2.js.map +1 -0
- package/dist/{chunk-QARCEYGO.js → chunk-VRRKXJ2H.js} +2 -2
- package/dist/{chunk-EIVZX4ZO.js → chunk-YYE5HQCL.js} +2 -2
- package/dist/chunk-ZC2HTRZF.js +2 -0
- package/dist/chunk-ZC2HTRZF.js.map +1 -0
- package/dist/{chunk-HN774HD7.js → chunk-ZHBJ46HB.js} +2 -2
- package/dist/core.d.ts +2 -2
- package/dist/core.js +1 -1
- package/dist/extension.d.ts +76 -4
- package/dist/extension.js +2 -0
- package/dist/extension.js.map +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +6 -2
- package/dist/chunk-3JMDGYDT.js.map +0 -1
- package/dist/chunk-DY7J6RNN.js +0 -2
- package/dist/chunk-DY7J6RNN.js.map +0 -1
- package/dist/chunk-GXPV6UQK.js +0 -2
- package/dist/chunk-GXPV6UQK.js.map +0 -1
- /package/dist/{chunk-NUW3VXZV.js.map → chunk-3K7MOEPS.js.map} +0 -0
- /package/dist/{chunk-K6Z47OQY.js.map → chunk-4RMOR7SV.js.map} +0 -0
- /package/dist/{chunk-ZFI27R3L.js.map → chunk-57AZDIBB.js.map} +0 -0
- /package/dist/{chunk-WQDYWDOE.js.map → chunk-EBGC6ZBF.js.map} +0 -0
- /package/dist/{chunk-CFIJQ4GP.js.map → chunk-ETJPB3TR.js.map} +0 -0
- /package/dist/{chunk-WDMJBGBD.js.map → chunk-FTA66XZT.js.map} +0 -0
- /package/dist/{chunk-ZC6YBKCP.js.map → chunk-OJJHAZZ4.js.map} +0 -0
- /package/dist/{chunk-BUEVZ3KA.js.map → chunk-PUWIYD4T.js.map} +0 -0
- /package/dist/{chunk-YQZHDMRF.js.map → chunk-QG254RGI.js.map} +0 -0
- /package/dist/{chunk-PHE4LIAN.js.map → chunk-QWYVMYJ2.js.map} +0 -0
- /package/dist/{chunk-QARCEYGO.js.map → chunk-VRRKXJ2H.js.map} +0 -0
- /package/dist/{chunk-EIVZX4ZO.js.map → chunk-YYE5HQCL.js.map} +0 -0
- /package/dist/{chunk-HN774HD7.js.map → chunk-ZHBJ46HB.js.map} +0 -0
package/README.md
CHANGED
|
@@ -3,11 +3,11 @@
|
|
|
3
3
|
[](https://github.com/cleverbrush/framework/actions/workflows/ci.yml)
|
|
4
4
|
[](https://standardschema.dev/)
|
|
5
5
|
<!-- bundle-badge-start -->
|
|
6
|
-
[](https://github.com/cleverbrush/framework/blob/master/libs/schema)
|
|
7
7
|
<!-- bundle-badge-end -->
|
|
8
8
|
[](../../LICENSE)
|
|
9
9
|
<!-- coverage-badge-start -->
|
|
10
|
-

|
|
11
11
|
<!-- coverage-badge-end -->
|
|
12
12
|
|
|
13
13
|
A schema definition and validation library for TypeScript — faster than Zod in 14/15 benchmarks (up to 204× faster on invalid input), 3× smaller than Zod v4, and compatible with 50+ ecosystem tools via [Standard Schema v1](https://standardschema.dev/).
|
|
@@ -541,6 +541,18 @@ const result = RouteSchema.validate('/orders/abc/bad-uuid');
|
|
|
541
541
|
// result.errors[0].message → "id: expected an integer number"
|
|
542
542
|
```
|
|
543
543
|
|
|
544
|
+
**Raw template access** — the original `{Property}` pattern is exposed via the `.template` getter. This enables consumers to use a parse-string schema as a Serilog-style message template (used by `@cleverbrush/log` for typed log events):
|
|
545
|
+
|
|
546
|
+
```typescript
|
|
547
|
+
const TodoCreated = parseString(
|
|
548
|
+
object({ TodoId: number(), Title: string(), UserId: string() }),
|
|
549
|
+
$t => $t`Todo #${t => t.TodoId} "${t => t.Title}" created by ${t => t.UserId}`
|
|
550
|
+
);
|
|
551
|
+
|
|
552
|
+
TodoCreated.template;
|
|
553
|
+
// → 'Todo #{TodoId} "{Title}" created by {UserId}'
|
|
554
|
+
```
|
|
555
|
+
|
|
544
556
|
## Coercion
|
|
545
557
|
|
|
546
558
|
The `number()`, `boolean()`, and `date()` builders each have a `.coerce()` method that adds a preprocessor to convert string values to the target type. This is especially useful with parse-string schemas where captured segments are always strings, but also works standalone for URL parameters, form inputs, or any other string source.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-ZHBJ46HB.js";import"../chunk-G6HTNXRO.js";export{a as AnySchemaBuilder,b as any};
|
|
2
2
|
//# sourceMappingURL=AnySchemaBuilder.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-3K7MOEPS.js";import"../chunk-G6HTNXRO.js";export{a as ArraySchemaBuilder,b as array};
|
|
2
2
|
//# sourceMappingURL=ArraySchemaBuilder.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-ETJPB3TR.js";import"../chunk-G6HTNXRO.js";export{a as BooleanSchemaBuilder,b as boolean};
|
|
2
2
|
//# sourceMappingURL=BooleanSchemaBuilder.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-YYE5HQCL.js";import"../chunk-G6HTNXRO.js";export{a as DateSchemaBuilder,b as date};
|
|
2
2
|
//# sourceMappingURL=DateSchemaBuilder.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-QWYVMYJ2.js";import"../chunk-G6HTNXRO.js";export{a as ExternSchemaBuilder,b as extern};
|
|
2
2
|
//# sourceMappingURL=ExternSchemaBuilder.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-OJJHAZZ4.js";import"../chunk-G6HTNXRO.js";export{a as FunctionSchemaBuilder,b as func};
|
|
2
2
|
//# sourceMappingURL=FunctionSchemaBuilder.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-PUWIYD4T.js";import"../chunk-G6HTNXRO.js";export{a as NumberSchemaBuilder,b as number};
|
|
2
2
|
//# sourceMappingURL=NumberSchemaBuilder.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-4RMOR7SV.js";import"../chunk-G6HTNXRO.js";export{a as ObjectSchemaBuilder,b as object};
|
|
2
2
|
//# sourceMappingURL=ObjectSchemaBuilder.js.map
|
|
@@ -52,6 +52,15 @@ export declare class ParseStringSchemaBuilder<TResult = any, TRequired extends b
|
|
|
52
52
|
*/
|
|
53
53
|
static create(props: ParseStringSchemaBuilderCreateProps): ParseStringSchemaBuilder<any, true, false, false, {}>;
|
|
54
54
|
protected constructor(props: ParseStringSchemaBuilderCreateProps);
|
|
55
|
+
/**
|
|
56
|
+
* The human-readable message template pattern with `{property}` holes,
|
|
57
|
+
* e.g. `"Todo created: #{TodoId} \"{Title}\" by user {UserId}"`.
|
|
58
|
+
*
|
|
59
|
+
* Useful for structured logging — pass this as the log `messageTemplate`
|
|
60
|
+
* so events with the same shape can be grouped, and pass
|
|
61
|
+
* `serialize(params)` as the rendered message.
|
|
62
|
+
*/
|
|
63
|
+
get template(): string;
|
|
55
64
|
/**
|
|
56
65
|
* Return a snapshot of this builder's configuration.
|
|
57
66
|
*
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-SY5EYKF2.js";import"../chunk-4RMOR7SV.js";import"../chunk-G6HTNXRO.js";export{a as ParseStringSchemaBuilder,b as parseString};
|
|
2
2
|
//# sourceMappingURL=ParseStringSchemaBuilder.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-FTA66XZT.js";import"../chunk-G6HTNXRO.js";export{a as PromiseSchemaBuilder,b as promise};
|
|
2
2
|
//# sourceMappingURL=PromiseSchemaBuilder.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-57AZDIBB.js";import"../chunk-G6HTNXRO.js";export{a as RecordSchemaBuilder,b as record};
|
|
2
2
|
//# sourceMappingURL=RecordSchemaBuilder.js.map
|
|
@@ -317,8 +317,8 @@ export type PropertySetterOptions = {
|
|
|
317
317
|
* Extracts the inner property descriptor type from a `PropertyDescriptor`.
|
|
318
318
|
* Returns `undefined` if `T` is not a valid `PropertyDescriptor`.
|
|
319
319
|
*/
|
|
320
|
-
export type PropertyDescriptorInnerFromPropertyDescriptor<T> = T extends PropertyDescriptor<infer TSchema, infer TPropertySchema, infer TParentPropertyDescriptor> ? PropertyDescriptorInner<TSchema, TPropertySchema, TParentPropertyDescriptor> : undefined;
|
|
321
|
-
export type PropertyDescriptorInner<TSchema extends ObjectSchemaBuilder<any, any, any, any, any>, TPropertySchema, TParentPropertyDescriptor> = {
|
|
320
|
+
export type PropertyDescriptorInnerFromPropertyDescriptor<T> = T extends PropertyDescriptor<infer TSchema, infer TPropertySchema, infer TParentPropertyDescriptor, infer TPropertyKey extends string> ? PropertyDescriptorInner<TSchema, TPropertySchema, TParentPropertyDescriptor, TPropertyKey> : undefined;
|
|
321
|
+
export type PropertyDescriptorInner<TSchema extends ObjectSchemaBuilder<any, any, any, any, any>, TPropertySchema, TParentPropertyDescriptor, TPropertyKey extends string = string> = {
|
|
322
322
|
/**
|
|
323
323
|
* Sets a new value to the property. If the process was successful,
|
|
324
324
|
* the method returns `true`, otherwise `false`.
|
|
@@ -374,8 +374,14 @@ export type PropertyDescriptorInner<TSchema extends ObjectSchemaBuilder<any, any
|
|
|
374
374
|
/**
|
|
375
375
|
* The name of this property within its parent object, or `undefined`
|
|
376
376
|
* for the root descriptor.
|
|
377
|
+
*
|
|
378
|
+
* When the property was created from a `PropertyDescriptorTree` leaf the
|
|
379
|
+
* type narrows to the literal key string (e.g. `'id'`), enabling
|
|
380
|
+
* accessor-function-based column inference in query builders.
|
|
381
|
+
*
|
|
382
|
+
* @typeParam TPropertyKey - The literal property name, or `string` for root/unknown descriptors.
|
|
377
383
|
*/
|
|
378
|
-
propertyName:
|
|
384
|
+
propertyName: TPropertyKey | undefined;
|
|
379
385
|
/**
|
|
380
386
|
* Returns a JSON Pointer (RFC 6901) string representing this
|
|
381
387
|
* property's path from the root descriptor.
|
|
@@ -390,15 +396,15 @@ export type PropertyDescriptorInner<TSchema extends ObjectSchemaBuilder<any, any
|
|
|
390
396
|
* holds a {@link PropertyDescriptorInner} for a particular property within
|
|
391
397
|
* an object schema. Used to get/set property values on validated objects.
|
|
392
398
|
*/
|
|
393
|
-
export type PropertyDescriptor<TRootSchema extends ObjectSchemaBuilder<any, any, any, any, any>, TPropertySchema, TParentPropertyDescriptor> = {
|
|
394
|
-
[SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR]: PropertyDescriptorInner<TRootSchema, TPropertySchema, TParentPropertyDescriptor>;
|
|
399
|
+
export type PropertyDescriptor<TRootSchema extends ObjectSchemaBuilder<any, any, any, any, any>, TPropertySchema, TParentPropertyDescriptor, TPropertyKey extends string = string> = {
|
|
400
|
+
[SYMBOL_SCHEMA_PROPERTY_DESCRIPTOR]: PropertyDescriptorInner<TRootSchema, TPropertySchema, TParentPropertyDescriptor, TPropertyKey>;
|
|
395
401
|
};
|
|
396
402
|
/**
|
|
397
403
|
* A tree of property descriptors for the schema.
|
|
398
404
|
* Has a possibility to filter properties by the type (`TAssignableTo` type parameter).
|
|
399
405
|
*/
|
|
400
406
|
export type PropertyDescriptorTree<TSchema extends ObjectSchemaBuilder<any, any, any, any, any>, TRootSchema extends ObjectSchemaBuilder<any, any, any, any, any> = TSchema, TAssignableTo = any, TParentPropertyDescriptor = undefined> = PropertyDescriptor<TRootSchema, TSchema, TParentPropertyDescriptor> & (TSchema extends ObjectSchemaBuilder<infer TProperties, any, any> ? {
|
|
401
|
-
[K in keyof TProperties]: TProperties[K] extends ObjectSchemaBuilder<any, any, any> ? PropertyDescriptorTree<TProperties[K], TRootSchema, any, PropertyDescriptor<TRootSchema, TSchema, TParentPropertyDescriptor>> : TProperties[K] extends ExternSchemaBuilder<any, any, any, any, any, any, infer TExternResult> ? PropertyDescriptor<TRootSchema, TProperties[K], PropertyDescriptor<TRootSchema, TSchema, TParentPropertyDescriptor
|
|
407
|
+
[K in keyof TProperties]: TProperties[K] extends ObjectSchemaBuilder<any, any, any> ? PropertyDescriptorTree<TProperties[K], TRootSchema, any, PropertyDescriptor<TRootSchema, TSchema, TParentPropertyDescriptor>> : TProperties[K] extends ExternSchemaBuilder<any, any, any, any, any, any, infer TExternResult> ? PropertyDescriptor<TRootSchema, TProperties[K], PropertyDescriptor<TRootSchema, TSchema, TParentPropertyDescriptor>, K & string> & ExternOutputPropertyDescriptors<TExternResult, TRootSchema, PropertyDescriptor<TRootSchema, TProperties[K], PropertyDescriptor<TRootSchema, TSchema, TParentPropertyDescriptor>, K & string>> : TProperties[K] extends ArraySchemaBuilder<infer TArrayElement, any, any> ? TArrayElement extends ObjectSchemaBuilder<any, any, any, any, any> ? PropertyDescriptor<TRootSchema, TProperties[K], PropertyDescriptor<TRootSchema, TSchema, TParentPropertyDescriptor>, K & string> : InferType<TProperties[K]> extends TAssignableTo ? PropertyDescriptor<TRootSchema, TProperties[K], PropertyDescriptor<TRootSchema, TSchema, TParentPropertyDescriptor>, K & string> : never : InferType<TProperties[K]> extends TAssignableTo ? PropertyDescriptor<TRootSchema, TProperties[K], PropertyDescriptor<TRootSchema, TSchema, TParentPropertyDescriptor>, K & string> : never;
|
|
402
408
|
} : never);
|
|
403
409
|
/**
|
|
404
410
|
* Recursively maps the keys of an extern schema's output type into
|
|
@@ -409,7 +415,7 @@ export type PropertyDescriptorTree<TSchema extends ObjectSchemaBuilder<any, any,
|
|
|
409
415
|
* @internal
|
|
410
416
|
*/
|
|
411
417
|
type ExternOutputPropertyDescriptors<TOutput, TRootSchema extends ObjectSchemaBuilder<any, any, any, any, any>, TParentPropertyDescriptor> = TOutput extends Date | Function | readonly any[] | string | number | boolean | symbol | bigint | null | undefined ? {} : TOutput extends Record<string, any> ? {
|
|
412
|
-
[K in keyof TOutput]: PropertyDescriptor<TRootSchema, SchemaBuilder<TOutput[K], true, false, false, {}>, TParentPropertyDescriptor> & ExternOutputPropertyDescriptors<TOutput[K], TRootSchema, PropertyDescriptor<TRootSchema, SchemaBuilder<TOutput[K], true, false, false, {}>, TParentPropertyDescriptor>>;
|
|
418
|
+
[K in keyof TOutput]: PropertyDescriptor<TRootSchema, SchemaBuilder<TOutput[K], true, false, false, {}>, TParentPropertyDescriptor, K & string> & ExternOutputPropertyDescriptors<TOutput[K], TRootSchema, PropertyDescriptor<TRootSchema, SchemaBuilder<TOutput[K], true, false, false, {}>, TParentPropertyDescriptor, K & string>>;
|
|
413
419
|
} : {};
|
|
414
420
|
/**
|
|
415
421
|
* Creates an array augmented with non-enumerable NestedValidationResult
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-QG254RGI.js";import"../chunk-G6HTNXRO.js";export{a as StringSchemaBuilder,b as string};
|
|
2
2
|
//# sourceMappingURL=StringSchemaBuilder.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-VRRKXJ2H.js";import"../chunk-G6HTNXRO.js";export{a as TupleSchemaBuilder,b as tuple};
|
|
2
2
|
//# sourceMappingURL=TupleSchemaBuilder.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"../chunk-
|
|
1
|
+
import{a,b}from"../chunk-EBGC6ZBF.js";import"../chunk-G6HTNXRO.js";export{a as UnionSchemaBuilder,b as union};
|
|
2
2
|
//# sourceMappingURL=UnionSchemaBuilder.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as T,e as p,f as h}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{c as T,e as p,f as h}from"./chunk-G6HTNXRO.js";var y=class m extends h{#r;#l=function(){return`is expected to have no less than ${this.#r} elements`};#n=this.#l;#t;#u=function(){return`is expected to have no more than ${this.#t} elements`};#s=this.#u;#e;static create(e){return new m({type:"array",...e})}constructor(e){super(e),typeof e.minLength=="number"&&(this.#r=e.minLength),this.#n=this.assureValidationErrorMessageProvider(e.minLengthValidationErrorMessageProvider,this.#l),typeof e.maxLength=="number"&&(this.#t=e.maxLength),this.#s=this.assureValidationErrorMessageProvider(e.maxLengthValidationErrorMessageProvider,this.#u),e.elementSchema instanceof h&&(this.#e=e.elementSchema)}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}#o(e,t){let{valid:u,context:r,errors:a,transaction:l}=t,d={[T]:{setValue:()=>!1,getValue:i=>({success:!0,value:i}),getSchema:()=>this,parent:void 0,propertyName:void 0,toJsonPointer:()=>""}},o=[],c=p([],()=>e,()=>o,()=>d[T]),s=(()=>c);if(!u)return o.push(...(a||[]).map(i=>i.message||String(i))),{needsElementValidation:!1,result:{valid:u,errors:a,getNestedErrors:s}};let{object:{validatedObject:n}}=l;return typeof n>"u"&&!this.isRequired||n===null&&(!this.isRequired||this.isNullable)?{needsElementValidation:!1,result:{valid:!0,object:n,getNestedErrors:s}}:Array.isArray(n)?{needsElementValidation:!0,objToValidate:n,prevalidationContext:r,getNestedErrors:s,elementResults:c,rootErrors:o}:(o.push("array expected"),{needsElementValidation:!1,result:{valid:!1,errors:[{message:"array expected"}],getNestedErrors:s}})}#i(e){return typeof this.#t=="number"&&e.length>this.#t?{provider:this.#s}:typeof this.#r=="number"&&e.length<this.#r?{provider:this.#n}:null}#d(e,t,u){let r=!0;for(let a=0;a<e.length;a++)e[a]?.valid||(r=!1),t[a]=e[a];return Object.assign({valid:r,getNestedErrors:u},r?{}:{errors:e.map(a=>a?.errors).filter(a=>a).flatMap(a=>a?.map(l=>({...l})))},r?{object:e.map(a=>a?.object)}:{})}validate(e,t){return super.validate(e,t)}async validateAsync(e,t){return super.validateAsync(e,t)}_validate(e,t){if(this.canSkipPreValidation&&!t?.doNotStopOnFirstError&&this.#e instanceof h){if(typeof e>"u"||e===null)if(typeof e>"u"&&this.hasDefault)e=this.resolveDefaultValue();else if(!this.isRequired||e===null&&this.isNullable){let a=this;return{valid:!0,object:e,getNestedErrors(){return a.#a(e,t).getNestedErrors()}}}else return this.#a(e,t);if(!Array.isArray(e))return this.#a(e,t);if(this.#i(e))return this.#a(e,t);let u=e.length;if(u>0){let a=new Array(u);for(let d=0;d<u;d++){let o=this.#e.validate(e[d]);if(!o.valid){let c=this;return{valid:!1,errors:o.errors&&o.errors.length>0?[o.errors[0]]:[],getNestedErrors(){return c.#a(e,t).getNestedErrors()}}}a[d]=o.object}let l=this;return{valid:!0,object:a,getNestedErrors(){return l.#a(e,t).getNestedErrors()}}}let r=this;return{valid:!0,object:e,getNestedErrors(){return r.#a(e,t).getNestedErrors()}}}return this.#a(e,t)}#a(e,t){let u=this.#o(e,this.preValidateSync(e,t));if(!u.needsElementValidation)return u.result;let{objToValidate:r,prevalidationContext:a,getNestedErrors:l,elementResults:d,rootErrors:o}=u,c=this.#i(r);if(c){let s=this.getValidationErrorMessageSync(c.provider,r);return o.push(s),{valid:!1,errors:[{message:s}],getNestedErrors:l}}if(r.length>0&&this.#e instanceof h)if(a.doNotStopOnFirstError){let s=[];for(let n=0;n<r.length;n++)s.push(this.#e.validate(r[n],{...a}));return this.#d(s,d,l)}else{let s=new Array(r.length);for(let n=0;n<r.length;n++){let i=this.#e.validate(r[n],{...a});if(d[n]=i,i.valid)s[n]=i.object;else return{valid:!1,errors:Array.isArray(i.errors)&&i.errors.length>0?[i.errors[0]]:[],getNestedErrors:l}}return{valid:!0,object:s,getNestedErrors:l}}return{valid:!0,object:r,getNestedErrors:l}}async _validateAsync(e,t){let u=this.#o(e,await super.preValidateAsync(e,t));if(!u.needsElementValidation)return u.result;let{objToValidate:r,prevalidationContext:a,getNestedErrors:l,elementResults:d,rootErrors:o}=u,c=this.#i(r);if(c){let s=await this.getValidationErrorMessage(c.provider,r);return o.push(s),{valid:!1,errors:[{message:s}],getNestedErrors:l}}if(r.length>0&&this.#e instanceof h)if(a.doNotStopOnFirstError){let s=await Promise.all(r.map(n=>this.#e?.validateAsync(n,a)));return this.#d(s,d,l)}else{let s=new Array(r.length);for(let n=0;n<r.length;n++){let i=await this.#e.validateAsync(r[n],{...a});if(d[n]=i,i.valid)s[n]=i.object;else return{valid:!1,errors:Array.isArray(i.errors)&&i.errors.length>0?[i.errors[0]]:[],getNestedErrors:l}}return{valid:!0,object:s,getNestedErrors:l}}return{valid:!0,object:r,getNestedErrors:l}}createFromProps(e){return m.create(e)}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}introspect(){return{...super.introspect(),elementSchema:this.#e,minLength:this.#r,minLengthValidationErrorMessageProvider:this.#n,maxLength:this.#t,maxLengthValidationErrorMessageProvider:this.#s}}of(e){return m.create({...this.introspect(),elementSchema:e})}clearOf(){return m.create({...this.introspect(),elementSchema:void 0})}minLength(e,t){if(typeof e!="number"||e<0)throw new Error("length is expected to be a number which is >= 0");return m.create({...this.introspect(),minLength:e,minLengthValidationErrorMessageProvider:t})}clearMinLength(){let e=this.introspect();return delete e.minLength,this.createFromProps({...e})}maxLength(e,t){if(typeof e!="number"||e<0)throw new Error("length is expected to be a number which is >= 0");return m.create({...this.introspect(),maxLength:e,maxLengthValidationErrorMessageProvider:t})}clearMaxLength(){let e=this.introspect();return delete e.maxLength,this.createFromProps({...e})}nullable(){return super.nullable()}notNullable(){return super.notNullable()}},S=m=>y.create({isRequired:!0,elementSchema:m});export{y as a,S as b};
|
|
2
|
+
//# sourceMappingURL=chunk-3K7MOEPS.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as f,d as k,f as S}from"./chunk-3JMDGYDT.js";var O=class{#e;#t;#n=[];#a=[];get seenValue(){let e=this.#e[f].getValue(this.#t);return e.success?e.value:void 0}get errors(){return this.#n}get isValid(){return this.#n.length===0&&this.getChildErrors().length===0}getChildErrors(){return this.#a}get descriptor(){return this.#e[f]}constructor(e,r,t){if(!b.isValidPropertyDescriptor(e))throw new Error("Invalid property descriptor");this.#e=e,this.#n=Array.isArray(t)?[...t]:[],this.#t=r}addError(e){this.#n.push(e)}addChildError(e){this.#a.push(e)}toJSON(){return{isValid:this.isValid,errors:this.errors}}};var V="must be an object",b=class p extends S{#e={};#t=!1;#n=[];#a=[];[k]=!0;#s=new WeakMap;static create(e){return new p({type:"object",...e})}createFromProps(e){return p.create(e)}constructor(e){super(e),typeof e.properties=="object"&&e.properties&&(this.#e=e.properties,this.#n=Object.keys(e.properties)),typeof e.acceptUnknownProps=="boolean"&&(this.#t=e.acceptUnknownProps),Array.isArray(e.constructorSchemas)&&(this.#a=e.constructorSchemas.filter(r=>r instanceof S))}introspect(){return{...super.introspect(),properties:{...this.#e},acceptUnknownProps:this.#t,constructorSchemas:[...this.#a]}}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}#i(e){p.isValidPropertyDescriptor(e?.context?.rootPropertyDescriptor)||(e.context.rootPropertyDescriptor=p.getPropertiesFor(this)),p.isValidPropertyDescriptor(e.context.currentPropertyDescriptor)||(e.context.currentPropertyDescriptor=e.context.rootPropertyDescriptor),!e.context.rootValidationObject&&e.transaction?.object?.validatedObject&&(e.context.rootValidationObject=e.transaction.object.validatedObject)}preValidateSync(e,r){let t=super.preValidateSync(e,r);return this.#i(t),t}async preValidateAsync(e,r){let t=await super.preValidateAsync(e,r);return this.#i(t),t}#o(e){let{valid:r,context:t,transaction:n,errors:a}=e,s=new WeakMap,y=new Set,{doNotStopOnFirstError:o,rootValidationObject:i}=t,l=t.rootPropertyDescriptor,u=t.currentPropertyDescriptor,P=(h,m,R)=>{if(!p.isValidPropertyDescriptor(h))throw new Error("invalid property descriptor");let g=s.has(h)?s.get(h):null;if(g||(g=new O(h,i),s.set(h,g)),g.addError(m),y.add(g),R&&p.isValidPropertyDescriptor(R)){let j=s.has(R)?s.get(R):null;j||(j=new O(R,i),s.set(R,j)),j.addChildError(g)}},d=(h=>{let m=typeof h=="function"?h(u):u;if(!p.isValidPropertyDescriptor(m))throw new Error("invalid property descriptor");return s.has(m)||s.set(m,new O(m,i)),s.get(m)}),c=()=>[...y].filter(h=>h.errors.length>0),T=e.errors||[],E=h=>{if(typeof h.property=="function"&&p.isValidPropertyDescriptor(u)){let m=h.property(u);if(p.isValidPropertyDescriptor(m)){P(m,h.message,u);return}}p.isValidPropertyDescriptor(u)&&P(u,h.message)};if(!r&&!o&&a){for(let h of a)E(h);return{earlyReturn:!0,result:{valid:r,errors:a,getErrorsFor:d,getInvalidProperties:c}}}if(o&&a)for(let h of a)E(h);let{object:{validatedObject:x}}=n;if(typeof x>"u"&&!this.isRequired||x===null&&(!this.isRequired||this.isNullable))return{earlyReturn:!0,result:{valid:!0,object:n.commit().validatedObject,getErrorsFor:d,getInvalidProperties:c}};if(typeof x!="object"||x===null)return T.length===0&&(T.push({message:V}),P(u,V)),n&&n.rollback(),{earlyReturn:!0,result:{valid:!1,errors:o?T:[T[0]],getErrorsFor:d,getInvalidProperties:c}};let w=this.#n,D=Object.keys(x);if(w.length===0){if(D.length===0)return o&&T.length>0?{earlyReturn:!0,result:{valid:!1,errors:T,getErrorsFor:d,getInvalidProperties:c}}:(n&&n.commit().validatedObject,{earlyReturn:!0,result:{valid:!0,object:{},getErrorsFor:d,getInvalidProperties:c}});if(!this.#t){for(let h=0;h<D.length;h++){let m=`unknown property '${D[h]}'`;if(T.push({message:m}),!o)break}return n&&n.rollback(),{earlyReturn:!0,result:{valid:!1,errors:o?T:[T[0]],getErrorsFor:d,getInvalidProperties:c}}}return n&&n.commit(),{earlyReturn:!0,result:{valid:!0,object:{...x},getErrorsFor:d,getInvalidProperties:c}}}return{earlyReturn:!1,errors:T,objToValidate:x,propKeys:w,objKeys:D,addErrorFor:P,getErrorsFor:d,getInvalidProperties:c,doNotStopOnFirstError:!!o,rootPropertyDescriptor:l,currentPropertyDescriptor:u,validationTransaction:n}}#p(e,r){let{objToValidate:t,objKeys:n,addErrorFor:a,getErrorsFor:s,getInvalidProperties:y,doNotStopOnFirstError:o,currentPropertyDescriptor:i,validationTransaction:l}=e,u=e.errors,P=!1;for(let{result:d}of r)if(!d.valid&&(P=!0,Array.isArray(d.errors)))for(let c of d.errors)u.push(c);for(let d=0;d<n.length;d++){let c=n[d];if(!(c in this.#e)&&!this.#t){let T=`unknown property '${c}'`;if(u.push({message:T}),a(i,T),!o)return l&&l.rollback(),{valid:!1,errors:[u[0]],getErrorsFor:s,getInvalidProperties:y}}}if(!P&&u.length===0){let d={};for(let{key:c,result:T}of r)d[c]=T.object;if(this.#t)for(let c of n)c in this.#e||(d[c]=t[c]);return{valid:!0,object:d,getErrorsFor:s,getInvalidProperties:y}}for(let{key:d,result:c}of r)if(!c.valid){let T=i[d];if(typeof c.getErrorsFor=="function"&&p.isValidPropertyDescriptor(T)){if(p.#c(c,T,a),Array.isArray(c.__externErrorPropertyNames)&&Array.isArray(c.errors))for(let E of c.errors)a(T,E.message,i)}else if(Array.isArray(c.errors)&&p.isValidPropertyDescriptor(T))for(let E of c.errors)a(T,E.message)}return l.rollback(),{valid:!1,errors:o?u:u[0]?[u[0]]:[],getErrorsFor:s,getInvalidProperties:y}}addValidator(e,r){return super.addValidator(e,r)}validate(e,r){return super.validate(e,r)}async validateAsync(e,r){return super.validateAsync(e,r)}_validate(e,r){if(this.canSkipPreValidation&&!r?.doNotStopOnFirstError&&!r?.rootPropertyDescriptor){if(typeof e>"u"||e===null)if(typeof e>"u"&&this.hasDefault)e=this.resolveDefaultValue();else if(!this.isRequired||e===null&&this.isNullable){let t=this;return{valid:!0,object:e,getErrorsFor(n){return t.#r(e,r).getErrorsFor(n)},getInvalidProperties(){return t.#r(e,r).getInvalidProperties()}}}else{let t=this;return{valid:!1,errors:[{message:this.getValidationErrorMessageSync(this.requiredErrorMessage,e)}],getErrorsFor(n){return t.#r(e,r).getErrorsFor(n)},getInvalidProperties(){return t.#r(e,r).getInvalidProperties()}}}else if(typeof e=="object"){let t=this.#n;if(!this.#t){let s=Object.keys(e);for(let y=0;y<s.length;y++)if(!(s[y]in this.#e)){let o=this;return{valid:!1,errors:[{message:`unknown property '${s[y]}'`}],getErrorsFor(i){return o.#r(e,r).getErrorsFor(i)},getInvalidProperties(){return o.#r(e,r).getInvalidProperties()}}}}let n={};for(let s=0;s<t.length;s++){let y=t[s],o=this.#e[y].validate(e[y]);if(!o.valid){let i=this;return{valid:!1,errors:o.errors&&o.errors.length>0?[o.errors[0]]:[],getErrorsFor(l){return i.#r(e,r).getErrorsFor(l)},getInvalidProperties(){return i.#r(e,r).getInvalidProperties()}}}n[y]=o.object}if(this.#t){let s=Object.keys(e);for(let y=0;y<s.length;y++)s[y]in this.#e||(n[s[y]]=e[s[y]])}let a=this;return{valid:!0,object:n,getErrorsFor(s){return a.#r(e,r).getErrorsFor(s)},getInvalidProperties(){return a.#r(e,r).getInvalidProperties()}}}}return this.#r(e,r)}#r(e,r){let t=this.#o(this.preValidateSync(e,r));if(t.earlyReturn)return t.result;let{propKeys:n,objToValidate:a,doNotStopOnFirstError:s,rootPropertyDescriptor:y,currentPropertyDescriptor:o}=t,i=[];for(let l of n){let u=this.#e[l].validate(a[l],{...r,rootPropertyDescriptor:y,currentPropertyDescriptor:o[l]});if(i.push({key:l,result:u}),!u.valid&&!s)break}return this.#p(t,i)}async _validateAsync(e,r){let t=this.#o(await this.preValidateAsync(e,r));if(t.earlyReturn)return t.result;let{propKeys:n,objToValidate:a,doNotStopOnFirstError:s,rootPropertyDescriptor:y,currentPropertyDescriptor:o}=t,i=[];if(s){let l=await Promise.all(n.map(async u=>{let P=await this.#e[u].validateAsync(a[u],{...r,rootPropertyDescriptor:y,currentPropertyDescriptor:o[u]});return{key:u,result:P}}));i.push(...l)}else for(let l of n){let u=await this.#e[l].validateAsync(a[l],{...r,rootPropertyDescriptor:y,currentPropertyDescriptor:o[l]});if(i.push({key:l,result:u}),!u.valid)break}return this.#p(t,i)}acceptUnknownProps(){return this.createFromProps({...this.introspect(),acceptUnknownProps:!0})}notAcceptUnknownProps(){return this.createFromProps({...this.introspect(),acceptUnknownProps:!1})}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}addConstructor(e){if(!(e instanceof S))throw new Error("schema must be an instance of the SchemaBuilder class");return this.createFromProps({...this.introspect(),constructorSchemas:[...this.#a,e]})}clearConstructors(){return this.createFromProps({...this.introspect(),constructorSchemas:[]})}addProp(e,r){if(typeof e!="string"||!e)throw new Error("propName must be a non empty string");if(e in this.#e)throw new Error(`Property ${e} already exists`);if(!(r instanceof S))throw new Error("schema must be an instance of the SchemaBuilder class");return this.createFromProps({...this.introspect(),properties:{...this.introspect().properties,[e]:r}})}optimize(){return this.createFromProps({...this.introspect()})}addProps(e){if(e instanceof p)return this.addProps(e.introspect().properties);if(typeof e!="object")throw new Error("props should be an object");if(e===null)throw new Error("props should not be null");let r={...this.#e};for(let t in e){if(t in this.#e)throw new Error(`property '${t}' already exists`);if(!(e[t]instanceof S))throw new Error(`${t} is not a SchemaBuilder`);r[t]=e[t]}return this.createFromProps({...this.introspect(),properties:r})}omit(e){if(typeof e=="string"){let r=e;if(!r||!(r in this.#e))throw new Error(`property ${r.toString()} does not exists in the schema`);return this.createFromProps({...this.introspect(),properties:(()=>{let t={...this.#e};return delete t[r],t})()})}else if(Array.isArray(e)){let r=e,t=new Map;if(r.forEach(a=>{if(typeof a!="string"||!a)throw new Error("property name must be a string");if(!(a in this.#e))throw new Error(`property ${a.toString()} does not exists in the schema`);t.set(a.toString(),!0)}),t.size===0)throw new Error("please provide at least one property to omit");let n={...this.introspect()};for(let a of t.keys())delete n.properties[a];return this.createFromProps(n)}else if(e instanceof p){let r={...e.introspect().properties},t={...this.introspect()};for(let n in r)n in t.properties&&delete t.properties[n];return this.createFromProps(t)}throw new Error("this parameter type is not supported")}intersect(e){if(!(e instanceof p))throw new Error("schema must be an instance of the ObjectSchemaBuilder class");let r=e.introspect().properties,t=this.introspect(),n=Object.keys(t.properties).reduce((a,s)=>(a[s]=s in r?r[s]:t.properties[s],a),{});return this.createFromProps({...this.introspect(),properties:n})}partial(e){if(typeof e>"u"||e===null)return this.createFromProps({...this.introspect(),properties:Object.keys(this.#e).reduce((r,t)=>(r[t]=this.#e[t].optional(),r),{})});if(Array.isArray(e)){let r=e;if(r.length===0)throw new Error("properties cannot be empty");let t={...this.introspect()};return r.forEach(n=>{if(typeof n!="string")throw new Error("each propery in property list must be as string value");if(!(n in t.properties))throw new Error(`property ${n} does not exists`);t.properties[n]=t.properties[n].optional()}),this.createFromProps(t)}if(typeof e=="string")return this.modifyPropSchema(e,r=>r.optional());throw new Error("expecting string or string[] parameter")}deepPartial(){let e={};for(let r of Object.keys(this.#e)){let t=this.#e[r];t instanceof p?e[r]=t.deepPartial().optional():e[r]=t.optional()}return this.createFromProps({...this.introspect(),properties:e})}pick(e){if(typeof e=="string"){let r=e;if(!r)throw new Error("property cannot be empty");if(!(r in this.#e))throw new Error(`property ${r} does not exists`);return this.createFromProps({...this.introspect(),properties:{[r]:this.#e[r]}})}if(Array.isArray(e)){if(e.length===0)throw new Error("properties must be a non empty erray");let r=e.reduce((t,n)=>{if(typeof n!="string"||!n)throw new Error("each property name must be a non empty string");if(!(n in this.#e))throw new Error(`property ${n} does not exists`);return t[n]=this.#e[n],t},{});return this.createFromProps({...this.introspect(),properties:r})}if(e instanceof p){let t=Object.keys(e.introspect().properties).filter(n=>typeof this.#e[n]<"u");if(t.length===0)throw new Error("there are no common properties in provided schemas");return this.pick(t)}throw new Error("string, array or ObjectSchemaBuilder is expected")}modifyPropSchema(e,r){if(typeof e!="string"||!e)throw new Error("propName must be a non empty string");if(!(e in this.#e))throw new Error(`property ${e} does not exists in the schema`);if(typeof r!="function")throw new Error("callback must be a function");let t=r(this.#e[e]);if(!(t instanceof S))throw new Error("callback must return a SchemaBuilder object");let n={...this.introspect()};return n.properties={...n.properties,[e]:t},this.createFromProps(n)}makePropOptional(e){return this.modifyPropSchema(e,r=>r.optional())}makePropRequired(e){return this.modifyPropSchema(e,r=>r.required())}makeAllPropsOptional(){return this.createFromProps({...this.introspect(),properties:Object.keys(this.#e).reduce((e,r)=>(e[r]=this.#e[r].optional(),e),{})})}makeAllPropsRequired(){return this.createFromProps({...this.introspect(),properties:Object.keys(this.#e).reduce((e,r)=>(e[r]=this.#e[r].required(),e),{})})}static#y(e,r,t,n,a){let s=e.introspect();if(!s.properties)return{};let y=Object.keys(s.properties);if(y.length===0)return{};typeof r!="function"&&(r=i=>i);let o=B((i,l)=>(t||r)(i,l),n,e,a);for(let i of y){let l=s.properties[i];if(l instanceof p){let u=l.introspect().properties;u&&typeof u=="object"&&Object.keys(u).length>0?o[i]=p.#y(l,(P,d)=>{let c=r(P,d);return c?(d&&!c[i]&&(c[i]={}),c[i]):null},r,i,o[f]):o[i]=B(r,i,l,o[f])}else if(l[k]===!0){let u=B(r,i,l,o[f]),P=(d,c)=>{let T=r(d,c);return T?(c&&!T[i]&&(T[i]={}),T[i]):null};o[i]=q(u,P)}else o[i]=B(r,i,l,o[f])}return o}static getPropertiesFor(e){if(!(e instanceof p))throw new Error("schema must be an instance of the ObjectSchemaBuilder class");if(e.#s.has(e))return e.#s.get(e);let r=p.#y(e);return e.#s.set(e,r),r}static isValidPropertyDescriptor(e){return typeof e=="object"&&e!==null&&typeof e[f]=="object"}static#c(e,r,t){let a=p.#l(r).introspect().properties,s;if(a)s=Object.keys(a);else if(Array.isArray(e.__externErrorPropertyNames))s=e.__externErrorPropertyNames;else return;for(let y of s){let o=r[y];if(!p.isValidPropertyDescriptor(o))continue;let i=e.getErrorsFor(()=>o);if(!i.isValid)for(let l of i.errors)t(o,l,r);if(a){let l=a[y];(l instanceof p||l[k]===!0)&&typeof e.getErrorsFor=="function"&&p.isValidPropertyDescriptor(o)&&p.#c(e,o,t)}}}static#l(e){if(!p.isValidPropertyDescriptor(e))throw new Error("descriptor is not a valid property descriptor");return e[f].getSchema()}nullable(){return super.nullable()}notNullable(){return super.notNullable()}},v=(p=>b.create({isRequired:!0,properties:p})),B=(p,e,r,t)=>({[f]:{setValue:(n,a,s)=>{let y=p(n,!!s?.createMissingStructure);return y?(typeof e=="string"&&(y[e]=a),!0):!1},getValue:n=>{let a=p(n,!1);return a?typeof e!="string"?{success:!0,value:a}:Object.hasOwn(a,e)?{success:!0,value:a[e]}:{success:!1}:{success:!1}},getSchema:()=>r,parent:t,propertyName:e,toJsonPointer:()=>{let n=[];typeof e=="string"&&n.push(e.replace(/~/g,"~0").replace(/\//g,"~1"));let a=t;for(;a;)typeof a.propertyName=="string"&&n.push(a.propertyName.replace(/~/g,"~0").replace(/\//g,"~1")),a=a.parent;return n.reverse(),n.length>0?"/"+n.join("/"):""}}}),q=(p,e)=>new Proxy(p,{get(r,t,n){if(t===f)return r[f];if(typeof t=="string"&&!(t in r)){let a=B(e,t,void 0,r[f]),s=(y,o)=>{let i=e(y,o);return i!=null&&typeof i=="object"?(o&&!(t in i)&&(i[t]={}),i[t]):null};r[t]=q(a,s)}return Reflect.get(r,t,n)}});v.getPropertiesFor=p=>b.getPropertiesFor(p);v.isValidPropertyDescriptor=b.isValidPropertyDescriptor;export{b as a,v as b};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{c as f,d as k,f as S}from"./chunk-G6HTNXRO.js";var O=class{#e;#t;#n=[];#a=[];get seenValue(){let e=this.#e[f].getValue(this.#t);return e.success?e.value:void 0}get errors(){return this.#n}get isValid(){return this.#n.length===0&&this.getChildErrors().length===0}getChildErrors(){return this.#a}get descriptor(){return this.#e[f]}constructor(e,r,t){if(!b.isValidPropertyDescriptor(e))throw new Error("Invalid property descriptor");this.#e=e,this.#n=Array.isArray(t)?[...t]:[],this.#t=r}addError(e){this.#n.push(e)}addChildError(e){this.#a.push(e)}toJSON(){return{isValid:this.isValid,errors:this.errors}}};var V="must be an object",b=class p extends S{#e={};#t=!1;#n=[];#a=[];[k]=!0;#s=new WeakMap;static create(e){return new p({type:"object",...e})}createFromProps(e){return p.create(e)}constructor(e){super(e),typeof e.properties=="object"&&e.properties&&(this.#e=e.properties,this.#n=Object.keys(e.properties)),typeof e.acceptUnknownProps=="boolean"&&(this.#t=e.acceptUnknownProps),Array.isArray(e.constructorSchemas)&&(this.#a=e.constructorSchemas.filter(r=>r instanceof S))}introspect(){return{...super.introspect(),properties:{...this.#e},acceptUnknownProps:this.#t,constructorSchemas:[...this.#a]}}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}#i(e){p.isValidPropertyDescriptor(e?.context?.rootPropertyDescriptor)||(e.context.rootPropertyDescriptor=p.getPropertiesFor(this)),p.isValidPropertyDescriptor(e.context.currentPropertyDescriptor)||(e.context.currentPropertyDescriptor=e.context.rootPropertyDescriptor),!e.context.rootValidationObject&&e.transaction?.object?.validatedObject&&(e.context.rootValidationObject=e.transaction.object.validatedObject)}preValidateSync(e,r){let t=super.preValidateSync(e,r);return this.#i(t),t}async preValidateAsync(e,r){let t=await super.preValidateAsync(e,r);return this.#i(t),t}#o(e){let{valid:r,context:t,transaction:n,errors:a}=e,s=new WeakMap,y=new Set,{doNotStopOnFirstError:o,rootValidationObject:i}=t,l=t.rootPropertyDescriptor,u=t.currentPropertyDescriptor,P=(h,m,R)=>{if(!p.isValidPropertyDescriptor(h))throw new Error("invalid property descriptor");let g=s.has(h)?s.get(h):null;if(g||(g=new O(h,i),s.set(h,g)),g.addError(m),y.add(g),R&&p.isValidPropertyDescriptor(R)){let j=s.has(R)?s.get(R):null;j||(j=new O(R,i),s.set(R,j)),j.addChildError(g)}},d=(h=>{let m=typeof h=="function"?h(u):u;if(!p.isValidPropertyDescriptor(m))throw new Error("invalid property descriptor");return s.has(m)||s.set(m,new O(m,i)),s.get(m)}),c=()=>[...y].filter(h=>h.errors.length>0),T=e.errors||[],E=h=>{if(typeof h.property=="function"&&p.isValidPropertyDescriptor(u)){let m=h.property(u);if(p.isValidPropertyDescriptor(m)){P(m,h.message,u);return}}p.isValidPropertyDescriptor(u)&&P(u,h.message)};if(!r&&!o&&a){for(let h of a)E(h);return{earlyReturn:!0,result:{valid:r,errors:a,getErrorsFor:d,getInvalidProperties:c}}}if(o&&a)for(let h of a)E(h);let{object:{validatedObject:x}}=n;if(typeof x>"u"&&!this.isRequired||x===null&&(!this.isRequired||this.isNullable))return{earlyReturn:!0,result:{valid:!0,object:n.commit().validatedObject,getErrorsFor:d,getInvalidProperties:c}};if(typeof x!="object"||x===null)return T.length===0&&(T.push({message:V}),P(u,V)),n&&n.rollback(),{earlyReturn:!0,result:{valid:!1,errors:o?T:[T[0]],getErrorsFor:d,getInvalidProperties:c}};let w=this.#n,D=Object.keys(x);if(w.length===0){if(D.length===0)return o&&T.length>0?{earlyReturn:!0,result:{valid:!1,errors:T,getErrorsFor:d,getInvalidProperties:c}}:(n&&n.commit().validatedObject,{earlyReturn:!0,result:{valid:!0,object:{},getErrorsFor:d,getInvalidProperties:c}});if(!this.#t){for(let h=0;h<D.length;h++){let m=`unknown property '${D[h]}'`;if(T.push({message:m}),!o)break}return n&&n.rollback(),{earlyReturn:!0,result:{valid:!1,errors:o?T:[T[0]],getErrorsFor:d,getInvalidProperties:c}}}return n&&n.commit(),{earlyReturn:!0,result:{valid:!0,object:{...x},getErrorsFor:d,getInvalidProperties:c}}}return{earlyReturn:!1,errors:T,objToValidate:x,propKeys:w,objKeys:D,addErrorFor:P,getErrorsFor:d,getInvalidProperties:c,doNotStopOnFirstError:!!o,rootPropertyDescriptor:l,currentPropertyDescriptor:u,validationTransaction:n}}#p(e,r){let{objToValidate:t,objKeys:n,addErrorFor:a,getErrorsFor:s,getInvalidProperties:y,doNotStopOnFirstError:o,currentPropertyDescriptor:i,validationTransaction:l}=e,u=e.errors,P=!1;for(let{result:d}of r)if(!d.valid&&(P=!0,Array.isArray(d.errors)))for(let c of d.errors)u.push(c);for(let d=0;d<n.length;d++){let c=n[d];if(!(c in this.#e)&&!this.#t){let T=`unknown property '${c}'`;if(u.push({message:T}),a(i,T),!o)return l&&l.rollback(),{valid:!1,errors:[u[0]],getErrorsFor:s,getInvalidProperties:y}}}if(!P&&u.length===0){let d={};for(let{key:c,result:T}of r)d[c]=T.object;if(this.#t)for(let c of n)c in this.#e||(d[c]=t[c]);return{valid:!0,object:d,getErrorsFor:s,getInvalidProperties:y}}for(let{key:d,result:c}of r)if(!c.valid){let T=i[d];if(typeof c.getErrorsFor=="function"&&p.isValidPropertyDescriptor(T)){if(p.#c(c,T,a),Array.isArray(c.__externErrorPropertyNames)&&Array.isArray(c.errors))for(let E of c.errors)a(T,E.message,i)}else if(Array.isArray(c.errors)&&p.isValidPropertyDescriptor(T))for(let E of c.errors)a(T,E.message)}return l.rollback(),{valid:!1,errors:o?u:u[0]?[u[0]]:[],getErrorsFor:s,getInvalidProperties:y}}addValidator(e,r){return super.addValidator(e,r)}validate(e,r){return super.validate(e,r)}async validateAsync(e,r){return super.validateAsync(e,r)}_validate(e,r){if(this.canSkipPreValidation&&!r?.doNotStopOnFirstError&&!r?.rootPropertyDescriptor){if(typeof e>"u"||e===null)if(typeof e>"u"&&this.hasDefault)e=this.resolveDefaultValue();else if(!this.isRequired||e===null&&this.isNullable){let t=this;return{valid:!0,object:e,getErrorsFor(n){return t.#r(e,r).getErrorsFor(n)},getInvalidProperties(){return t.#r(e,r).getInvalidProperties()}}}else{let t=this;return{valid:!1,errors:[{message:this.getValidationErrorMessageSync(this.requiredErrorMessage,e)}],getErrorsFor(n){return t.#r(e,r).getErrorsFor(n)},getInvalidProperties(){return t.#r(e,r).getInvalidProperties()}}}else if(typeof e=="object"){let t=this.#n;if(!this.#t){let s=Object.keys(e);for(let y=0;y<s.length;y++)if(!(s[y]in this.#e)){let o=this;return{valid:!1,errors:[{message:`unknown property '${s[y]}'`}],getErrorsFor(i){return o.#r(e,r).getErrorsFor(i)},getInvalidProperties(){return o.#r(e,r).getInvalidProperties()}}}}let n={};for(let s=0;s<t.length;s++){let y=t[s],o=this.#e[y].validate(e[y]);if(!o.valid){let i=this;return{valid:!1,errors:o.errors&&o.errors.length>0?[o.errors[0]]:[],getErrorsFor(l){return i.#r(e,r).getErrorsFor(l)},getInvalidProperties(){return i.#r(e,r).getInvalidProperties()}}}n[y]=o.object}if(this.#t){let s=Object.keys(e);for(let y=0;y<s.length;y++)s[y]in this.#e||(n[s[y]]=e[s[y]])}let a=this;return{valid:!0,object:n,getErrorsFor(s){return a.#r(e,r).getErrorsFor(s)},getInvalidProperties(){return a.#r(e,r).getInvalidProperties()}}}}return this.#r(e,r)}#r(e,r){let t=this.#o(this.preValidateSync(e,r));if(t.earlyReturn)return t.result;let{propKeys:n,objToValidate:a,doNotStopOnFirstError:s,rootPropertyDescriptor:y,currentPropertyDescriptor:o}=t,i=[];for(let l of n){let u=this.#e[l].validate(a[l],{...r,rootPropertyDescriptor:y,currentPropertyDescriptor:o[l]});if(i.push({key:l,result:u}),!u.valid&&!s)break}return this.#p(t,i)}async _validateAsync(e,r){let t=this.#o(await this.preValidateAsync(e,r));if(t.earlyReturn)return t.result;let{propKeys:n,objToValidate:a,doNotStopOnFirstError:s,rootPropertyDescriptor:y,currentPropertyDescriptor:o}=t,i=[];if(s){let l=await Promise.all(n.map(async u=>{let P=await this.#e[u].validateAsync(a[u],{...r,rootPropertyDescriptor:y,currentPropertyDescriptor:o[u]});return{key:u,result:P}}));i.push(...l)}else for(let l of n){let u=await this.#e[l].validateAsync(a[l],{...r,rootPropertyDescriptor:y,currentPropertyDescriptor:o[l]});if(i.push({key:l,result:u}),!u.valid)break}return this.#p(t,i)}acceptUnknownProps(){return this.createFromProps({...this.introspect(),acceptUnknownProps:!0})}notAcceptUnknownProps(){return this.createFromProps({...this.introspect(),acceptUnknownProps:!1})}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}addConstructor(e){if(!(e instanceof S))throw new Error("schema must be an instance of the SchemaBuilder class");return this.createFromProps({...this.introspect(),constructorSchemas:[...this.#a,e]})}clearConstructors(){return this.createFromProps({...this.introspect(),constructorSchemas:[]})}addProp(e,r){if(typeof e!="string"||!e)throw new Error("propName must be a non empty string");if(e in this.#e)throw new Error(`Property ${e} already exists`);if(!(r instanceof S))throw new Error("schema must be an instance of the SchemaBuilder class");return this.createFromProps({...this.introspect(),properties:{...this.introspect().properties,[e]:r}})}optimize(){return this.createFromProps({...this.introspect()})}addProps(e){if(e instanceof p)return this.addProps(e.introspect().properties);if(typeof e!="object")throw new Error("props should be an object");if(e===null)throw new Error("props should not be null");let r={...this.#e};for(let t in e){if(t in this.#e)throw new Error(`property '${t}' already exists`);if(!(e[t]instanceof S))throw new Error(`${t} is not a SchemaBuilder`);r[t]=e[t]}return this.createFromProps({...this.introspect(),properties:r})}omit(e){if(typeof e=="string"){let r=e;if(!r||!(r in this.#e))throw new Error(`property ${r.toString()} does not exists in the schema`);return this.createFromProps({...this.introspect(),properties:(()=>{let t={...this.#e};return delete t[r],t})()})}else if(Array.isArray(e)){let r=e,t=new Map;if(r.forEach(a=>{if(typeof a!="string"||!a)throw new Error("property name must be a string");if(!(a in this.#e))throw new Error(`property ${a.toString()} does not exists in the schema`);t.set(a.toString(),!0)}),t.size===0)throw new Error("please provide at least one property to omit");let n={...this.introspect()};for(let a of t.keys())delete n.properties[a];return this.createFromProps(n)}else if(e instanceof p){let r={...e.introspect().properties},t={...this.introspect()};for(let n in r)n in t.properties&&delete t.properties[n];return this.createFromProps(t)}throw new Error("this parameter type is not supported")}intersect(e){if(!(e instanceof p))throw new Error("schema must be an instance of the ObjectSchemaBuilder class");let r=e.introspect().properties,t=this.introspect(),n=Object.keys(t.properties).reduce((a,s)=>(a[s]=s in r?r[s]:t.properties[s],a),{});return this.createFromProps({...this.introspect(),properties:n})}partial(e){if(typeof e>"u"||e===null)return this.createFromProps({...this.introspect(),properties:Object.keys(this.#e).reduce((r,t)=>(r[t]=this.#e[t].optional(),r),{})});if(Array.isArray(e)){let r=e;if(r.length===0)throw new Error("properties cannot be empty");let t={...this.introspect()};return r.forEach(n=>{if(typeof n!="string")throw new Error("each propery in property list must be as string value");if(!(n in t.properties))throw new Error(`property ${n} does not exists`);t.properties[n]=t.properties[n].optional()}),this.createFromProps(t)}if(typeof e=="string")return this.modifyPropSchema(e,r=>r.optional());throw new Error("expecting string or string[] parameter")}deepPartial(){let e={};for(let r of Object.keys(this.#e)){let t=this.#e[r];t instanceof p?e[r]=t.deepPartial().optional():e[r]=t.optional()}return this.createFromProps({...this.introspect(),properties:e})}pick(e){if(typeof e=="string"){let r=e;if(!r)throw new Error("property cannot be empty");if(!(r in this.#e))throw new Error(`property ${r} does not exists`);return this.createFromProps({...this.introspect(),properties:{[r]:this.#e[r]}})}if(Array.isArray(e)){if(e.length===0)throw new Error("properties must be a non empty erray");let r=e.reduce((t,n)=>{if(typeof n!="string"||!n)throw new Error("each property name must be a non empty string");if(!(n in this.#e))throw new Error(`property ${n} does not exists`);return t[n]=this.#e[n],t},{});return this.createFromProps({...this.introspect(),properties:r})}if(e instanceof p){let t=Object.keys(e.introspect().properties).filter(n=>typeof this.#e[n]<"u");if(t.length===0)throw new Error("there are no common properties in provided schemas");return this.pick(t)}throw new Error("string, array or ObjectSchemaBuilder is expected")}modifyPropSchema(e,r){if(typeof e!="string"||!e)throw new Error("propName must be a non empty string");if(!(e in this.#e))throw new Error(`property ${e} does not exists in the schema`);if(typeof r!="function")throw new Error("callback must be a function");let t=r(this.#e[e]);if(!(t instanceof S))throw new Error("callback must return a SchemaBuilder object");let n={...this.introspect()};return n.properties={...n.properties,[e]:t},this.createFromProps(n)}makePropOptional(e){return this.modifyPropSchema(e,r=>r.optional())}makePropRequired(e){return this.modifyPropSchema(e,r=>r.required())}makeAllPropsOptional(){return this.createFromProps({...this.introspect(),properties:Object.keys(this.#e).reduce((e,r)=>(e[r]=this.#e[r].optional(),e),{})})}makeAllPropsRequired(){return this.createFromProps({...this.introspect(),properties:Object.keys(this.#e).reduce((e,r)=>(e[r]=this.#e[r].required(),e),{})})}static#y(e,r,t,n,a){let s=e.introspect();if(!s.properties)return{};let y=Object.keys(s.properties);if(y.length===0)return{};typeof r!="function"&&(r=i=>i);let o=B((i,l)=>(t||r)(i,l),n,e,a);for(let i of y){let l=s.properties[i];if(l instanceof p){let u=l.introspect().properties;u&&typeof u=="object"&&Object.keys(u).length>0?o[i]=p.#y(l,(P,d)=>{let c=r(P,d);return c?(d&&!c[i]&&(c[i]={}),c[i]):null},r,i,o[f]):o[i]=B(r,i,l,o[f])}else if(l[k]===!0){let u=B(r,i,l,o[f]),P=(d,c)=>{let T=r(d,c);return T?(c&&!T[i]&&(T[i]={}),T[i]):null};o[i]=q(u,P)}else o[i]=B(r,i,l,o[f])}return o}static getPropertiesFor(e){if(!(e instanceof p))throw new Error("schema must be an instance of the ObjectSchemaBuilder class");if(e.#s.has(e))return e.#s.get(e);let r=p.#y(e);return e.#s.set(e,r),r}static isValidPropertyDescriptor(e){return typeof e=="object"&&e!==null&&typeof e[f]=="object"}static#c(e,r,t){let a=p.#l(r).introspect().properties,s;if(a)s=Object.keys(a);else if(Array.isArray(e.__externErrorPropertyNames))s=e.__externErrorPropertyNames;else return;for(let y of s){let o=r[y];if(!p.isValidPropertyDescriptor(o))continue;let i=e.getErrorsFor(()=>o);if(!i.isValid)for(let l of i.errors)t(o,l,r);if(a){let l=a[y];(l instanceof p||l[k]===!0)&&typeof e.getErrorsFor=="function"&&p.isValidPropertyDescriptor(o)&&p.#c(e,o,t)}}}static#l(e){if(!p.isValidPropertyDescriptor(e))throw new Error("descriptor is not a valid property descriptor");return e[f].getSchema()}nullable(){return super.nullable()}notNullable(){return super.notNullable()}},v=(p=>b.create({isRequired:!0,properties:p})),B=(p,e,r,t)=>({[f]:{setValue:(n,a,s)=>{let y=p(n,!!s?.createMissingStructure);return y?(typeof e=="string"&&(y[e]=a),!0):!1},getValue:n=>{let a=p(n,!1);return a?typeof e!="string"?{success:!0,value:a}:Object.hasOwn(a,e)?{success:!0,value:a[e]}:{success:!1}:{success:!1}},getSchema:()=>r,parent:t,propertyName:e,toJsonPointer:()=>{let n=[];typeof e=="string"&&n.push(e.replace(/~/g,"~0").replace(/\//g,"~1"));let a=t;for(;a;)typeof a.propertyName=="string"&&n.push(a.propertyName.replace(/~/g,"~0").replace(/\//g,"~1")),a=a.parent;return n.reverse(),n.length>0?"/"+n.join("/"):""}}}),q=(p,e)=>new Proxy(p,{get(r,t,n){if(t===f)return r[f];if(typeof t=="string"&&!(t in r)){let a=B(e,t,void 0,r[f]),s=(y,o)=>{let i=e(y,o);return i!=null&&typeof i=="object"?(o&&!(t in i)&&(i[t]={}),i[t]):null};r[t]=q(a,s)}return Reflect.get(r,t,n)}});v.getPropertiesFor=p=>b.getPropertiesFor(p);v.isValidPropertyDescriptor=b.isValidPropertyDescriptor;export{b as a,v as b};
|
|
2
|
+
//# sourceMappingURL=chunk-4RMOR7SV.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{f as m}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{f as m}from"./chunk-G6HTNXRO.js";var p=class R extends m{#a;#e;static create(e){return new R({type:"record",...e})}constructor(e){super(e),e.keySchema instanceof m&&(this.#a=e.keySchema),e.valueSchema instanceof m&&(this.#e=e.valueSchema)}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}createFromProps(e){return R.create(e)}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}introspect(){return{...super.introspect(),keySchema:this.#a,valueSchema:this.#e}}#s(e){let t={};for(let[n,o]of e)t[n]=o;return t}#r(e,t,n){let o=this.#e;return{errors:t,isValid:t.length===0,seenValue:n!==null&&typeof n=="object"?n[e]:void 0,descriptor:{key:e,getSchema:()=>o,getValue:r=>r!==null&&typeof r=="object"&&Object.hasOwn(r,e)?{success:!0,value:r[e]}:{success:!1},setValue:(r,d)=>r!==null&&typeof r=="object"?(r[e]=d,!0):!1}}}#n(e,t){let{valid:n,errors:o}=t,r=[],d=new Map,y=()=>this.#s(d),u=l=>{if(typeof l>"u")return{errors:r,isValid:r.length===0,seenValue:e};let i=d.get(l),s=i&&!i.valid?(i.errors??[]).map(T=>T.message):[];return this.#r(l,s,e)};if(!n){for(let l of o??[])r.push(l.message);return{earlyReturn:!0,result:{valid:n,errors:o,getNestedErrors:y,getErrorsFor:u}}}let a=t.transaction.object.validatedObject;return typeof a>"u"&&!this.isRequired||a===null&&(!this.isRequired||this.isNullable)?{earlyReturn:!0,result:{valid:!0,object:a,getNestedErrors:y,getErrorsFor:u}}:typeof a!="object"||Array.isArray(a)||a===null?(r.push("object expected"),{earlyReturn:!0,result:{valid:!1,errors:[{message:"object expected"}],getNestedErrors:y,getErrorsFor:u}}):{earlyReturn:!1,objToValidate:a,nestedKeyResults:d,getNestedErrors:y,getErrorsFor:u}}#l(e,t,n,o,r,d){return e?{valid:!0,object:n,getNestedErrors:r,getErrorsFor:d}:{valid:!1,errors:o?t:[t[0]],getNestedErrors:r,getErrorsFor:d}}validate(e,t){return super.validate(e,t)}async validateAsync(e,t){return super.validateAsync(e,t)}_validate(e,t){if(this.canSkipPreValidation&&!t?.doNotStopOnFirstError){if(typeof e>"u"||e===null)if(typeof e>"u"&&this.hasDefault)e=this.resolveDefaultValue();else if(!this.isRequired||e===null&&this.isNullable){let a=e;return{valid:!0,object:e,getNestedErrors(){return{}},getErrorsFor:l=>typeof l>"u"?{errors:[],isValid:!0,seenValue:a}:this.#r(l,[],a)}}else return this.#t(e,t);if(typeof e!="object"||Array.isArray(e)||e===null)return this.#t(e,t);let n=new Map,o={},r=null;for(let a of Object.keys(e)){let l=this.#a.validate(a);if(!l.valid){let s=l.errors&&l.errors.length>0?l.errors:[{message:`key "${a}" is invalid`}];n.set(a,{valid:!1,errors:s}),r=s[0];break}let i=this.#e.validate(e[a]);if(n.set(a,i),i.valid)o[a]=i.object;else{let s=i.errors&&i.errors.length>0?i.errors:[{message:`value for key "${a}" is invalid`}];n.set(a,{valid:!1,errors:s}),r=s[0];break}}let d=e,y=()=>this.#s(n),u=a=>{if(typeof a>"u")return{errors:[],isValid:!0,seenValue:d};let l=n.get(a),i=l&&!l.valid?(l.errors??[]).map(s=>s.message):[];return this.#r(a,i,d)};return r!==null?{valid:!1,errors:[r],getNestedErrors:y,getErrorsFor:u}:{valid:!0,object:o,getNestedErrors:y,getErrorsFor:u}}return this.#t(e,t)}#t(e,t){let n=this.#n(e,this.preValidateSync(e,t));if(n.earlyReturn)return n.result;let{objToValidate:o,nestedKeyResults:r,getNestedErrors:d,getErrorsFor:y}=n,u=t?.doNotStopOnFirstError??!1,a=!0,l={},i=[];for(let s of Object.keys(o)){let T=this.#a.validate(s);if(!T.valid){a=!1;let h=T.errors&&T.errors.length>0?T.errors:[{message:`key "${s}" is invalid`}];if(r.set(s,{valid:!1,errors:h}),i.push(...h),!u)break;continue}let c=this.#e.validate(o[s],u?{doNotStopOnFirstError:!0}:void 0);if(r.set(s,c),c.valid)l[s]=c.object;else{a=!1;let h=c.errors&&c.errors.length>0?c.errors:[{message:`value for key "${s}" is invalid`}];if(i.push(...h),!u)break}}return this.#l(a,i,l,u,d,y)}async _validateAsync(e,t){let n=this.#n(e,await this.preValidateAsync(e,t));if(n.earlyReturn)return n.result;let{objToValidate:o,nestedKeyResults:r,getNestedErrors:d,getErrorsFor:y}=n,u=t?.doNotStopOnFirstError??!1,a=!0,l={},i=[];for(let s of Object.keys(o)){let T=await this.#a.validateAsync(s);if(!T.valid){a=!1;let h=T.errors&&T.errors.length>0?T.errors:[{message:`key "${s}" is invalid`}];if(r.set(s,{valid:!1,errors:h}),i.push(...h),!u)break;continue}let c=await this.#e.validateAsync(o[s],u?{doNotStopOnFirstError:!0}:void 0);if(r.set(s,c),c.valid)l[s]=c.object;else{a=!1;let h=c.errors&&c.errors.length>0?c.errors:[{message:`value for key "${s}" is invalid`}];if(i.push(...h),!u)break}}return this.#l(a,i,l,u,d,y)}nullable(){return super.nullable()}notNullable(){return super.notNullable()}};function f(R,e){return p.create({type:"record",keySchema:R,valueSchema:e})}export{p as a,f as b};
|
|
2
|
+
//# sourceMappingURL=chunk-57AZDIBB.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{f as r}from"./chunk-G6HTNXRO.js";var s=class a extends r{#e;#t=null;static create(e){return new a({type:"lazy",...e})}constructor(e){if(super(e),typeof e.getter!="function")throw new Error("LazySchemaBuilder: getter must be a function");this.#e=e.getter}resolve(){return this.#t===null&&(this.#t=this.#e()),this.#t}introspect(){return{...super.introspect(),getter:this.#e}}#a(e,t){let{valid:n,transaction:i,errors:o}=e;if(!n)return{valid:n,errors:o};let{object:{validatedObject:l}}=i;return l==null?{valid:!0,object:l}:this.resolve().validate(l,t)}validate(e,t){return super.validate(e,t)}async validateAsync(e,t){return super.validateAsync(e,t)}_validate(e,t){return this.#a(this.preValidateSync(e,t),t)}async _validateAsync(e,t){let n=await super.preValidateAsync(e,t),{valid:i,transaction:o,errors:l}=n;if(!i)return{valid:i,errors:l};let{object:{validatedObject:d}}=o;return d==null?{valid:!0,object:d}:this.resolve().validateAsync(d,t)}createFromProps(e){return a.create(e)}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}nullable(){return super.nullable()}notNullable(){return super.notNullable()}};function c(a){return s.create({type:"lazy",isRequired:!0,preprocessors:[],validators:[],getter:a})}var u=class a extends r{static create(e){return new a({type:"null",...e})}constructor(e){super(e)}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}#e(e){return e===null?{valid:!0,object:null}:e===void 0&&this.hasDefault?this.resolveDefaultValue()===null?{valid:!0,object:null}:{valid:!1,errors:[{message:"must be null"}]}:e===void 0&&!this.isRequired?{valid:!0,object:void 0}:{valid:!1,errors:[{message:"must be null"}]}}validate(e,t){return super.validate(e,t)}async validateAsync(e,t){return super.validateAsync(e,t)}_validate(e,t){return this.#e(e)}async _validateAsync(e,t){return this.#e(e)}createFromProps(e){return a.create(e)}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}nullable(){return super.nullable()}notNullable(){return super.notNullable()}},p=()=>u.create({isRequired:!0});export{s as a,c as b,u as c,p as d};
|
|
2
|
+
//# sourceMappingURL=chunk-C4LSLV6T.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/builders/LazySchemaBuilder.ts","../src/builders/NullSchemaBuilder.ts"],"sourcesContent":["import {\n type BRAND,\n SchemaBuilder,\n type ValidationContext,\n type ValidationErrorMessageProvider,\n type ValidationResult\n} from './SchemaBuilder.js';\n\ntype LazySchemaBuilderCreateProps<R extends boolean = true> = Partial<\n ReturnType<LazySchemaBuilder<any, R>['introspect']>\n>;\n\n/**\n * Lazy schema builder class. Allows defining recursive/self-referential schemas\n * by wrapping a getter function that returns the target schema. The getter is\n * called once on first validation and the result is cached.\n *\n * This is the primary mechanism for building recursive data structures such as\n * tree nodes, nested menus, and threaded comments.\n *\n * **NOTE** TypeScript cannot infer recursive types automatically, so you must\n * provide an explicit type annotation on the variable holding the schema:\n *\n * @example\n * ```ts\n * type TreeNode = { value: number; children: TreeNode[] };\n *\n * const treeNode: SchemaBuilder<TreeNode, true> = object({\n * value: number(),\n * children: array(lazy(() => treeNode))\n * });\n *\n * treeNode.validate({ value: 1, children: [{ value: 2, children: [] }] });\n * // { valid: true, object: { value: 1, children: [{ value: 2, children: [] }] } }\n * ```\n *\n * @example\n * ```ts\n * type Comment = { text: string; replies: Comment[] };\n *\n * const commentSchema: SchemaBuilder<Comment, true> = object({\n * text: string(),\n * replies: array(lazy(() => commentSchema))\n * });\n * ```\n */\nexport class LazySchemaBuilder<\n TResult = any,\n TRequired extends boolean = true,\n TNullable extends boolean = false,\n THasDefault extends boolean = false,\n TExtensions = {}\n> extends SchemaBuilder<\n TResult,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n> {\n #getter: () => SchemaBuilder<TResult, any, any>;\n #resolvedSchema: SchemaBuilder<TResult, any, any> | null = null;\n\n /**\n * @hidden\n */\n public static create(props: LazySchemaBuilderCreateProps<any>) {\n return new LazySchemaBuilder({\n type: 'lazy',\n ...props\n });\n }\n\n protected constructor(props: LazySchemaBuilderCreateProps<TRequired>) {\n super(props as any);\n if (typeof (props as any).getter !== 'function') {\n throw new Error('LazySchemaBuilder: getter must be a function');\n }\n this.#getter = (props as any).getter;\n }\n\n /**\n * Resolves the lazy schema by calling the getter (once; result is cached).\n * After the first call subsequent calls return the cached schema instance.\n */\n public resolve(): SchemaBuilder<TResult, any, any> {\n if (this.#resolvedSchema === null) {\n this.#resolvedSchema = this.#getter();\n }\n return this.#resolvedSchema;\n }\n\n /**\n * @inheritdoc\n */\n public introspect() {\n return {\n ...super.introspect(),\n /**\n * The getter function that returns the lazily-resolved schema.\n * Call {@link LazySchemaBuilder.resolve} to obtain the schema instance.\n */\n getter: this.#getter\n };\n }\n\n #buildResult(\n superResult: ReturnType<LazySchemaBuilder['preValidateSync']>,\n context?: ValidationContext\n ): ValidationResult<TResult> {\n const {\n valid,\n transaction: preValidationTransaction,\n errors\n } = superResult;\n\n if (!valid) {\n return { valid, errors };\n }\n\n const {\n object: { validatedObject: objToValidate }\n } = preValidationTransaction!;\n\n // Value is null/undefined and the schema is optional — skip delegation.\n if (objToValidate == null) {\n return { valid: true, object: objToValidate };\n }\n\n return this.resolve().validate(\n objToValidate,\n context\n ) as ValidationResult<TResult>;\n }\n\n /** {@inheritDoc SchemaBuilder.validate} */\n public validate(\n object: TResult,\n context?: ValidationContext\n ): ValidationResult<TResult> {\n return super.validate(object, context) as ValidationResult<TResult>;\n }\n\n /** {@inheritDoc SchemaBuilder.validateAsync} */\n public async validateAsync(\n object: TResult,\n context?: ValidationContext\n ): Promise<ValidationResult<TResult>> {\n return super.validateAsync(object, context) as Promise<\n ValidationResult<TResult>\n >;\n }\n\n /**\n * Performs synchronous validation of the schema over `object`.\n * Throws if any preprocessor, validator, or error message provider returns a Promise.\n * @param context Optional `ValidationContext` settings.\n */\n protected _validate(\n object: TResult,\n context?: ValidationContext\n ): ValidationResult<TResult> {\n return this.#buildResult(\n this.preValidateSync(object, context),\n context\n );\n }\n\n /**\n * Performs async validation of the schema over `object`.\n * Supports async preprocessors, validators, and error message providers.\n * @param context Optional `ValidationContext` settings.\n */\n protected async _validateAsync(\n object: TResult,\n context?: ValidationContext\n ): Promise<ValidationResult<TResult>> {\n const superResult = await super.preValidateAsync(object, context);\n\n const {\n valid,\n transaction: preValidationTransaction,\n errors\n } = superResult;\n\n if (!valid) {\n return { valid, errors };\n }\n\n const {\n object: { validatedObject: objToValidate }\n } = preValidationTransaction!;\n\n if (objToValidate == null) {\n return { valid: true, object: objToValidate };\n }\n\n return this.resolve().validateAsync(objToValidate, context) as Promise<\n ValidationResult<TResult>\n >;\n }\n\n protected createFromProps<TReq extends boolean>(\n props: LazySchemaBuilderCreateProps<TReq>\n ): this {\n return LazySchemaBuilder.create(props as any) as any;\n }\n\n /**\n * @inheritdoc\n */\n public hasType<T>(\n _notUsed?: T\n ): LazySchemaBuilder<T, true, TNullable, THasDefault, TExtensions> &\n TExtensions {\n return this.createFromProps({\n ...this.introspect()\n } as any) as any;\n }\n\n /**\n * @inheritdoc\n */\n public clearHasType(): LazySchemaBuilder<\n TResult,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return this.createFromProps({\n ...this.introspect()\n } as any) as any;\n }\n\n /**\n * @hidden\n */\n public required(\n errorMessage?: ValidationErrorMessageProvider\n ): LazySchemaBuilder<TResult, true, TNullable, THasDefault, TExtensions> &\n TExtensions {\n return super.required(errorMessage);\n }\n\n /**\n * @hidden\n */\n public optional(): LazySchemaBuilder<\n TResult,\n false,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.optional();\n }\n\n /**\n * @hidden\n */\n public default(\n value: TResult | (() => TResult)\n ): LazySchemaBuilder<TResult, true, TNullable, true, TExtensions> &\n TExtensions {\n return super.default(value) as any;\n }\n\n /**\n * @hidden\n */\n public clearDefault(): LazySchemaBuilder<\n TResult,\n TRequired,\n TNullable,\n false,\n TExtensions\n > &\n TExtensions {\n return super.clearDefault() as any;\n }\n\n /**\n * @hidden\n */\n public brand<TBrand extends string | symbol>(\n _name?: TBrand\n ): LazySchemaBuilder<\n TResult & { readonly [K in BRAND]: TBrand },\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.brand(_name);\n }\n\n /**\n * @hidden\n */\n public readonly(): LazySchemaBuilder<\n Readonly<TResult>,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.readonly();\n }\n\n /**\n * @hidden\n */\n public nullable(): LazySchemaBuilder<\n TResult,\n TRequired,\n true,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.nullable() as any;\n }\n\n /**\n * @hidden\n */\n public notNullable(): LazySchemaBuilder<\n TResult,\n TRequired,\n false,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.notNullable() as any;\n }\n}\n\n/**\n * Creates a lazy schema that defers the schema definition until first validation.\n * Use this to define recursive/self-referential schemas.\n *\n * The getter function is called **once** on first use and the result is cached.\n * You **must** provide an explicit TypeScript type annotation on the variable\n * holding the outer schema — TypeScript cannot infer recursive types automatically.\n *\n * @param getter - A function that returns the schema to use for validation.\n *\n * @example\n * ```ts\n * // Tree structure\n * type TreeNode = { value: number; children: TreeNode[] };\n *\n * const treeNode: SchemaBuilder<TreeNode, true> = object({\n * value: number(),\n * children: array(lazy(() => treeNode))\n * });\n * ```\n *\n * @example\n * ```ts\n * // Optional recursive field (submenu)\n * type MenuItem = { label: string; submenu?: MenuItem[] };\n *\n * const menuItem: SchemaBuilder<MenuItem, true> = object({\n * label: string(),\n * submenu: array(lazy(() => menuItem)).optional()\n * });\n * ```\n */\nexport function lazy<TResult>(\n getter: () => SchemaBuilder<TResult, any, any>\n): LazySchemaBuilder<TResult, true, false, false, {}> {\n return LazySchemaBuilder.create({\n type: 'lazy',\n isRequired: true,\n preprocessors: [],\n validators: [],\n getter\n } as any);\n}\n","import {\n type BRAND,\n SchemaBuilder,\n type ValidationContext,\n type ValidationErrorMessageProvider,\n type ValidationResult\n} from './SchemaBuilder.js';\n\ntype NullSchemaBuilderCreateProps<R extends boolean = true> = Partial<\n ReturnType<NullSchemaBuilder<R>['introspect']>\n>;\n\n/**\n * Schema builder for `null` values. Validates that the input is exactly `null`.\n *\n * When required (the default), only `null` is accepted. When optional (via\n * `.optional()`), both `null` and `undefined` are accepted; any other value\n * is rejected.\n *\n * This builder is useful when you need to represent an explicitly-null field\n * in a typed schema, for example in discriminated-union branches or when\n * modelling a JSON payload that may carry a JSON `null` value.\n *\n * **NOTE** this class is exported only to give opportunity to extend it\n * by inheriting. It is not recommended to create an instance of this class\n * directly. Use {@link nul | nul()} function instead.\n *\n * @example\n * ```ts\n * import { nul } from '@cleverbrush/schema';\n *\n * const schema = nul();\n *\n * schema.validate(null); // { valid: true, object: null }\n * schema.validate(undefined); // { valid: false }\n * schema.validate(0); // { valid: false }\n * schema.validate(''); // { valid: false }\n * ```\n *\n * @example\n * ```ts\n * // Optional — accepts null or undefined\n * const schema = nul().optional();\n *\n * schema.validate(null); // { valid: true, object: null }\n * schema.validate(undefined); // { valid: true, object: undefined }\n * schema.validate(false); // { valid: false }\n * ```\n *\n * @example\n * ```ts\n * // Use inside a union to model a nullable string field\n * import { union, string, nul, InferType } from '@cleverbrush/schema';\n *\n * const NullableString = union(string()).or(nul());\n * type NullableString = InferType<typeof NullableString>;\n * // string | null\n *\n * NullableString.validate('hello'); // valid\n * NullableString.validate(null); // valid\n * NullableString.validate(42); // invalid\n * ```\n *\n * @see {@link nul}\n */\nexport class NullSchemaBuilder<\n TRequired extends boolean = true,\n TNullable extends boolean = false,\n TExplicitType = undefined,\n THasDefault extends boolean = false,\n TExtensions = {}\n> extends SchemaBuilder<null, TRequired, TNullable, THasDefault, TExtensions> {\n /**\n * @hidden\n */\n public static create(props: NullSchemaBuilderCreateProps<any>) {\n return new NullSchemaBuilder({\n type: 'null',\n ...props\n });\n }\n\n protected constructor(props: NullSchemaBuilderCreateProps<TRequired>) {\n super(props as any);\n }\n\n /**\n * @hidden\n */\n public hasType<T>(\n _notUsed?: T\n ): NullSchemaBuilder<true, TNullable, T, THasDefault, TExtensions> &\n TExtensions {\n return this.createFromProps({\n ...this.introspect()\n } as any) as any;\n }\n\n /**\n * @hidden\n */\n public clearHasType(): NullSchemaBuilder<\n TRequired,\n TNullable,\n undefined,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return this.createFromProps({\n ...this.introspect()\n } as any) as any;\n }\n\n // The SchemaBuilder base-class preValidateSync/preValidateAsync treats\n // null as an invalid value for required schemas, which would prevent null\n // from ever passing validation here. We therefore bypass preValidateSync\n // entirely and implement the full (and simple) validation inline.\n #buildResult(object: any): ValidationResult<null> {\n if (object === null) return { valid: true, object: null };\n\n if (object === undefined && this.hasDefault) {\n const defaultVal = this.resolveDefaultValue();\n if (defaultVal === null) return { valid: true, object: null };\n return { valid: false, errors: [{ message: 'must be null' }] };\n }\n\n if (object === undefined && !this.isRequired) {\n return { valid: true, object: undefined as any };\n }\n\n return {\n valid: false,\n errors: [{ message: 'must be null' }]\n };\n }\n\n /** {@inheritDoc SchemaBuilder.validate} */\n public validate(\n object: null,\n context?: ValidationContext\n ): ValidationResult<null> {\n return super.validate(object, context) as ValidationResult<null>;\n }\n\n /** {@inheritDoc SchemaBuilder.validateAsync} */\n public async validateAsync(\n object: null,\n context?: ValidationContext\n ): Promise<ValidationResult<null>> {\n return super.validateAsync(object, context) as Promise<\n ValidationResult<null>\n >;\n }\n\n /**\n * Performs synchronous validation of the schema over `object`.\n * @param context Optional `ValidationContext` settings.\n */\n protected _validate(\n object: null,\n _context?: ValidationContext\n ): ValidationResult<null> {\n return this.#buildResult(object);\n }\n\n /**\n * Performs async validation of the schema over `object`.\n * @param context Optional `ValidationContext` settings.\n */\n protected async _validateAsync(\n object: null,\n _context?: ValidationContext\n ): Promise<ValidationResult<null>> {\n return this.#buildResult(object);\n }\n\n protected createFromProps<TReq extends boolean>(\n props: NullSchemaBuilderCreateProps<TReq>\n ): this {\n return NullSchemaBuilder.create(props as any) as any;\n }\n\n /**\n * @hidden\n */\n public required(\n errorMessage?: ValidationErrorMessageProvider\n ): NullSchemaBuilder<\n true,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.required(errorMessage);\n }\n\n /**\n * @hidden\n */\n public optional(): NullSchemaBuilder<\n false,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.optional();\n }\n\n /**\n * @hidden\n */\n public default(\n value: null | (() => null)\n ): NullSchemaBuilder<true, TNullable, TExplicitType, true, TExtensions> &\n TExtensions {\n return super.default(value) as any;\n }\n\n /**\n * @hidden\n */\n public clearDefault(): NullSchemaBuilder<\n TRequired,\n TNullable,\n TExplicitType,\n false,\n TExtensions\n > &\n TExtensions {\n return super.clearDefault() as any;\n }\n\n /**\n * @hidden\n */\n public brand<TBrand extends string | symbol>(\n _name?: TBrand\n ): NullSchemaBuilder<\n TRequired,\n TNullable,\n null & { readonly [K in BRAND]: TBrand },\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.brand(_name);\n }\n\n /**\n * Marks the inferred type as `Readonly<null>`. Since `null` is already\n * immutable this is an identity operation, but it sets the `isReadonly`\n * introspection flag for tooling consistency.\n *\n * @see {@link SchemaBuilder.readonly}\n */\n public readonly(): NullSchemaBuilder<\n TRequired,\n TNullable,\n Readonly<null>,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.readonly();\n }\n\n /**\n * @hidden\n */\n public nullable(): NullSchemaBuilder<\n TRequired,\n true,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.nullable() as any;\n }\n\n /**\n * @hidden\n */\n public notNullable(): NullSchemaBuilder<\n TRequired,\n false,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.notNullable() as any;\n }\n}\n\n/**\n * Creates a schema that validates the value is exactly `null`.\n *\n * By default the schema is **required** — only `null` is accepted.\n * Call `.optional()` to also allow `undefined`.\n *\n * @example\n * ```ts\n * import { nul } from '@cleverbrush/schema';\n *\n * nul().validate(null); // { valid: true, object: null }\n * nul().validate(undefined); // { valid: false }\n * nul().validate(0); // { valid: false }\n * ```\n *\n * @example\n * ```ts\n * nul().optional().validate(null); // { valid: true, object: null }\n * nul().optional().validate(undefined); // { valid: true, object: undefined }\n * nul().optional().validate(false); // { valid: false }\n * ```\n *\n * @example\n * ```ts\n * // Nullable field in an object schema\n * import { object, string, nul, union, InferType } from '@cleverbrush/schema';\n *\n * const Schema = object({\n * name: string(),\n * deleted: union(nul()).or(string()), // null | string\n * });\n *\n * type T = InferType<typeof Schema>;\n * // { name: string; deleted: null | string }\n * ```\n */\nexport const nul = () =>\n NullSchemaBuilder.create({\n isRequired: true\n }) as NullSchemaBuilder<true>;\n"],"mappings":"wCA8CO,IAAMA,EAAN,MAAMC,UAMHC,CAMR,CACEC,GACAC,GAA2D,KAK3D,OAAc,OAAOC,EAA0C,CAC3D,OAAO,IAAIJ,EAAkB,CACzB,KAAM,OACN,GAAGI,CACP,CAAC,CACL,CAEU,YAAYA,EAAgD,CAElE,GADA,MAAMA,CAAY,EACd,OAAQA,EAAc,QAAW,WACjC,MAAM,IAAI,MAAM,8CAA8C,EAElE,KAAKF,GAAWE,EAAc,MAClC,CAMO,SAA4C,CAC/C,OAAI,KAAKD,KAAoB,OACzB,KAAKA,GAAkB,KAAKD,GAAQ,GAEjC,KAAKC,EAChB,CAKO,YAAa,CAChB,MAAO,CACH,GAAG,MAAM,WAAW,EAKpB,OAAQ,KAAKD,EACjB,CACJ,CAEAG,GACIC,EACAC,EACyB,CACzB,GAAM,CACF,MAAAC,EACA,YAAaC,EACb,OAAAC,CACJ,EAAIJ,EAEJ,GAAI,CAACE,EACD,MAAO,CAAE,MAAAA,EAAO,OAAAE,CAAO,EAG3B,GAAM,CACF,OAAQ,CAAE,gBAAiBC,CAAc,CAC7C,EAAIF,EAGJ,OAAIE,GAAiB,KACV,CAAE,MAAO,GAAM,OAAQA,CAAc,EAGzC,KAAK,QAAQ,EAAE,SAClBA,EACAJ,CACJ,CACJ,CAGO,SACHK,EACAL,EACyB,CACzB,OAAO,MAAM,SAASK,EAAQL,CAAO,CACzC,CAGA,MAAa,cACTK,EACAL,EACkC,CAClC,OAAO,MAAM,cAAcK,EAAQL,CAAO,CAG9C,CAOU,UACNK,EACAL,EACyB,CACzB,OAAO,KAAKF,GACR,KAAK,gBAAgBO,EAAQL,CAAO,EACpCA,CACJ,CACJ,CAOA,MAAgB,eACZK,EACAL,EACkC,CAClC,IAAMD,EAAc,MAAM,MAAM,iBAAiBM,EAAQL,CAAO,EAE1D,CACF,MAAAC,EACA,YAAaC,EACb,OAAAC,CACJ,EAAIJ,EAEJ,GAAI,CAACE,EACD,MAAO,CAAE,MAAAA,EAAO,OAAAE,CAAO,EAG3B,GAAM,CACF,OAAQ,CAAE,gBAAiBC,CAAc,CAC7C,EAAIF,EAEJ,OAAIE,GAAiB,KACV,CAAE,MAAO,GAAM,OAAQA,CAAc,EAGzC,KAAK,QAAQ,EAAE,cAAcA,EAAeJ,CAAO,CAG9D,CAEU,gBACNH,EACI,CACJ,OAAOJ,EAAkB,OAAOI,CAAY,CAChD,CAKO,QACHS,EAEY,CACZ,OAAO,KAAK,gBAAgB,CACxB,GAAG,KAAK,WAAW,CACvB,CAAQ,CACZ,CAKO,cAOS,CACZ,OAAO,KAAK,gBAAgB,CACxB,GAAG,KAAK,WAAW,CACvB,CAAQ,CACZ,CAKO,SACHC,EAEY,CACZ,OAAO,MAAM,SAASA,CAAY,CACtC,CAKO,UAOS,CACZ,OAAO,MAAM,SAAS,CAC1B,CAKO,QACHC,EAEY,CACZ,OAAO,MAAM,QAAQA,CAAK,CAC9B,CAKO,cAOS,CACZ,OAAO,MAAM,aAAa,CAC9B,CAKO,MACHC,EAQY,CACZ,OAAO,MAAM,MAAMA,CAAK,CAC5B,CAKO,UAOS,CACZ,OAAO,MAAM,SAAS,CAC1B,CAKO,UAOS,CACZ,OAAO,MAAM,SAAS,CAC1B,CAKO,aAOS,CACZ,OAAO,MAAM,YAAY,CAC7B,CACJ,EAkCO,SAASC,EACZC,EACkD,CAClD,OAAOnB,EAAkB,OAAO,CAC5B,KAAM,OACN,WAAY,GACZ,cAAe,CAAC,EAChB,WAAY,CAAC,EACb,OAAAmB,CACJ,CAAQ,CACZ,CC/TO,IAAMC,EAAN,MAAMC,UAMHC,CAAoE,CAI1E,OAAc,OAAOC,EAA0C,CAC3D,OAAO,IAAIF,EAAkB,CACzB,KAAM,OACN,GAAGE,CACP,CAAC,CACL,CAEU,YAAYA,EAAgD,CAClE,MAAMA,CAAY,CACtB,CAKO,QACHC,EAEY,CACZ,OAAO,KAAK,gBAAgB,CACxB,GAAG,KAAK,WAAW,CACvB,CAAQ,CACZ,CAKO,cAOS,CACZ,OAAO,KAAK,gBAAgB,CACxB,GAAG,KAAK,WAAW,CACvB,CAAQ,CACZ,CAMAC,GAAaC,EAAqC,CAC9C,OAAIA,IAAW,KAAa,CAAE,MAAO,GAAM,OAAQ,IAAK,EAEpDA,IAAW,QAAa,KAAK,WACV,KAAK,oBAAoB,IACzB,KAAa,CAAE,MAAO,GAAM,OAAQ,IAAK,EACrD,CAAE,MAAO,GAAO,OAAQ,CAAC,CAAE,QAAS,cAAe,CAAC,CAAE,EAG7DA,IAAW,QAAa,CAAC,KAAK,WACvB,CAAE,MAAO,GAAM,OAAQ,MAAiB,EAG5C,CACH,MAAO,GACP,OAAQ,CAAC,CAAE,QAAS,cAAe,CAAC,CACxC,CACJ,CAGO,SACHA,EACAC,EACsB,CACtB,OAAO,MAAM,SAASD,EAAQC,CAAO,CACzC,CAGA,MAAa,cACTD,EACAC,EAC+B,CAC/B,OAAO,MAAM,cAAcD,EAAQC,CAAO,CAG9C,CAMU,UACND,EACAE,EACsB,CACtB,OAAO,KAAKH,GAAaC,CAAM,CACnC,CAMA,MAAgB,eACZA,EACAE,EAC+B,CAC/B,OAAO,KAAKH,GAAaC,CAAM,CACnC,CAEU,gBACNH,EACI,CACJ,OAAOF,EAAkB,OAAOE,CAAY,CAChD,CAKO,SACHM,EAQY,CACZ,OAAO,MAAM,SAASA,CAAY,CACtC,CAKO,UAOS,CACZ,OAAO,MAAM,SAAS,CAC1B,CAKO,QACHC,EAEY,CACZ,OAAO,MAAM,QAAQA,CAAK,CAC9B,CAKO,cAOS,CACZ,OAAO,MAAM,aAAa,CAC9B,CAKO,MACHC,EAQY,CACZ,OAAO,MAAM,MAAMA,CAAK,CAC5B,CASO,UAOS,CACZ,OAAO,MAAM,SAAS,CAC1B,CAKO,UAOS,CACZ,OAAO,MAAM,SAAS,CAC1B,CAKO,aAOS,CACZ,OAAO,MAAM,YAAY,CAC7B,CACJ,EAsCaC,EAAM,IACfZ,EAAkB,OAAO,CACrB,WAAY,EAChB,CAAC","names":["LazySchemaBuilder","_LazySchemaBuilder","SchemaBuilder","#getter","#resolvedSchema","props","#buildResult","superResult","context","valid","preValidationTransaction","errors","objToValidate","object","_notUsed","errorMessage","value","_name","lazy","getter","NullSchemaBuilder","_NullSchemaBuilder","SchemaBuilder","props","_notUsed","#buildResult","object","context","_context","errorMessage","value","_name","nul"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as h,e as m,f as c}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{c as h,e as m,f as c}from"./chunk-G6HTNXRO.js";var f=class T extends c{#e;#n=null;#t=null;static create(e){return new T({type:"union",...e})}constructor(e){super(e),Array.isArray(e.options)&&(this.#e=e.options,this.#o())}#o(){let e=this.#e;if(!e||e.length<2)return;let n=[];for(let s of e){let t=s.introspect();if(t.type!=="object")return;n.push(t)}let i=n[0].properties;if(i)for(let s of Object.keys(i)){let t=new Map,a=!0;for(let o=0;o<n.length;o++){let d=n[o].properties;if(!d||!(s in d)){a=!1;break}let r=d[s].introspect();if(r.isRequired!==!0){a=!1;break}let l=r.equalsTo;if(l==null){a=!1;break}if(typeof l!="string"&&typeof l!="number"){a=!1;break}if(t.has(l)){a=!1;break}t.set(l,e[o])}if(a&&t.size===e.length){this.#n=s,this.#t=t;return}}}introspect(){return{...super.introspect(),options:this.#e,discriminatorPropertyName:this.#n??void 0}}get isNullRequiredViolation(){return!1}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}#r(e,n){let{valid:i,transaction:s,context:t,errors:a}=n,o={[h]:{setValue:()=>!1,getValue:u=>({success:!0,value:u}),getSchema:()=>this,parent:void 0,propertyName:void 0,toJsonPointer:()=>""}},d=[],y=m([],()=>e,()=>d,()=>o[h]),r=(()=>y);if(!i)return d.push(...(a||[]).map(u=>u.message||String(u))),{needsOptionValidation:!1,result:{valid:i,errors:a,getNestedErrors:r}};let{object:{validatedObject:l}}=s;return typeof l>"u"&&!this.isRequired||l===null&&(!this.isRequired||this.isNullable)?{needsOptionValidation:!1,result:{valid:!0,object:l,getNestedErrors:r}}:{needsOptionValidation:!0,objToValidate:l,prevalidationContext:t,preValidationTransaction:s,getNestedErrors:r,optionResults:y,rootErrors:d}}#s(e,n,i,s,t,a){if(i[n]=e,e.valid)return{valid:!0,object:e.object,getNestedErrors:a};let o=e.errors;return Array.isArray(o)&&o.length>0&&o.length<t.minErrorsCount&&(t.resultingErrors=o,t.minErrorsCount=o.length),t.objToValidate=s.rollback().validatedObject,null}validate(e,n){return super.validate(e,n)}async validateAsync(e,n){return super.validateAsync(e,n)}_validate(e,n){if(this.canSkipPreValidation&&!n?.doNotStopOnFirstError&&!n?.rootPropertyDescriptor){if(typeof e>"u")if(this.hasDefault)e=this.resolveDefaultValue();else return this.isRequired?this.#i(!1,void 0,[{message:this.getValidationErrorMessageSync(this.requiredErrorMessage,e)}],e,n):this.#i(!0,e,void 0,e,n);else if(e===null&&(!this.isRequired||this.isNullable))return this.#i(!0,e,void 0,e,n);if(this.#n&&this.#t&&typeof e=="object"&&e!==null){let i=e[this.#n],s=this.#t.get(i);if(s){let t=s.validate(e);return this.#i(t.valid,t.valid?t.object:void 0,t.valid?void 0:t.errors,e,n)}return this.#i(!1,void 0,[{message:"value doesn't match any option in union schema"}],e,n)}if(!this.#n){let i=this.#e,s=Number.MAX_SAFE_INTEGER,t=[];for(let a=0;a<i.length;a++){let o=i[a].validate(e);if(o.valid)return this.#i(!0,o.object,void 0,e,n);let d=o.errors;Array.isArray(d)&&d.length>0&&d.length<s&&(t=d,s=d.length)}return this.#i(!1,void 0,t,e,n)}}return this.#a(e,n)}#i(e,n,i,s,t){let a=this;return e?{valid:!0,object:n,getNestedErrors(){return a.#a(s,t).getNestedErrors()}}:{valid:!1,errors:i,getNestedErrors(){return a.#a(s,t).getNestedErrors()}}}#a(e,n){let i=this.#r(e,this.preValidateSync(e,n));if(!i.needsOptionValidation)return i.result;let{prevalidationContext:s,preValidationTransaction:t,getNestedErrors:a,optionResults:o,rootErrors:d}=i;if(this.#n&&this.#t){let r=i.objToValidate;if(typeof r=="object"&&r!==null){let l=r[this.#n],u=this.#t.get(l);if(u){let p=u.validate(r,{...s,currentPropertyDescriptor:void 0,rootPropertyDescriptor:void 0});if(p.valid)return{valid:!0,object:p.object,getNestedErrors:a}}}}let y={objToValidate:i.objToValidate,minErrorsCount:Number.MAX_SAFE_INTEGER,resultingErrors:[]};for(let r=0;r<this.#e.length;r++){let l=this.#e[r].validate(y.objToValidate,{...s,currentPropertyDescriptor:void 0,rootPropertyDescriptor:void 0}),u=this.#s(l,r,o,t,y,a);if(u)return u}return d.push("value doesn't match any option in union schema"),{valid:!1,errors:y.resultingErrors,getNestedErrors:a}}async _validateAsync(e,n){let i=this.#r(e,await super.preValidateAsync(e,n));if(!i.needsOptionValidation)return i.result;let{prevalidationContext:s,preValidationTransaction:t,getNestedErrors:a,optionResults:o,rootErrors:d}=i;if(this.#n&&this.#t){let r=i.objToValidate;if(typeof r=="object"&&r!==null){let l=r[this.#n],u=this.#t.get(l);if(u){let p=await u.validateAsync(r,{...s,currentPropertyDescriptor:void 0,rootPropertyDescriptor:void 0});if(p.valid)return{valid:!0,object:p.object,getNestedErrors:a}}}}let y={objToValidate:i.objToValidate,minErrorsCount:Number.MAX_SAFE_INTEGER,resultingErrors:[]};for(let r=0;r<this.#e.length;r++){let l=await this.#e[r].validateAsync(y.objToValidate,{...s,currentPropertyDescriptor:void 0,rootPropertyDescriptor:void 0}),u=this.#s(l,r,o,t,y,a);if(u)return u}return d.push("value doesn't match any option in union schema"),{valid:!1,errors:y.resultingErrors,getNestedErrors:a}}createFromProps(e){return T.create(e)}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}or(e){if(!(e instanceof c))throw new Error("schema must be an instance of the SchemaBuilder class");return this.createFromProps({...this.introspect(),options:[...this.#e,e]})}removeOption(e){if(typeof e!="number"||e<0||e>this.#e.length)throw new Error("index must be >= 0 and <= count of the options");return this.createFromProps({...this.introspect(),options:this.#e.filter((n,i)=>i!==e)})}removeFirstOption(){return this.removeOption(0)}reset(e){if(!(e instanceof c))throw new Error("schema must be an instance of the SchemaBuilder class");return this.createFromProps({...this.introspect(),options:[e]})}nullable(){return super.nullable()}notNullable(){return super.notNullable()}},E=T=>f.create({isRequired:!0,options:[T]});export{f as a,E as b};
|
|
2
|
+
//# sourceMappingURL=chunk-EBGC6ZBF.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{f as o}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{f as o}from"./chunk-G6HTNXRO.js";var i=class n extends o{#e;#t=function(){return`is expected to be equal ${this.#e}`};#a=this.#t;static create(e){return new n({type:"boolean",...e})}constructor(e){super(e),(typeof e.equalsTo=="boolean"||typeof e.equalsTo>"u")&&(this.#e=e.equalsTo),this.#a=this.assureValidationErrorMessageProvider(e.equalsToValidationErrorMessageProvider,this.#t)}introspect(){return{...super.introspect(),equalsTo:this.#e,equalsToValidationErrorMessageProvider:this.#a}}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}#s(e){return typeof e!="boolean"?{message:"expected to be boolean"}:typeof this.#e<"u"&&e!==this.#e?{provider:this.#a}:null}#r(e){let{valid:a,transaction:t,errors:s}=e;if(!a)return{done:!0,result:{valid:a,errors:s}};let{object:{validatedObject:r}}=t;if(typeof r>"u"&&!this.isRequired||r===null&&(!this.isRequired||this.isNullable))return{done:!0,result:{valid:!0,object:r}};let l=this.#s(r);return l?"message"in l?{done:!0,result:{valid:!1,errors:[{message:l.message}]}}:{done:!1,provider:l.provider,objToValidate:r}:{done:!0,result:{valid:!0,object:r}}}validate(e,a){return super.validate(e,a)}async validateAsync(e,a){return super.validateAsync(e,a)}_validate(e,a){if(this.canSkipPreValidation){if(typeof e>"u"||e===null)if(typeof e>"u"&&this.hasDefault)e=this.resolveDefaultValue();else return!this.isRequired||e===null&&this.isNullable?{valid:!0,object:e}:{valid:!1,errors:[{message:this.getValidationErrorMessageSync(this.requiredErrorMessage,e)}]};let s=this.#s(e);return s?"message"in s?{valid:!1,errors:[{message:s.message}]}:{valid:!1,errors:[{message:this.getValidationErrorMessageSync(s.provider,e)}]}:{valid:!0,object:e}}let t=this.#r(this.preValidateSync(e,a));return t.done?t.result:{valid:!1,errors:[{message:this.getValidationErrorMessageSync(t.provider,t.objToValidate)}]}}async _validateAsync(e,a){let t=this.#r(await super.preValidateAsync(e,a));return t.done?t.result:{valid:!1,errors:[{message:await this.getValidationErrorMessage(t.provider,t.objToValidate)}]}}createFromProps(e){return n.create(e)}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}equals(e,a){if(typeof e!="boolean")throw new Error("boolean expected");return this.createFromProps({...this.introspect(),equalsTo:e,equalsToValidationErrorMessageProvider:a})}clearEquals(){return this.createFromProps({...this.introspect(),equalsTo:void 0})}coerce(){return this.addPreprocessor((e=>e==="true"?!0:e==="false"?!1:e),{mutates:!0})}nullable(){return super.nullable()}notNullable(){return super.notNullable()}},d=()=>i.create({isRequired:!0});export{i as a,d as b};
|
|
2
|
+
//# sourceMappingURL=chunk-ETJPB3TR.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{f as i}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{f as i}from"./chunk-G6HTNXRO.js";var r=class s extends i{#e;static create(e){return new s({type:"promise",...e})}constructor(e){super(e),e.resolvedType instanceof i&&(this.#e=e.resolvedType)}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}introspect(){return{...super.introspect(),resolvedType:this.#e}}#a(e){let{valid:a,transaction:n,errors:l}=e;if(!a)return{valid:a,errors:l};let{object:{validatedObject:t}}=n;return typeof t>"u"&&!this.isRequired||t===null&&(!this.isRequired||this.isNullable)?{valid:!0,object:t}:t==null||typeof t.then!="function"?{valid:!1,errors:[{message:`expected a Promise, but saw ${t===null?"null":typeof t}`}]}:{valid:!0,object:t}}validate(e,a){return super.validate(e,a)}async validateAsync(e,a){return super.validateAsync(e,a)}_validate(e,a){return this.#a(this.preValidateSync(e,a))}async _validateAsync(e,a){return this.#a(await super.preValidateAsync(e,a))}createFromProps(e){return s.create(e)}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}nullable(){return super.nullable()}notNullable(){return super.notNullable()}hasResolvedType(e){return this.createFromProps({...this.introspect(),resolvedType:e})}};function o(s){return r.create({isRequired:!0,resolvedType:s})}export{r as a,o as b};
|
|
2
|
+
//# sourceMappingURL=chunk-FTA66XZT.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var y=Symbol("transaction"),P=[Error,RegExp,Date],R={shouldNotWrapWithTransaction:u=>!!P.find(e=>u instanceof e)},h=(u,e)=>{let r={},a=new Map;e=Object.assign({},R,e||{});let{shouldNotWrapWithTransaction:i}=e,l=()=>!!Object.keys(r).find(s=>r[s]?.[y]?r[s][y].isDirty():!0)||a.size>0,c=()=>{let s={};Object.keys(u).forEach(t=>{s[t]=u[t]}),Object.keys(r).forEach(t=>{let o=r[t];if(o[y]){let{commit:d}=o[y];s[t]=d()}else s[t]=r[t]});for(let t of a.keys())delete s[t];return r={},a=new Map,s},p=()=>{for(let s in r){let t=r[s];t&&typeof t=="object"&&t[y]&&t[y].rollback()}return r={},a=new Map,u};if(Array.isArray(u)){let s=u.map(d=>typeof d=="object"&&d&&!i(d)?h(d).object:d),t=()=>s.map(d=>d&&typeof d[y]=="object"?d[y].commit():d),o=()=>!!s.find((d,f)=>d&&typeof d[y]=="object"?d[y].isDirty():s[f]!==u[f]);return Object.defineProperty(s,y,{writable:!1,configurable:!1,value:{initial:u,object:s,commit:t,rollback:()=>u,isDirty:o}}),{object:s,commit:t,rollback:()=>u,isDirty:o}}let n=new Proxy(u,{set:(s,t,o)=>s&&s[t]===o?(delete r[t],!0):(r[t]=o,a.delete(t),!0),ownKeys:s=>[...Object.keys(s).filter(t=>!a.has(t)),...Object.keys(r).filter(t=>!(t in s))],getOwnPropertyDescriptor:(s,t)=>{if(!a.has(t))return t in r?Object.getOwnPropertyDescriptor(r,t):Object.getOwnPropertyDescriptor(s,t)},has:(s,t)=>a.has(t)?!1:t in r?!0:t in s,get:(s,t)=>{if(typeof t=="symbol")return t===y?{initial:u,object:n,commit:c,rollback:p,isDirty:l}:s[t];if(t in r)return r[t];if(!a.has(t)){if(!g(s[t])&&typeof s[t]=="object"&&s[t]&&!i(s[t])){let{object:o}=h(s[t],e);return r[t]=o,o}return s[t]}},deleteProperty:(s,t)=>(t in r&&(r[t]&&typeof r[t][y]=="object"&&r[t][y].rollback(),delete r[t]),t in s&&a.set(t,!0),!0)});return{object:n,commit:c,rollback:p,isDirty:l}},T=u=>({object:u,commit:()=>u,rollback:()=>u,isDirty:()=>!1}),g=u=>u&&typeof u=="object"&&Object.hasOwn(u,y);var m=class extends Error{errors;constructor(e){let r=e.length>0?e.map(a=>a.message).join("; "):"Validation failed";super(r),this.name="SchemaValidationError",this.errors=e}},x=Symbol(),v=Symbol();function E(u,e,r,a){return Object.defineProperties(u,{seenValue:{get:e,enumerable:!1},errors:{get:r,enumerable:!1},isValid:{get:()=>r().length===0,enumerable:!1},descriptor:{get:a,enumerable:!1}}),u}var b=class{#d=!0;#a=!1;#y=!1;#p;#h;#e=[];#t=[];#n=!1;#T=!0;#c={};#f="base";#m="is required";#o="is required";#s=void 0;#i=void 0;#l=!1;#b=void 0;#u;get"~standard"(){if(this.#u)return this.#u;let e=this;return this.#u={version:1,vendor:"@cleverbrush/schema",validate(r){let a=e.validate(r);return a.valid?{value:a.object}:{issues:(a.errors??[]).map(i=>({message:i.message}))}}},this.#u}get type(){return this.#f}set type(e){if(typeof e!="string"||!e)throw new Error("value should be non empty string");this.#f=e}get preprocessors(){return this.#e}get validators(){return this.#t}get isRequired(){return this.#d}get isNullable(){return this.#a}set isRequired(e){if(typeof e!="boolean")throw new Error("should be a boolean value");this.#d=e}get requiredErrorMessage(){return this.#o}get hasDefault(){return this.#s!==void 0}get hasCatch(){return this.#l}resolveCatchValue(){return typeof this.#i=="function"?this.#i():this.#i}get isReadonly(){return this.#y}resolveDefaultValue(){return typeof this.#s=="function"?this.#s():this.#s}get canSkipPreValidation(){return this.#T}get isNullRequiredViolation(){return!0}#P(e,r){let a=r?.doNotStopOnFirstError??!1,i={doNotStopOnFirstError:a,rootPropertyDescriptor:r?.rootPropertyDescriptor,currentPropertyDescriptor:r?.currentPropertyDescriptor},l=this.#n;return{doNotStopOnFirstError:a,resultingContext:i,transaction:l?h({validatedObject:e}):T({validatedObject:e}),errors:[]}}#r(e,r){return{valid:!1,errors:[e[0]].filter(a=>a),context:r}}#R(e,r,a){return Array.isArray(a)&&a.length?a:[{message:`Validator #${e}${r?` (${r})`:""} didn't pass.`}]}#g(e,r,a,i){return e.length>0?{valid:!1,errors:e.filter(l=>l).filter((l,c)=>r?!0:c===0),context:a,transaction:i}:{valid:!0,context:a,transaction:i}}preValidateSync(e,r){let a=this.#P(e,r),{doNotStopOnFirstError:i,resultingContext:l,errors:c}=a,p=a.transaction,n=p.object.validatedObject;if(this.#e.length>0){let s=0;for(let t of this.#e)try{let o=t.fn(n);if(o instanceof Promise)throw new Error(`Preprocessor #${s}${t.fn.name?` (${t.fn.name})`:""} returned a Promise. Use validateAsync() for schemas with async preprocessors.`);n=o}catch(o){if(o.message?.includes("Use validateAsync()"))throw o;if(c.push({message:`Preprocessor #${s}${t.fn.name?` (${t.fn.name})`:""} thrown an error: ${o.message}`}),!i)return this.#r(c,l)}finally{s++}p=this.#n?h({validatedObject:n}):T({validatedObject:n})}if(typeof n>"u"&&this.hasDefault&&(n=this.resolveDefaultValue(),p=this.#n?h({validatedObject:n}):T({validatedObject:n})),this.#t.length>0&&!(n==null&&!this.isRequired)&&!(n===null&&this.#a)){let s=0;for(let t of this.#t)try{let o=t.fn(n);if(o instanceof Promise)throw new Error(`Validator #${s}${t.fn.name?` (${t.fn.name})`:""} returned a Promise. Use validateAsync() for schemas with async validators.`);let{valid:d,errors:f}=o;if(!d&&(c.push(...this.#R(s,t.fn.name,f)),!i))return this.#r(c,l)}catch(o){if(o.message?.includes("Use validateAsync()"))throw o;if(c.push({message:`Validator #${s}${t.fn.name?` (${t.fn.name})`:""} thrown an error: ${o.message}`}),!i)return this.#r(c,l)}finally{s++}}return this.isRequired&&(typeof n>"u"||n===null&&this.isNullRequiredViolation&&!this.#a)&&(c.push({message:this.getValidationErrorMessageSync(this.#o,n)}),!i)?(p.rollback(),this.#r(c,l)):this.#g(c,i,l,p)}async preValidateAsync(e,r){let a=this.#P(e,r),{doNotStopOnFirstError:i,resultingContext:l,errors:c}=a,p=a.transaction,n=p.object.validatedObject;if(this.#e.length>0){let s=0;for(let t of this.#e)try{n=await Promise.resolve(t.fn(n))}catch(o){if(c.push({message:`Preprocessor #${s}${t.fn.name?` (${t.fn.name})`:""} thrown an error: ${o.message}`}),!i)return this.#r(c,l)}finally{s++}p=this.#n?h({validatedObject:n}):T({validatedObject:n})}if(typeof n>"u"&&this.hasDefault&&(n=this.resolveDefaultValue(),p=this.#n?h({validatedObject:n}):T({validatedObject:n})),this.#t.length>0&&!(n==null&&!this.isRequired)&&!(n===null&&this.#a)){let s=0;for(let t of this.#t)try{let{valid:o,errors:d}=await Promise.resolve(t.fn(n));if(!o&&(c.push(...this.#R(s,t.fn.name,d)),!i))return this.#r(c,l)}catch(o){if(c.push({message:`Validator #${s}${t.fn.name?` (${t.fn.name})`:""} thrown an error: ${o.message}`}),!i)return this.#r(c,l)}finally{s++}}return this.isRequired&&(typeof n>"u"||n===null&&this.isNullRequiredViolation&&!this.#a)&&(c.push({message:await this.getValidationErrorMessage(this.#o,n)}),!i)?(p.rollback(),this.#r(c,l)):this.#g(c,i,l,p)}preValidate(e,r){return this.preValidateAsync(e,r)}introspect(){return{type:this.type,isRequired:this.#d,isNullable:this.#a,isReadonly:this.#y,preprocessors:[...this.preprocessors],validators:[...this.validators],requiredValidationErrorMessageProvider:this.#o,extensions:{...this.#c},hasDefault:this.#s!==void 0,defaultValue:this.#s,description:this.#p,schemaName:this.#h,hasCatch:this.#l,catchValue:this.#i,example:this.#b}}optional(){return this.createFromProps({...this.introspect(),isRequired:!1})}nullable(){return this.createFromProps({...this.introspect(),isNullable:!0})}notNullable(){return this.createFromProps({...this.introspect(),isNullable:!1})}default(e){return this.createFromProps({...this.introspect(),defaultValue:e})}catch(e){return this.createFromProps({...this.introspect(),catchValue:e,hasCatch:!0})}clearDefault(){return this.createFromProps({...this.introspect(),defaultValue:void 0})}describe(e){return this.createFromProps({...this.introspect(),description:e})}example(e){return this.createFromProps({...this.introspect(),example:e})}schemaName(e){return this.createFromProps({...this.introspect(),schemaName:e})}brand(e){return this.createFromProps({...this.introspect()})}readonly(){return this.createFromProps({...this.introspect(),isReadonly:!0})}required(e){return this.createFromProps({...this.introspect(),isRequired:!0,...e!==void 0?{requiredValidationErrorMessageProvider:this.assureValidationErrorMessageProvider(e,this.#m)}:{}})}addPreprocessor(e,r){if(typeof e!="function")throw new Error("preprocessor must be a function");return this.createFromProps({...this.introspect(),preprocessors:[...this.preprocessors,{fn:e,mutates:r?.mutates??!0}]})}clearPreprocessors(){return this.createFromProps({...this.introspect(),preprocessors:[]})}addValidator(e,r){if(typeof e!="function")throw new Error("validator must be a function");return this.createFromProps({...this.introspect(),validators:[...this.validators,{fn:e,mutates:r?.mutates??!1}]})}clearValidators(){return this.createFromProps({...this.introspect(),validators:[]})}validate(e,r){let a=this._validate(e,r);if(!a.valid&&this.#l){let i=this.resolveCatchValue(),l=this._validate(i,r);return l.valid?l:{valid:!0,object:i}}return a}async validateAsync(e,r){let a=await this._validateAsync(e,r);if(!a.valid&&this.#l){let i=this.resolveCatchValue(),l=await this._validateAsync(i,r);return l.valid?l:{valid:!0,object:i}}return a}getValidationErrorMessageSync(e,r){if(typeof e=="string")return e;if(typeof e=="function"){let a=e(r,this);if(a instanceof Promise)throw new Error("Async error message providers require validateAsync(). Use a string or sync function instead.");return a}throw new Error("Invalid error message provider must be a string or a function returning a string")}async getValidationErrorMessage(e,r){if(typeof e=="string")return e;if(typeof e=="function")return e(r,this);throw new Error("Invalid error message provider must be a string or a function returning a string or a promise of a string")}assureValidationErrorMessageProvider(e,r){return typeof e=="string"?e:typeof e=="function"?e.bind(this):typeof r=="function"?r.bind(this):r}withExtension(e,r){return this.createFromProps({...this.introspect(),extensions:{...this.#c,[e]:r}})}getExtension(e){return this.#c[e]}parse(e,r){let a=this.validate(e,r);if(!a.valid)throw new m(a.errors||[]);return a.object}async parseAsync(e,r){let a=await this.validateAsync(e,r);if(!a.valid)throw new m(a.errors||[]);return a.object}safeParse(e,r){return this.validate(e,r)}safeParseAsync(e,r){return this.validateAsync(e,r)}constructor(e){if(!(typeof e=="object"&&e))throw new Error("SchemaBuilder props must be an object");let{type:r,preprocessors:a,validators:i,isRequired:l}=e;this.type=r,typeof l=="boolean"&&(this.isRequired=l),typeof e.isNullable=="boolean"&&(this.#a=e.isNullable),typeof e.isReadonly=="boolean"&&(this.#y=e.isReadonly),Array.isArray(a)&&(this.#e=[...a]),Array.isArray(i)&&(this.#t=[...i]),this.#n=this.#e.some(c=>c.mutates)||this.#t.some(c=>c.mutates),this.#T=this.#e.length===0&&this.#t.length===0,typeof e.extensions=="object"&&e.extensions&&(this.#c={...e.extensions}),e.defaultValue!==void 0&&(this.#s=e.defaultValue),e.hasCatch&&(this.#l=!0,this.#i=e.catchValue),typeof e.description=="string"&&(this.#p=e.description),typeof e.schemaName=="string"&&(this.#h=e.schemaName),e.example!==void 0&&(this.#b=e.example),this.#o=this.assureValidationErrorMessageProvider(e.requiredValidationErrorMessageProvider,this.#m)}};export{h as a,m as b,x as c,v as d,E as e,b as f};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
//# sourceMappingURL=chunk-G6HTNXRO.js.map
|