@oxog/vld 2.2.7 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -0
- package/README.md +113 -1
- package/dist/chunks/errors-core-BU14-Dk8.js +1 -0
- package/dist/chunks/index-CKPStM3V.js +1 -0
- package/dist/cjs/chunks/errors-core-C0mA6tfa.cjs +1 -0
- package/dist/cjs/chunks/index-lejEpLfv.cjs +1 -0
- package/dist/cjs/cli/bin.cjs +1 -1
- package/dist/cjs/codecs/index.cjs +1 -1
- package/dist/cjs/coercion/index.cjs +1 -1
- package/dist/cjs/compile.cjs +1 -0
- package/dist/cjs/errors.cjs +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/locales/gu.cjs +1 -0
- package/dist/cjs/locales/index.cjs +1 -1
- package/dist/cjs/locales/kn.cjs +1 -0
- package/dist/cjs/locales/ne.cjs +1 -0
- package/dist/cjs/locales/pt-BR-v4.cjs +1 -0
- package/dist/cjs/locales/sk.cjs +1 -0
- package/dist/cjs/mini.cjs +1 -1
- package/dist/cjs/v3/index.cjs +1 -1
- package/dist/cjs/v4/core/index.cjs +1 -1
- package/dist/cjs/v4/index.cjs +1 -1
- package/dist/cjs/v4/locales/index.cjs +1 -1
- package/dist/cjs/v4/mini/index.cjs +1 -1
- package/dist/cjs/v4-mini/index.cjs +1 -1
- package/dist/cjs/validators/any.cjs +1 -1
- package/dist/cjs/validators/array-v2.cjs +1 -0
- package/dist/cjs/validators/array.cjs +1 -1
- package/dist/cjs/validators/base.cjs +1 -1
- package/dist/cjs/validators/base64.cjs +1 -1
- package/dist/cjs/validators/bigint-v2.cjs +1 -0
- package/dist/cjs/validators/bigint.cjs +1 -1
- package/dist/cjs/validators/boolean.cjs +1 -1
- package/dist/cjs/validators/codec.cjs +1 -1
- package/dist/cjs/validators/composite-v2.cjs +1 -0
- package/dist/cjs/validators/custom.cjs +1 -1
- package/dist/cjs/validators/date-v2.cjs +1 -0
- package/dist/cjs/validators/date.cjs +1 -1
- package/dist/cjs/validators/discriminated-union.cjs +1 -1
- package/dist/cjs/validators/enum.cjs +1 -1
- package/dist/cjs/validators/file.cjs +1 -1
- package/dist/cjs/validators/function.cjs +1 -1
- package/dist/cjs/validators/hex.cjs +1 -1
- package/dist/cjs/validators/index.cjs +1 -1
- package/dist/cjs/validators/intersection.cjs +1 -1
- package/dist/cjs/validators/json.cjs +1 -1
- package/dist/cjs/validators/lazy.cjs +1 -1
- package/dist/cjs/validators/leaf-v2.cjs +1 -0
- package/dist/cjs/validators/literal.cjs +1 -1
- package/dist/cjs/validators/map.cjs +1 -1
- package/dist/cjs/validators/nan.cjs +1 -1
- package/dist/cjs/validators/never.cjs +1 -1
- package/dist/cjs/validators/null.cjs +1 -1
- package/dist/cjs/validators/number-v2.cjs +1 -0
- package/dist/cjs/validators/number.cjs +1 -1
- package/dist/cjs/validators/object-v2.cjs +1 -0
- package/dist/cjs/validators/object.cjs +1 -1
- package/dist/cjs/validators/promise.cjs +1 -1
- package/dist/cjs/validators/record.cjs +1 -1
- package/dist/cjs/validators/set.cjs +1 -1
- package/dist/cjs/validators/string-bool.cjs +1 -1
- package/dist/cjs/validators/string-formats.cjs +1 -1
- package/dist/cjs/validators/string-v2.cjs +1 -0
- package/dist/cjs/validators/string.cjs +1 -1
- package/dist/cjs/validators/symbol.cjs +1 -1
- package/dist/cjs/validators/template-literal.cjs +1 -1
- package/dist/cjs/validators/tuple.cjs +1 -1
- package/dist/cjs/validators/uint8array.cjs +1 -1
- package/dist/cjs/validators/undefined.cjs +1 -1
- package/dist/cjs/validators/union-v2.cjs +1 -0
- package/dist/cjs/validators/union.cjs +1 -1
- package/dist/cjs/validators/unknown.cjs +1 -1
- package/dist/cjs/validators/void.cjs +1 -1
- package/dist/cjs/validators/wrapper-v2.cjs +1 -0
- package/dist/cjs/validators/xor.cjs +1 -1
- package/dist/compile.d.ts +81 -0
- package/dist/compile.js +1 -0
- package/dist/errors-core.d.ts +3 -0
- package/dist/errors.js +1 -1
- package/dist/index.d.ts +484 -21
- package/dist/index.js +1 -1
- package/dist/locales/gu.d.ts +2 -0
- package/dist/locales/gu.js +1 -0
- package/dist/locales/index.js +1 -1
- package/dist/locales/kn.d.ts +2 -0
- package/dist/locales/kn.js +1 -0
- package/dist/locales/ne.d.ts +2 -0
- package/dist/locales/ne.js +1 -0
- package/dist/locales/pt-BR-v4.d.ts +2 -0
- package/dist/locales/pt-BR-v4.js +1 -0
- package/dist/locales/sk.d.ts +2 -0
- package/dist/locales/sk.js +1 -0
- package/dist/v3/index.js +1 -1
- package/dist/v4/core/index.d.ts +13 -0
- package/dist/v4/core/index.js +1 -1
- package/dist/v4/index.d.ts +1 -0
- package/dist/v4/index.js +1 -1
- package/dist/v4/locales/index.d.ts +6 -0
- package/dist/v4/locales/index.js +1 -1
- package/dist/v4/mini/index.js +1 -1
- package/dist/v4-mini/index.d.ts +2 -0
- package/dist/v4-mini/index.js +1 -1
- package/dist/validators/array-v2.d.ts +113 -0
- package/dist/validators/array-v2.js +1 -0
- package/dist/validators/array.js +1 -1
- package/dist/validators/base.js +1 -1
- package/dist/validators/base64.js +1 -1
- package/dist/validators/bigint-v2.d.ts +105 -0
- package/dist/validators/bigint-v2.js +1 -0
- package/dist/validators/bigint.js +1 -1
- package/dist/validators/boolean.js +1 -1
- package/dist/validators/codec.js +1 -1
- package/dist/validators/composite-v2.d.ts +59 -0
- package/dist/validators/composite-v2.js +1 -0
- package/dist/validators/custom.js +1 -1
- package/dist/validators/date-v2.d.ts +140 -0
- package/dist/validators/date-v2.js +1 -0
- package/dist/validators/date.js +1 -1
- package/dist/validators/enum.js +1 -1
- package/dist/validators/file.js +1 -1
- package/dist/validators/function.js +1 -1
- package/dist/validators/hex.js +1 -1
- package/dist/validators/intersection.js +1 -1
- package/dist/validators/leaf-v2.d.ts +138 -0
- package/dist/validators/leaf-v2.js +1 -0
- package/dist/validators/literal.js +1 -1
- package/dist/validators/map.js +1 -1
- package/dist/validators/nan.js +1 -1
- package/dist/validators/never.js +1 -1
- package/dist/validators/null.js +1 -1
- package/dist/validators/number-v2.d.ts +252 -0
- package/dist/validators/number-v2.js +1 -0
- package/dist/validators/number.js +1 -1
- package/dist/validators/object-v2.d.ts +40 -0
- package/dist/validators/object-v2.js +1 -0
- package/dist/validators/object.d.ts +9 -0
- package/dist/validators/object.js +1 -1
- package/dist/validators/record.js +1 -1
- package/dist/validators/set.js +1 -1
- package/dist/validators/string-formats.d.ts +1 -0
- package/dist/validators/string-formats.js +1 -1
- package/dist/validators/string-v2.d.ts +274 -0
- package/dist/validators/string-v2.js +1 -0
- package/dist/validators/string.js +1 -1
- package/dist/validators/symbol.js +1 -1
- package/dist/validators/tuple.js +1 -1
- package/dist/validators/uint8array.js +1 -1
- package/dist/validators/undefined.js +1 -1
- package/dist/validators/union-v2.d.ts +28 -0
- package/dist/validators/union-v2.js +1 -0
- package/dist/validators/void.js +1 -1
- package/dist/validators/wrapper-v2.d.ts +74 -0
- package/dist/validators/wrapper-v2.js +1 -0
- package/dist/zod-error.d.ts +84 -0
- package/package.json +7 -2
- package/dist/chunks/errors-core-CerMg2rq.js +0 -1
- package/dist/chunks/index-yjpbvFgw.js +0 -1
- package/dist/cjs/chunks/errors-core-DrydF46s.cjs +0 -1
- package/dist/cjs/chunks/index-BEV9nG0N.cjs +0 -1
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* VldNumberV2 — OPTIMIZED: check returns Issue | null, no per-call payload.
|
|
3
|
+
* Same public API as legacy VldNumber.
|
|
4
|
+
*/
|
|
5
|
+
import { VldBase, type ErrorParam, type ParseResult } from './base.js';
|
|
6
|
+
import { type VldIssue } from '../errors-core.js';
|
|
7
|
+
export declare abstract class VldNumberCheck {
|
|
8
|
+
abstract readonly kind: 'min' | 'max' | 'gt' | 'lt' | 'int' | 'finite' | 'safe' | 'multipleOf' | 'positive' | 'negative' | 'nonnegative' | 'nonpositive' | 'even' | 'odd' | 'uint32' | 'uint64' | 'int32' | 'int64' | 'float32' | 'float64';
|
|
9
|
+
abstract check(value: number): VldIssue | null;
|
|
10
|
+
abstract meta(): Record<string, any>;
|
|
11
|
+
}
|
|
12
|
+
export declare class VldNumberCheckMin extends VldNumberCheck {
|
|
13
|
+
readonly threshold: number;
|
|
14
|
+
private _msg?;
|
|
15
|
+
readonly kind: "min";
|
|
16
|
+
constructor(threshold: number, _msg?: string | undefined);
|
|
17
|
+
check(value: number): VldIssue | null;
|
|
18
|
+
meta(): {
|
|
19
|
+
kind: string;
|
|
20
|
+
value: number;
|
|
21
|
+
inclusive: boolean;
|
|
22
|
+
message: string | undefined;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export declare class VldNumberCheckMax extends VldNumberCheck {
|
|
26
|
+
readonly threshold: number;
|
|
27
|
+
private _msg?;
|
|
28
|
+
readonly kind: "max";
|
|
29
|
+
constructor(threshold: number, _msg?: string | undefined);
|
|
30
|
+
check(value: number): VldIssue | null;
|
|
31
|
+
meta(): {
|
|
32
|
+
kind: string;
|
|
33
|
+
value: number;
|
|
34
|
+
inclusive: boolean;
|
|
35
|
+
message: string | undefined;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export declare class VldNumberCheckGt extends VldNumberCheck {
|
|
39
|
+
readonly threshold: number;
|
|
40
|
+
private _msg?;
|
|
41
|
+
readonly kind: "gt";
|
|
42
|
+
constructor(threshold: number, _msg?: string | undefined);
|
|
43
|
+
check(value: number): VldIssue | null;
|
|
44
|
+
meta(): {
|
|
45
|
+
kind: string;
|
|
46
|
+
value: number;
|
|
47
|
+
inclusive: boolean;
|
|
48
|
+
message: string | undefined;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export declare class VldNumberCheckLt extends VldNumberCheck {
|
|
52
|
+
readonly threshold: number;
|
|
53
|
+
private _msg?;
|
|
54
|
+
readonly kind: "lt";
|
|
55
|
+
constructor(threshold: number, _msg?: string | undefined);
|
|
56
|
+
check(value: number): VldIssue | null;
|
|
57
|
+
meta(): {
|
|
58
|
+
kind: string;
|
|
59
|
+
value: number;
|
|
60
|
+
inclusive: boolean;
|
|
61
|
+
message: string | undefined;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export declare class VldNumberCheckInt extends VldNumberCheck {
|
|
65
|
+
private _msg?;
|
|
66
|
+
readonly kind: "int";
|
|
67
|
+
constructor(_msg?: string | undefined);
|
|
68
|
+
check(value: number): VldIssue | null;
|
|
69
|
+
meta(): {
|
|
70
|
+
kind: string;
|
|
71
|
+
message: string | undefined;
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
export declare class VldNumberCheckFinite extends VldNumberCheck {
|
|
75
|
+
private _msg?;
|
|
76
|
+
readonly kind: "finite";
|
|
77
|
+
constructor(_msg?: string | undefined);
|
|
78
|
+
check(value: number): VldIssue | null;
|
|
79
|
+
meta(): {
|
|
80
|
+
kind: string;
|
|
81
|
+
message: string | undefined;
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
export declare class VldNumberCheckSafe extends VldNumberCheck {
|
|
85
|
+
private _msg?;
|
|
86
|
+
readonly kind: "safe";
|
|
87
|
+
constructor(_msg?: string | undefined);
|
|
88
|
+
check(value: number): VldIssue | null;
|
|
89
|
+
meta(): {
|
|
90
|
+
kind: string;
|
|
91
|
+
message: string | undefined;
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
export declare class VldNumberCheckMultipleOf extends VldNumberCheck {
|
|
95
|
+
readonly divisor: number;
|
|
96
|
+
private _msg?;
|
|
97
|
+
readonly kind: "multipleOf";
|
|
98
|
+
constructor(divisor: number, _msg?: string | undefined);
|
|
99
|
+
check(value: number): VldIssue | null;
|
|
100
|
+
meta(): {
|
|
101
|
+
kind: string;
|
|
102
|
+
value: number;
|
|
103
|
+
message: string | undefined;
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
export declare class VldNumberCheckRange extends VldNumberCheck {
|
|
107
|
+
readonly min: number;
|
|
108
|
+
readonly max: number;
|
|
109
|
+
private _msg?;
|
|
110
|
+
readonly kind: "min";
|
|
111
|
+
constructor(min: number, max: number, _msg?: string | undefined);
|
|
112
|
+
check(value: number): VldIssue | null;
|
|
113
|
+
meta(): {
|
|
114
|
+
kind: string;
|
|
115
|
+
min: number;
|
|
116
|
+
max: number;
|
|
117
|
+
message: string | undefined;
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
export declare class VldNumberCheckEven extends VldNumberCheck {
|
|
121
|
+
private _msg?;
|
|
122
|
+
readonly kind: "even";
|
|
123
|
+
constructor(_msg?: string | undefined);
|
|
124
|
+
check(value: number): VldIssue | null;
|
|
125
|
+
meta(): {
|
|
126
|
+
kind: string;
|
|
127
|
+
message: string | undefined;
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
export declare class VldNumberCheckOdd extends VldNumberCheck {
|
|
131
|
+
private _msg?;
|
|
132
|
+
readonly kind: "odd";
|
|
133
|
+
constructor(_msg?: string | undefined);
|
|
134
|
+
check(value: number): VldIssue | null;
|
|
135
|
+
meta(): {
|
|
136
|
+
kind: string;
|
|
137
|
+
message: string | undefined;
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
export declare class VldNumberCheckUInt32 extends VldNumberCheck {
|
|
141
|
+
private _msg?;
|
|
142
|
+
readonly kind: "uint32";
|
|
143
|
+
constructor(_msg?: string | undefined);
|
|
144
|
+
check(value: number): VldIssue | null;
|
|
145
|
+
meta(): {
|
|
146
|
+
kind: string;
|
|
147
|
+
message: string | undefined;
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
export declare class VldNumberCheckUInt64 extends VldNumberCheck {
|
|
151
|
+
private _msg?;
|
|
152
|
+
readonly kind: "uint64";
|
|
153
|
+
constructor(_msg?: string | undefined);
|
|
154
|
+
check(value: number): VldIssue | null;
|
|
155
|
+
meta(): {
|
|
156
|
+
kind: string;
|
|
157
|
+
message: string | undefined;
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
export declare class VldNumberCheckInt32 extends VldNumberCheck {
|
|
161
|
+
private _msg?;
|
|
162
|
+
readonly kind: "int32";
|
|
163
|
+
constructor(_msg?: string | undefined);
|
|
164
|
+
check(value: number): VldIssue | null;
|
|
165
|
+
meta(): {
|
|
166
|
+
kind: string;
|
|
167
|
+
message: string | undefined;
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
export declare class VldNumberCheckInt64 extends VldNumberCheck {
|
|
171
|
+
private _msg?;
|
|
172
|
+
readonly kind: "int64";
|
|
173
|
+
constructor(_msg?: string | undefined);
|
|
174
|
+
check(value: number): VldIssue | null;
|
|
175
|
+
meta(): {
|
|
176
|
+
kind: string;
|
|
177
|
+
message: string | undefined;
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
export declare class VldNumberCheckFloat32 extends VldNumberCheck {
|
|
181
|
+
private _msg?;
|
|
182
|
+
readonly kind: "float32";
|
|
183
|
+
constructor(_msg?: string | undefined);
|
|
184
|
+
check(value: number): VldIssue | null;
|
|
185
|
+
meta(): {
|
|
186
|
+
kind: string;
|
|
187
|
+
message: string | undefined;
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
export interface VldNumberDef {
|
|
191
|
+
readonly type: 'number';
|
|
192
|
+
readonly checks: ReadonlyArray<VldNumberCheck>;
|
|
193
|
+
readonly jsonSchema?: {
|
|
194
|
+
minimum?: number;
|
|
195
|
+
maximum?: number;
|
|
196
|
+
exclusiveMinimum?: number;
|
|
197
|
+
exclusiveMaximum?: number;
|
|
198
|
+
type?: 'integer' | 'number';
|
|
199
|
+
multipleOf?: number;
|
|
200
|
+
format?: string;
|
|
201
|
+
} | undefined;
|
|
202
|
+
readonly errorMessage?: string | undefined;
|
|
203
|
+
readonly isSimple: boolean;
|
|
204
|
+
}
|
|
205
|
+
export declare class VldNumberV2 extends VldBase<number, number> {
|
|
206
|
+
readonly __def: VldNumberDef;
|
|
207
|
+
constructor(def?: VldNumberDef);
|
|
208
|
+
static create(): VldNumberV2;
|
|
209
|
+
get isSimple(): boolean;
|
|
210
|
+
get hasCustomChecks(): boolean;
|
|
211
|
+
get minValue(): number | null;
|
|
212
|
+
get maxValue(): number | null;
|
|
213
|
+
get isInt(): boolean;
|
|
214
|
+
get isFinite(): boolean;
|
|
215
|
+
get getFormat(): string | null;
|
|
216
|
+
get isCoercion(): boolean;
|
|
217
|
+
parse(value: unknown): number;
|
|
218
|
+
parseKnownNumber(value: number): number;
|
|
219
|
+
safeParse(value: unknown): ParseResult<number>;
|
|
220
|
+
protected withDef(def: Partial<VldNumberDef> & {
|
|
221
|
+
type: 'number';
|
|
222
|
+
}): VldNumberV2;
|
|
223
|
+
min(value: number, message?: ErrorParam): VldNumberV2;
|
|
224
|
+
max(value: number, message?: ErrorParam): VldNumberV2;
|
|
225
|
+
int(message?: ErrorParam): VldNumberV2;
|
|
226
|
+
positive(message?: ErrorParam): VldNumberV2;
|
|
227
|
+
negative(message?: ErrorParam): VldNumberV2;
|
|
228
|
+
nonnegative(message?: ErrorParam): VldNumberV2;
|
|
229
|
+
nonpositive(message?: ErrorParam): VldNumberV2;
|
|
230
|
+
finite(message?: ErrorParam): VldNumberV2;
|
|
231
|
+
safe(message?: ErrorParam): VldNumberV2;
|
|
232
|
+
multipleOf(value: number, message?: ErrorParam): VldNumberV2;
|
|
233
|
+
step(value: number, message?: ErrorParam): VldNumberV2;
|
|
234
|
+
between(min: number, max: number, message?: ErrorParam): VldNumberV2;
|
|
235
|
+
even(message?: ErrorParam): VldNumberV2;
|
|
236
|
+
odd(message?: ErrorParam): VldNumberV2;
|
|
237
|
+
gt(value: number, message?: ErrorParam): VldNumberV2;
|
|
238
|
+
lt(value: number, message?: ErrorParam): VldNumberV2;
|
|
239
|
+
gte(value: number, message?: ErrorParam): VldNumberV2;
|
|
240
|
+
lte(value: number, message?: ErrorParam): VldNumberV2;
|
|
241
|
+
uint32(message?: ErrorParam): VldNumberV2;
|
|
242
|
+
uint64(message?: ErrorParam): VldNumberV2;
|
|
243
|
+
int32(message?: ErrorParam): VldNumberV2;
|
|
244
|
+
int64(message?: ErrorParam): VldNumberV2;
|
|
245
|
+
float32(message?: ErrorParam): VldNumberV2;
|
|
246
|
+
float64(message?: ErrorParam): VldNumberV2;
|
|
247
|
+
}
|
|
248
|
+
export declare class VldCoerceNumberV2 extends VldNumberV2 {
|
|
249
|
+
constructor(def?: VldNumberDef);
|
|
250
|
+
static create(): VldCoerceNumberV2;
|
|
251
|
+
parse(value: unknown): number;
|
|
252
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{VLD_VALIDATOR_TYPES as e,VldBase as t,resolveErrorMessage as s}from"./base.js";import{V as r,c as i,g as n}from"../chunks/errors-core-BU14-Dk8.js";import{getMessages as m}from"../locales/runtime.js";class VldNumberCheck{}class VldNumberCheckMin extends VldNumberCheck{constructor(e,t){super(),this.threshold=e,this._msg=t,this.kind="min"}check(e){return e<this.threshold?{code:"too_small",path:[],origin:"number",minimum:this.threshold,inclusive:!0,message:this._msg||`Too small: expected number to be >=${this.threshold}`}:null}meta(){return{kind:"min",value:this.threshold,inclusive:!0,message:this._msg}}}class VldNumberCheckMax extends VldNumberCheck{constructor(e,t){super(),this.threshold=e,this._msg=t,this.kind="max"}check(e){return e>this.threshold?{code:"too_big",path:[],origin:"number",maximum:this.threshold,inclusive:!0,message:this._msg||`Too big: expected number to be <=${this.threshold}`}:null}meta(){return{kind:"max",value:this.threshold,inclusive:!0,message:this._msg}}}class VldNumberCheckGt extends VldNumberCheck{constructor(e,t){super(),this.threshold=e,this._msg=t,this.kind="gt"}check(e){return e<=this.threshold?{code:"too_small",path:[],origin:"number",minimum:this.threshold,inclusive:!1,message:this._msg||`Too small: expected number to be >${this.threshold}`}:null}meta(){return{kind:"gt",value:this.threshold,inclusive:!1,message:this._msg}}}class VldNumberCheckLt extends VldNumberCheck{constructor(e,t){super(),this.threshold=e,this._msg=t,this.kind="lt"}check(e){return e>=this.threshold?{code:"too_big",path:[],origin:"number",maximum:this.threshold,inclusive:!1,message:this._msg||`Too big: expected number to be <${this.threshold}`}:null}meta(){return{kind:"lt",value:this.threshold,inclusive:!1,message:this._msg}}}class VldNumberCheckInt extends VldNumberCheck{constructor(e){super(),this._msg=e,this.kind="int"}check(e){return Number.isInteger(e)?null:{code:"invalid_type",path:[],expected:"int",received:"number",message:this._msg||"Invalid input: expected int, received number"}}meta(){return{kind:"int",message:this._msg}}}class VldNumberCheckFinite extends VldNumberCheck{constructor(e){super(),this._msg=e,this.kind="finite"}check(e){return Number.isFinite(e)?null:{code:"custom",path:[],message:this._msg||"Number must be finite"}}meta(){return{kind:"finite",message:this._msg}}}class VldNumberCheckSafe extends VldNumberCheck{constructor(e){super(),this._msg=e,this.kind="safe"}check(e){return Number.isSafeInteger(e)?null:{code:"custom",path:[],message:this._msg||"Number must be a safe integer"}}meta(){return{kind:"safe",message:this._msg}}}class VldNumberCheckMultipleOf extends VldNumberCheck{constructor(e,t){super(),this.divisor=e,this._msg=t,this.kind="multipleOf"}check(e){const t=Math.abs(e%this.divisor);return t<Number.EPSILON||Math.abs(t-Math.abs(this.divisor))<Number.EPSILON?null:{code:"custom",path:[],message:this._msg||`Number must be a multiple of ${this.divisor}`}}meta(){return{kind:"multipleOf",value:this.divisor,message:this._msg}}}class VldNumberCheckRange extends VldNumberCheck{constructor(e,t,s){super(),this.min=e,this.max=t,this._msg=s,this.kind="min"}check(e){return e<this.min||e>this.max?{code:"custom",path:[],message:this._msg||`Number must be between ${this.min} and ${this.max}`}:null}meta(){return{kind:"range",min:this.min,max:this.max,message:this._msg}}}class VldNumberCheckEven extends VldNumberCheck{constructor(e){super(),this._msg=e,this.kind="even"}check(e){return Number.isInteger(e)&&e%2==0?null:{code:"custom",path:[],message:this._msg||"Number must be even"}}meta(){return{kind:"even",message:this._msg}}}class VldNumberCheckOdd extends VldNumberCheck{constructor(e){super(),this._msg=e,this.kind="odd"}check(e){return Number.isInteger(e)&&e%2!=0?null:{code:"custom",path:[],message:this._msg||"Number must be odd"}}meta(){return{kind:"odd",message:this._msg}}}class VldNumberCheckUInt32 extends VldNumberCheck{constructor(e){super(),this._msg=e,this.kind="uint32"}check(e){return!Number.isSafeInteger(e)||e<0||e>4294967295?{code:"custom",path:[],message:this._msg||"Expected an unsigned 32-bit integer"}:null}meta(){return{kind:"uint32",message:this._msg}}}class VldNumberCheckUInt64 extends VldNumberCheck{constructor(e){super(),this._msg=e,this.kind="uint64"}check(e){return!Number.isSafeInteger(e)||e<0?{code:"custom",path:[],message:this._msg||"Expected an unsigned 64-bit integer"}:null}meta(){return{kind:"uint64",message:this._msg}}}class VldNumberCheckInt32 extends VldNumberCheck{constructor(e){super(),this._msg=e,this.kind="int32"}check(e){return!Number.isSafeInteger(e)||e<-2147483648||e>2147483647?{code:"custom",path:[],message:this._msg||"Expected a signed 32-bit integer"}:null}meta(){return{kind:"int32",message:this._msg}}}class VldNumberCheckInt64 extends VldNumberCheck{constructor(e){super(),this._msg=e,this.kind="int64"}check(e){return Number.isSafeInteger(e)?null:{code:"custom",path:[],message:this._msg||"Expected a signed 64-bit integer"}}meta(){return{kind:"int64",message:this._msg}}}class VldNumberCheckFloat32 extends VldNumberCheck{constructor(e){super(),this._msg=e,this.kind="float32"}check(e){return!Number.isFinite(e)||Math.abs(e)>34e37?{code:"custom",path:[],message:this._msg||"Expected a 32-bit float"}:null}meta(){return{kind:"float32",message:this._msg}}}const h=Object.freeze({type:"number",checks:Object.freeze([]),isSimple:!0});class VldNumberV2 extends t{constructor(t=h){super(e.NUMBER),this.__def=t}static create(){return new VldNumberV2}get isSimple(){return this.__def.isSimple}get hasCustomChecks(){return!this.isSimple}get minValue(){const e=this.__def.jsonSchema;return e?.minimum??e?.exclusiveMinimum??null}get maxValue(){const e=this.__def.jsonSchema;return e?.maximum??e?.exclusiveMaximum??null}get isInt(){return"integer"===this.__def.jsonSchema?.type}get isFinite(){return!0}get getFormat(){return this.__def.jsonSchema?.format??null}get isCoercion(){return this.validatorType===e.COERCE_NUMBER}parse(e){if("number"!=typeof e||!Number.isFinite(e))throw new r([i("number",n(e),this.__def.errorMessage)]);return this.__def.isSimple?e:this.parseKnownNumber(e)}parseKnownNumber(e){const t=this.__def.checks;for(let s=0;s<t.length;s++){const i=t[s].check(e);if(null!==i)throw new r([i])}return e}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:e instanceof r?e:new r([{code:"custom",path:[],message:String(e)}])}}}withDef(e){const t=(s=e.checks??this.__def.checks,r=e.jsonSchema??this.__def.jsonSchema,i=e.errorMessage??this.__def.errorMessage,Object.freeze({type:"number",checks:s,jsonSchema:r,errorMessage:i,isSimple:0===s.length}));var s,r,i;return new this.constructor(t)}min(e,t){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckMin(e,s(t,m().numberMin(e)))],jsonSchema:{...this.__def.jsonSchema,minimum:e},errorMessage:s(t,m().numberMin(e))})}max(e,t){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckMax(e,s(t,m().numberMax(e)))],jsonSchema:{...this.__def.jsonSchema,maximum:e},errorMessage:s(t,m().numberMax(e))})}int(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckInt(s(e,m().numberInt))],jsonSchema:{...this.__def.jsonSchema,type:"integer"},errorMessage:s(e,m().numberInt)})}positive(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckGt(0,s(e,m().numberPositive))],jsonSchema:{...this.__def.jsonSchema,exclusiveMinimum:0},errorMessage:s(e,m().numberPositive)})}negative(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckLt(0,s(e,m().numberNegative))],jsonSchema:{...this.__def.jsonSchema,exclusiveMaximum:0},errorMessage:s(e,m().numberNegative)})}nonnegative(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckMin(0,s(e,m().numberNonnegative))],jsonSchema:{...this.__def.jsonSchema,minimum:0},errorMessage:s(e,m().numberNonnegative)})}nonpositive(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckMax(0,s(e,m().numberNonpositive))],jsonSchema:{...this.__def.jsonSchema,maximum:0},errorMessage:s(e,m().numberNonpositive)})}finite(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckFinite(s(e,m().numberFinite))],errorMessage:s(e,m().numberFinite)})}safe(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckSafe(s(e,m().numberSafe))],jsonSchema:{...this.__def.jsonSchema,type:"integer"},errorMessage:s(e,m().numberSafe)})}multipleOf(e,t){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckMultipleOf(e,s(t,m().numberMultipleOf(e)))],jsonSchema:{...this.__def.jsonSchema,multipleOf:e},errorMessage:s(t,m().numberMultipleOf(e))})}step(e,t){return this.multipleOf(e,t)}between(e,t,r){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckRange(e,t,s(r,`Number must be between ${e} and ${t}`))],jsonSchema:{...this.__def.jsonSchema,minimum:e,maximum:t},errorMessage:s(r,`Number must be between ${e} and ${t}`)})}even(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckEven(s(e,"Number must be even"))],jsonSchema:{...this.__def.jsonSchema,type:"integer",multipleOf:2},errorMessage:s(e,"Number must be even")})}odd(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckOdd(s(e,"Number must be odd"))],jsonSchema:{...this.__def.jsonSchema,type:"integer"},errorMessage:s(e,"Number must be odd")})}gt(e,t){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckGt(e,s(t,`Number must be greater than ${e}`))],jsonSchema:{...this.__def.jsonSchema,exclusiveMinimum:e},errorMessage:s(t,`Number must be greater than ${e}`)})}lt(e,t){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckLt(e,s(t,`Number must be less than ${e}`))],jsonSchema:{...this.__def.jsonSchema,exclusiveMaximum:e},errorMessage:s(t,`Number must be less than ${e}`)})}gte(e,t){return this.min(e,t)}lte(e,t){return this.max(e,t)}uint32(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckUInt32(s(e,"Expected an unsigned 32-bit integer"))],jsonSchema:{...this.__def.jsonSchema,type:"integer",minimum:0,maximum:4294967295},errorMessage:s(e,"Expected an unsigned 32-bit integer")})}uint64(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckUInt64(s(e,"Expected an unsigned 64-bit integer"))],jsonSchema:{...this.__def.jsonSchema,type:"integer",minimum:0},errorMessage:s(e,"Expected an unsigned 64-bit integer")})}int32(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckInt32(s(e,"Expected a signed 32-bit integer"))],jsonSchema:{...this.__def.jsonSchema,type:"integer",minimum:-2147483648,maximum:2147483647},errorMessage:s(e,"Expected a signed 32-bit integer")})}int64(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckInt64(s(e,"Expected a signed 64-bit integer"))],jsonSchema:{...this.__def.jsonSchema,type:"integer"},errorMessage:s(e,"Expected a signed 64-bit integer")})}float32(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckFloat32(s(e,"Expected a 32-bit float"))],jsonSchema:{...this.__def.jsonSchema,minimum:-34e37,maximum:34e37},errorMessage:s(e,"Expected a 32-bit float")})}float64(e){return this.withDef({type:"number",checks:[...this.__def.checks,new VldNumberCheckFinite(s(e,"Expected a 64-bit float"))],errorMessage:s(e,"Expected a 64-bit float")})}}const c=Object.freeze({type:"number",checks:Object.freeze([]),isSimple:!0});class VldCoerceNumberV2 extends VldNumberV2{constructor(t=c){super(t),this.validatorType=e.COERCE_NUMBER}static create(){return new VldCoerceNumberV2}parse(e){let t;if("number"==typeof e)t=e;else if("string"==typeof e&&""!==e.trim()){const s=Number(e);if(Number.isNaN(s))throw new Error(m().coercionFailed("number",e));t=s}else if("boolean"==typeof e)t=e?1:0;else if("bigint"==typeof e){const s=Number(e);if(Number.isNaN(s))throw new Error(m().coercionFailed("number",e));t=s}else{if(null!==e)throw new Error(m().coercionFailed("number",e));t=0}if(!Number.isFinite(t))throw new Error(m().coercionFailed("number",e));return super.parse(t)}}export{VldCoerceNumberV2,VldNumberCheck,VldNumberCheckEven,VldNumberCheckFinite,VldNumberCheckFloat32,VldNumberCheckGt,VldNumberCheckInt,VldNumberCheckInt32,VldNumberCheckInt64,VldNumberCheckLt,VldNumberCheckMax,VldNumberCheckMin,VldNumberCheckMultipleOf,VldNumberCheckOdd,VldNumberCheckRange,VldNumberCheckSafe,VldNumberCheckUInt32,VldNumberCheckUInt64,VldNumberV2};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as s,resolveErrorMessage as i}from"./base.js";import{getMessages as n}from"../locales/runtime.js";import{V as t,c,g as r}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as s,resolveErrorMessage as i}from"./base.js";import{getMessages as n}from"../locales/runtime.js";import{V as t,c,g as r}from"../chunks/errors-core-BU14-Dk8.js";class VldNumber extends e{constructor(e){super(e?.validatorType||s.NUMBER),this.config={checks:e?.checks||[],errorMessage:e?.errorMessage,jsonSchema:e?.jsonSchema,checkMetas:e?.checkMetas},this._checks=this.config.checks,this._isSimple=0===this._checks.length,this._fastCheckMode=this.detectFastCheckMode(),this._checkMetas=this.config.checkMetas}detectFastCheckMode(){const e=this.config.jsonSchema;return 0===this._checks.length?"none":1===this._checks.length&&0===e?.exclusiveMinimum&&"integer"!==e.type?"positive":2===this._checks.length&&0===e?.exclusiveMinimum&&"integer"===e.type?"positive-int":void 0}get hasCustomChecks(){return!this._isSimple}get isSimple(){return this._isSimple}get minValue(){return this.config.jsonSchema?.minimum??this.config.jsonSchema?.exclusiveMinimum??null}get maxValue(){return this.config.jsonSchema?.maximum??this.config.jsonSchema?.exclusiveMaximum??null}get isInt(){return"integer"===this.config.jsonSchema?.type}get isFinite(){return!0}get format(){return this.config.jsonSchema?.format??null}static create(){return new VldNumber}parse(e){if("number"!=typeof e||!Number.isFinite(e))throw new t([c("number",r(e),this.config.errorMessage)]);switch(this._fastCheckMode){case"none":return e;case"positive":if(e>0)return e;throw new t([this._createCheckIssue("gt",0,this.config.errorMessage)]);case"positive-int":if(e>0&&Number.isInteger(e))return e;throw new t([this._createCheckIssue("int",void 0,this.config.errorMessage)])}return this.parseKnownNumber(e)}_createCheckIssue(e,s,i){switch(e){case"min":return{code:"too_small",path:[],origin:"number",minimum:s,inclusive:!0,message:i||`Too small: expected number to be >=${s}`};case"max":return{code:"too_big",path:[],origin:"number",maximum:s,inclusive:!0,message:i||`Too big: expected number to be <=${s}`};case"gt":return{code:"too_small",path:[],origin:"number",minimum:s,inclusive:!1,message:i||`Too small: expected number to be >${s}`};case"lt":return{code:"too_big",path:[],origin:"number",maximum:s,inclusive:!1,message:i||`Too big: expected number to be <${s}`};case"int":return{code:"invalid_type",path:[],expected:"int",received:"number",message:i||"Invalid input: expected int, received number"};default:return{code:"custom",path:[],message:i||"Invalid number"}}}_findFailingCheck(e){const s=this._checks,i=this._checkMetas;for(let n=0;n<s.length;n++)if(!s[n](e))return i?.[n]??{kind:"other",message:this.config.errorMessage};return null}parseKnownNumber(e){switch(this._fastCheckMode){case"none":return e;case"positive":if(e>0)return e;throw new t([this._createCheckIssue("gt",0,this.config.errorMessage)]);case"positive-int":if(e>0&&Number.isInteger(e))return e;throw new t([this._createCheckIssue("int",void 0,this.config.errorMessage)])}const s=this._findFailingCheck(e);if(s)throw new t([this._createCheckIssue(s.kind,s.value,s.message)]);return e}safeParse(e){if("number"!=typeof e||!Number.isFinite(e))return{success:!1,error:new t([c("number",r(e),this.config.errorMessage)])};try{const s=this._findFailingCheck(e);if(s)return{success:!1,error:new t([this._createCheckIssue(s.kind,s.value,s.message)])}}catch(e){return e instanceof t?{success:!1,error:e}:{success:!1,error:new t([{code:"custom",path:[],message:e.message}])}}return{success:!0,data:e}}min(e,s){return new VldNumber({checks:[...this.config.checks,s=>s>=e],errorMessage:i(s,n().numberMin(e)),jsonSchema:{...this.config.jsonSchema,minimum:e},checkMetas:[...this.config.checkMetas??[],{kind:"min",value:e,inclusive:!0,message:i(s,n().numberMin(e))}]})}max(e,s){return new VldNumber({checks:[...this.config.checks,s=>s<=e],errorMessage:i(s,n().numberMax(e)),jsonSchema:{...this.config.jsonSchema,maximum:e},checkMetas:[...this.config.checkMetas??[],{kind:"max",value:e,inclusive:!0,message:i(s,n().numberMax(e))}]})}int(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isInteger(e)],errorMessage:i(e,n().numberInt),jsonSchema:{...this.config.jsonSchema,type:"integer"},checkMetas:[...this.config.checkMetas??[],{kind:"int",message:i(e,n().numberInt)}]})}positive(e){return new VldNumber({checks:[...this.config.checks,e=>e>0],errorMessage:i(e,n().numberPositive),jsonSchema:{...this.config.jsonSchema,exclusiveMinimum:0},checkMetas:[...this.config.checkMetas??[],{kind:"gt",value:0,inclusive:!1,message:i(e,n().numberPositive)}]})}negative(e){return new VldNumber({checks:[...this.config.checks,e=>e<0],errorMessage:i(e,n().numberNegative),jsonSchema:{...this.config.jsonSchema,exclusiveMaximum:0},checkMetas:[...this.config.checkMetas??[],{kind:"lt",value:0,inclusive:!1,message:i(e,n().numberNegative)}]})}nonnegative(e){return new VldNumber({checks:[...this.config.checks,e=>e>=0],errorMessage:i(e,n().numberNonnegative),jsonSchema:{...this.config.jsonSchema,minimum:0},checkMetas:[...this.config.checkMetas??[],{kind:"min",value:0,inclusive:!0,message:i(e,n().numberNonnegative)}]})}nonpositive(e){return new VldNumber({checks:[...this.config.checks,e=>e<=0],errorMessage:i(e,n().numberNonpositive),jsonSchema:{...this.config.jsonSchema,maximum:0},checkMetas:[...this.config.checkMetas??[],{kind:"max",value:0,inclusive:!0,message:i(e,n().numberNonpositive)}]})}finite(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isFinite(e)],errorMessage:i(e,n().numberFinite),jsonSchema:this.config.jsonSchema})}safe(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isSafeInteger(e)],errorMessage:i(e,n().numberSafe),jsonSchema:{...this.config.jsonSchema,type:"integer"}})}multipleOf(e,s){return new VldNumber({checks:[...this.config.checks,s=>{const i=Math.abs(s%e);return i<Number.EPSILON||Math.abs(i-Math.abs(e))<Number.EPSILON}],errorMessage:i(s,n().numberMultipleOf(e)),jsonSchema:{...this.config.jsonSchema,multipleOf:e}})}step(e,s){return this.multipleOf(e,s)}between(e,s,n){return new VldNumber({checks:[...this.config.checks,i=>i>=e&&i<=s],errorMessage:i(n,`Number must be between ${e} and ${s}`),jsonSchema:{...this.config.jsonSchema,minimum:e,maximum:s}})}even(e){return new VldNumber({checks:[...this.config.checks,e=>!!Number.isInteger(e)&&e%2==0],errorMessage:i(e,"Number must be even"),jsonSchema:{...this.config.jsonSchema,type:"integer",multipleOf:2}})}odd(e){return new VldNumber({checks:[...this.config.checks,e=>!!Number.isInteger(e)&&e%2!=0],errorMessage:i(e,"Number must be odd"),jsonSchema:{...this.config.jsonSchema,type:"integer"}})}gt(e,s){return new VldNumber({checks:[...this.config.checks,s=>s>e],errorMessage:i(s,`Number must be greater than ${e}`),jsonSchema:{...this.config.jsonSchema,exclusiveMinimum:e},checkMetas:[...this.config.checkMetas??[],{kind:"gt",value:e,inclusive:!1,message:i(s,`Number must be greater than ${e}`)}]})}lt(e,s){return new VldNumber({checks:[...this.config.checks,s=>s<e],errorMessage:i(s,`Number must be less than ${e}`),jsonSchema:{...this.config.jsonSchema,exclusiveMaximum:e},checkMetas:[...this.config.checkMetas??[],{kind:"lt",value:e,inclusive:!1,message:i(s,`Number must be less than ${e}`)}]})}gte(e,s){return this.min(e,s)}lte(e,s){return this.max(e,s)}uint32(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isSafeInteger(e)&&e>=0&&e<=4294967295],errorMessage:i(e,"Expected an unsigned 32-bit integer"),jsonSchema:{...this.config.jsonSchema,type:"integer",minimum:0,maximum:4294967295}})}uint64(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isSafeInteger(e)&&e>=0],errorMessage:i(e,"Expected an unsigned 64-bit integer"),jsonSchema:{...this.config.jsonSchema,type:"integer",minimum:0}})}int32(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isSafeInteger(e)&&e>=-2147483648&&e<=2147483647],errorMessage:i(e,"Expected a signed 32-bit integer"),jsonSchema:{...this.config.jsonSchema,type:"integer",minimum:-2147483648,maximum:2147483647}})}int64(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isSafeInteger(e)],errorMessage:i(e,"Expected a signed 64-bit integer"),jsonSchema:{...this.config.jsonSchema,type:"integer"}})}float32(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isFinite(e)&&Math.abs(e)<=34e37],errorMessage:i(e,"Expected a 32-bit float"),jsonSchema:{...this.config.jsonSchema,minimum:-34e37,maximum:34e37}})}float64(e){return new VldNumber({checks:[...this.config.checks,e=>Number.isFinite(e)],errorMessage:i(e,"Expected a 64-bit float"),jsonSchema:this.config.jsonSchema})}}export{VldNumber};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* VldObjectV2 — Analysis and decision document
|
|
3
|
+
*
|
|
4
|
+
* After detailed analysis of VldObject (1071 lines, 10 own properties, all
|
|
5
|
+
* precomputed internal arrays for fast-path dispatch), the V2 single-def
|
|
6
|
+
* pattern does NOT yield memory wins for composite validators. Here's why:
|
|
7
|
+
*
|
|
8
|
+
* - The V2 pattern saves memory by collapsing duplicated data
|
|
9
|
+
* (`config` + `_checks` + `_transforms` + `_isSimple` + `_checkMetas`)
|
|
10
|
+
* into a single `__def` object.
|
|
11
|
+
* - VldObject has NO duplicated data — it has 10 distinct internal arrays
|
|
12
|
+
* (shapeKeys, validators, validatorTypes, simpleFieldModes, ...), each
|
|
13
|
+
* serving a unique fast-path purpose.
|
|
14
|
+
* - A "VldObjectV2" wrapper that holds both a `__def` AND a VldObject
|
|
15
|
+
* child would have 2+10=12 own properties — WORSE than the legacy.
|
|
16
|
+
*
|
|
17
|
+
* The real Zod 4.5 9.8x win on `z.object()` came from a fundamentally
|
|
18
|
+
* different data layout: a single `def = {type, shape, ...}` object shared
|
|
19
|
+
* across all chained variants, plus bound methods. Replicating that for
|
|
20
|
+
* VldObject would require rewriting the entire fast-path dispatch logic
|
|
21
|
+
* (1071 lines) into a def-based representation — a multi-day refactor with
|
|
22
|
+
* uncertain return.
|
|
23
|
+
*
|
|
24
|
+
* Decision (Faz 4): VldObject, VldArray, VldUnion remain in their legacy
|
|
25
|
+
* form. The composite-side memory benefit from the V2 pattern is below
|
|
26
|
+
* noise. The ~38% wins we observed come from using VldStringV2/VldNumberV2
|
|
27
|
+
* as the children of VldObject — that's where the savings live.
|
|
28
|
+
*
|
|
29
|
+
* The composite itself is not refactored. Only its child primitive types
|
|
30
|
+
* get the V2 treatment.
|
|
31
|
+
*
|
|
32
|
+
* If you really need to push composites, the next step would be:
|
|
33
|
+
* 1. Move the precomputed arrays into a single shared `__def` object
|
|
34
|
+
* 2. Replace per-instance fields with getter accessors on `__def`
|
|
35
|
+
* 3. Use lazy memoization for keys that are only computed once
|
|
36
|
+
*
|
|
37
|
+
* That's a 3-5 day refactor of VldObject with ~10-20% expected win, much
|
|
38
|
+
* smaller than the 38% we got from primitive V2.
|
|
39
|
+
*/
|
|
40
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -109,6 +109,15 @@ export declare class VldObject<T extends Record<string, any>> extends VldBase<un
|
|
|
109
109
|
* Create a new validator with deep partial (nested objects also partial)
|
|
110
110
|
*/
|
|
111
111
|
deepPartial(): VldObject<any>;
|
|
112
|
+
/**
|
|
113
|
+
* Zod 4 `z.exactPartial()` counterpart - same as `partial()` but errors
|
|
114
|
+
* when an explicit `undefined` is provided for an optional field. VLD
|
|
115
|
+
* mirrors Zod's behaviour by rejecting explicit-undefined inputs through
|
|
116
|
+
* `VldExactOptional`.
|
|
117
|
+
*/
|
|
118
|
+
exactPartial(): VldObject<{
|
|
119
|
+
[K in keyof T]?: T[K];
|
|
120
|
+
}>;
|
|
112
121
|
/**
|
|
113
122
|
* Create a new validator with only specified keys
|
|
114
123
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as t,VldOptional as s}from"./base.js";import{getMessages as i}from"../locales/runtime.js";import{VldEnum as r}from"./enum.js";import{i as n}from"../chunks/security-Dy24T8N7.js";import{V as o}from"../chunks/errors-core-CerMg2rq.js";class VldObject extends e{createSafeParseError(e,t){if(e instanceof o)return void 0!==t?new o(e.issues.map(e=>({...e,path:e.path?[t,...e.path]:[t],message:e.message.startsWith("Invalid field")?e.message:i().objectField(String(t),e.message)}))):e;const s=e instanceof Error?e.message:String(e);return new o([{code:"invalid_type",path:void 0!==t?[t]:[],message:void 0===t||s.startsWith("Invalid field")?s:i().objectField(String(t),s)}])}constructor(s){super(t.OBJECT),this._config=s,this._shapeKeys=Object.keys(s.shape),this._shapeKeysSet=new Set(this._shapeKeys),this._validators=this._shapeKeys.map(e=>this.tryGetFieldValidator(e)),this._validatorTypes=this._shapeKeys.map((e,t)=>this._validators[t]?.validatorType||this.getValidatorType(e)),this._simpleFieldModes=this._validators.map((e,t)=>this.getSimpleFieldMode(e,this._validatorTypes[t])),this._simpleFieldValues=this._validators.map((e,t)=>"literal"===this._simpleFieldModes[t]?e.literal:void 0),this._canUseSimpleObjectFastPath=!s.strict&&!s.passthrough&&!s.catchall&&this._shapeKeys.length>0&&this._simpleFieldModes.every(e=>void 0!==e),this._canUseSafeParseFastPath=this._validators.every(t=>t instanceof e)&&(void 0===s.catchall||s.catchall instanceof e)}tryGetFieldValidator(e){try{const t=Object.getOwnPropertyDescriptor(this._config.shape,e);if(t?.get)return;return this.resolveFieldValidator(e)}catch{return}}resolveFieldValidator(e){try{const t=this._config.shape[e];if(!t||"function"!=typeof t.safeParse)return;return t}catch{return}}getFieldValidator(e,t){const s=(void 0===t?void 0:this._validators[t])||this.resolveFieldValidator(e);if(!s)throw new Error(`Invalid validator for field "${e}"`);return s}getValidatorType(e){try{const s=this._config.shape[e];return s?.validatorType||t.UNKNOWN}catch{return t.UNKNOWN}}getSimpleFieldMode(e,s){if(e&&!0===e.isSimple)switch(s){case t.STRING:return"string";case t.NUMBER:return"number";case t.BOOLEAN:return"boolean";case t.BIGINT:return"bigint";case t.SYMBOL:return"symbol";case t.NULL:return"null";case t.UNDEFINED:case t.VOID:return"undefinedValue";case t.LITERAL:return"literal";case t.ANY:case t.UNKNOWN:return"passthrough";default:return}}getSimpleFieldError(e,t,s){switch(e){case"string":return i().invalidString;case"number":return i().invalidNumber;case"boolean":return i().invalidBoolean;case"bigint":return i().invalidBigint;case"symbol":return i().invalidSymbol;case"null":return"Expected null, received "+typeof s;case"undefinedValue":return i().expectedUndefined;case"literal":return i().literalExpected(JSON.stringify(t),JSON.stringify(s));default:return i().invalidObject}}parseCheckedField(e,s,i){if(s===t.STRING&&"string"==typeof i){const t=e.parseKnownString;if("function"==typeof t)return t.call(e,i)}if(s===t.NUMBER&&"number"==typeof i&&!isNaN(i)){const t=e.parseKnownNumber;if("function"==typeof t)return t.call(e,i)}if(s===t.BOOLEAN&&"boolean"==typeof i){const t=e.parseKnownBoolean;if("function"==typeof t)return t.call(e,i)}if(s===t.BIGINT&&"bigint"==typeof i){const t=e.parseKnownBigInt;if("function"==typeof t)return t.call(e,i)}if(s===t.SYMBOL&&"symbol"==typeof i){const t=e.parseKnownSymbol;if("function"==typeof t)return t.call(e,i)}if(s===t.FUNCTION&&"function"==typeof i){const t=e.parseKnownFunction;if("function"==typeof t)return t.call(e,i)}if(s===t.FILE&&"object"==typeof i&&null!==i&&("size"in i&&"type"in i||"undefined"!=typeof File&&i instanceof File)){const t=e.parseKnownFile;if("function"==typeof t)return t.call(e,i)}if(s===t.DATE&&i instanceof Date){const t=e.parseKnownDate;if("function"==typeof t)return t.call(e,i)}if(s===t.OBJECT&&"object"==typeof i&&null!==i&&!Array.isArray(i)){const t=e.parseKnownObject;if("function"==typeof t)return t.call(e,i)}if(s===t.ARRAY&&Array.isArray(i)){const t=e.parseKnownArray;if("function"==typeof t)return t.call(e,i)}if(s===t.TUPLE&&Array.isArray(i)){const t=e.parseKnownTuple;if("function"==typeof t)return t.call(e,i)}if(s===t.RECORD&&"object"==typeof i&&null!==i&&!Array.isArray(i)){const t=e.parseKnownRecord;if("function"==typeof t)return t.call(e,i)}if(s===t.SET&&i instanceof Set){const t=e.parseKnownSet;if("function"==typeof t)return t.call(e,i)}if(s===t.MAP&&i instanceof Map){const t=e.parseKnownMap;if("function"==typeof t)return t.call(e,i)}return e.parse(i)}parseSimpleObjectValue(e,t,s=!1){if(2===this._shapeKeys.length&&"string"===this._simpleFieldModes[0]&&"number"===this._simpleFieldModes[1]){const t=this._shapeKeys[0],s=e[t];if("string"!=typeof s)throw new Error(i().objectField(t,i().invalidString));const r=this._shapeKeys[1],n=e[r];if("number"!=typeof n||isNaN(n))throw new Error(i().objectField(r,i().invalidNumber));const o={};return o[t]=s,o[r]=n,o}if(3===this._shapeKeys.length&&"literal"===this._simpleFieldModes[0]&&"string"===this._simpleFieldModes[1]&&"number"===this._simpleFieldModes[2]){const r=this._shapeKeys[0],n=e[r],o=this._simpleFieldValues[0];if((!s||r!==t)&&n!==o)throw new Error(i().objectField(r,this.getSimpleFieldError("literal",o,n)));const a=this._shapeKeys[1],c=e[a];if("string"!=typeof c)throw new Error(i().objectField(a,i().invalidString));const l=this._shapeKeys[2],h=e[l];if("number"!=typeof h||isNaN(h))throw new Error(i().objectField(l,i().invalidNumber));const f={};return f[r]=o,f[a]=c,f[l]=h,f}const r={};for(let n=0;n<this._shapeKeys.length;n++){const o=this._shapeKeys[n],a=e[o],c=this._simpleFieldModes[n];switch(c){case"string":if("string"!=typeof a)throw new Error(i().objectField(o,i().invalidString));r[o]=a;break;case"number":if("number"!=typeof a||isNaN(a))throw new Error(i().objectField(o,i().invalidNumber));r[o]=a;break;case"boolean":if("boolean"!=typeof a)throw new Error(i().objectField(o,i().invalidBoolean));r[o]=a;break;case"bigint":if("bigint"!=typeof a)throw new Error(i().objectField(o,i().invalidBigint));r[o]=a;break;case"symbol":if("symbol"!=typeof a)throw new Error(i().objectField(o,i().invalidSymbol));r[o]=a;break;case"null":if(null!==a)throw new Error(i().objectField(o,this.getSimpleFieldError(c,void 0,a)));r[o]=null;break;case"undefinedValue":if(void 0!==a)throw new Error(i().objectField(o,i().expectedUndefined));r[o]=void 0;break;case"literal":if(s&&o===t){r[o]=this._simpleFieldValues[n];break}if(a!==this._simpleFieldValues[n])throw new Error(i().objectField(o,this.getSimpleFieldError(c,this._simpleFieldValues[n],a)));r[o]=this._simpleFieldValues[n];break;case"passthrough":r[o]=a;break;default:throw new Error(i().objectField(o,i().invalidObject))}}return r}get config(){return this._config}get shapeKeys(){return this._shapeKeys}get shapeKeysSet(){return this._shapeKeysSet}static create(e){return new VldObject({shape:e})}parse(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this._config.errorMessage||i().invalidObject);return this.parseObjectValue(e)}parseKnownObject(e,t){return this.parseObjectValue(e,t)}parseTrustedKnownObject(e,t){return this.parseObjectValue(e,t,!0)}parseObjectValue(e,t,s=!1){if(this._canUseSimpleObjectFastPath)return this.parseSimpleObjectValue(e,t,s);const r={};let a="";try{for(let n=0;n<this._shapeKeys.length;n++){if(a=this._shapeKeys[n],s&&a===t&&"literal"===this._simpleFieldModes[n]){r[a]=this._simpleFieldValues[n];continue}const o=this._simpleFieldModes[n];if(void 0!==o){const t=e[a];switch(o){case"string":if("string"!=typeof t)throw new Error(i().invalidString);r[a]=t;continue;case"number":if("number"!=typeof t||isNaN(t))throw new Error(i().invalidNumber);r[a]=t;continue;case"boolean":if("boolean"!=typeof t)throw new Error(i().invalidBoolean);r[a]=t;continue;case"bigint":if("bigint"!=typeof t)throw new Error(i().invalidBigint);r[a]=t;continue;case"symbol":if("symbol"!=typeof t)throw new Error(i().invalidSymbol);r[a]=t;continue;case"null":if(null!==t)throw new Error(this.getSimpleFieldError(o,void 0,t));r[a]=null;continue;case"undefinedValue":if(void 0!==t)throw new Error(i().expectedUndefined);r[a]=void 0;continue;case"literal":if(t!==this._simpleFieldValues[n])throw new Error(this.getSimpleFieldError(o,this._simpleFieldValues[n],t));r[a]=this._simpleFieldValues[n];continue;case"passthrough":r[a]=t;continue}continue}const c=this.getFieldValidator(a,n);r[a]=this.parseCheckedField(c,this._validatorTypes[n],e[a])}}catch(e){if(e instanceof o)throw new o(e.issues.map(e=>({...e,path:e.path?[a,...e.path]:[a],message:i().objectField(a,e.message.startsWith("Invalid field")?e.message.replace(/^Invalid field "[^"]+": /,""):e.message)})));const t=e instanceof Error?e.message:String(e);throw new o([{code:"invalid_type",path:[a],message:t.startsWith("Invalid field")?t:i().objectField(a,t)}])}if(this._config.strict||this._config.passthrough||this._config.catchall){const t=Object.keys(e);if(this._config.strict){const e=[];for(let s=0;s<t.length;s++){const i=t[s];this._shapeKeysSet.has(i)||e.push(i)}if(e.length>0)throw new Error(i().unexpectedKeys(e))}if(this._config.passthrough)for(let s=0;s<t.length;s++){const i=t[s];this._shapeKeysSet.has(i)||n(i)||(r[i]=e[i])}if(this._config.catchall)for(let s=0;s<t.length;s++){const o=t[s];if(!this._shapeKeysSet.has(o)&&!n(o))try{r[o]=this._config.catchall.parse(e[o])}catch(e){throw new Error(i().objectField(o,e.message))}}}return r}safeParse(t){if("object"!=typeof t||null===t||Array.isArray(t))return{success:!1,error:this.createSafeParseError(this._config.errorMessage||i().invalidObject)};const s=t;if(this._canUseSimpleObjectFastPath)try{return{success:!0,data:this.parseSimpleObjectValue(s)}}catch{}if(this._canUseSafeParseFastPath)try{return{success:!0,data:this.parseObjectValue(s)}}catch{}const r={},a=[];for(let t=0;t<this._shapeKeys.length;t++){const n=this._shapeKeys[t],o=s[n],c=this._simpleFieldModes[t];if(void 0!==c){if("string"===c&&"string"==typeof o||"number"===c&&"number"==typeof o&&!isNaN(o)||"boolean"===c&&"boolean"==typeof o||"bigint"===c&&"bigint"==typeof o||"symbol"===c&&"symbol"==typeof o||"null"===c&&null===o||"undefinedValue"===c&&void 0===o||"literal"===c&&o===this._simpleFieldValues[t]||"passthrough"===c){r[n]="literal"===c?this._simpleFieldValues[t]:"null"===c?null:o;continue}a.push({code:"invalid_type",path:[n],message:i().objectField(n,this.getSimpleFieldError(c,this._simpleFieldValues[t],o))});continue}let l;try{l=this.getFieldValidator(n,t)}catch(e){const t=this.createSafeParseError(e,n);a.push(...t.issues);continue}try{if(l instanceof e)r[n]=this.parseCheckedField(l,this._validatorTypes[t],o);else{const e=l.safeParse(o);if(e.success)r[n]=e.data;else{const t=this.createSafeParseError(e.error,n);a.push(...t.issues)}}}catch(e){const t=this.createSafeParseError(e,n);a.push(...t.issues)}}if(this._config.strict||this._config.passthrough||this._config.catchall){const t=Object.keys(s);if(this._config.strict){const e=[];for(let s=0;s<t.length;s++){const i=t[s];this._shapeKeysSet.has(i)||e.push(i)}e.length>0&&a.push(...e.map(e=>({code:"unrecognized_keys",path:[e],message:i().unexpectedKeys([e])})))}if(this._config.passthrough)for(let e=0;e<t.length;e++){const i=t[e];this._shapeKeysSet.has(i)||n(i)||(r[i]=s[i])}if(this._config.catchall){const i=this._config.catchall;for(let o=0;o<t.length;o++){const c=t[o];if(!this._shapeKeysSet.has(c)&&!n(c))try{if(i instanceof e)r[c]=i.parse(s[c]);else{const e=i.safeParse(s[c]);if(e.success)r[c]=e.data;else{const t=this.createSafeParseError(e.error,c);a.push(...t.issues)}}}catch(e){const t=this.createSafeParseError(e,c);a.push(...t.issues)}}}}return a.length>0?{success:!1,error:new o(a)}:{success:!0,data:r}}encode(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this._config.errorMessage||i().invalidObject);return this.encodeObjectSync(e)}safeEncode(e){try{return{success:!0,data:this.encode(e)}}catch(e){return{success:!1,error:this.createSafeParseError(e.message)}}}async encodeAsync(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this._config.errorMessage||i().invalidObject);return this.encodeObjectAsync(e)}async safeEncodeAsync(e){try{return{success:!0,data:await this.encodeAsync(e)}}catch(e){return{success:!1,error:this.createSafeParseError(e.message)}}}encodeObjectSync(e){const t={};for(let s=0;s<this._shapeKeys.length;s++){const i=this._shapeKeys[s],r=this.getFieldValidator(i,s).encode(e[i]);(void 0!==r||Object.prototype.hasOwnProperty.call(e,i))&&(t[i]=r)}return this.encodeExtraKeysSync(e,t),t}async encodeObjectAsync(e){const t={};for(let s=0;s<this._shapeKeys.length;s++){const i=this._shapeKeys[s],r=await this.getFieldValidator(i,s).encodeAsync(e[i]);(void 0!==r||Object.prototype.hasOwnProperty.call(e,i))&&(t[i]=r)}const s=this.getEncodedExtraKeys(e);for(const i of s)n(i)||(this._config.catchall?t[i]=await this._config.catchall.encodeAsync(e[i]):this._config.passthrough&&(t[i]=e[i]));return t}getEncodedExtraKeys(e){const t=Object.keys(e).filter(e=>!this._shapeKeysSet.has(e));if(this._config.strict&&t.length>0)throw new Error(i().unexpectedKeys(t));return t}encodeExtraKeysSync(e,t){for(const s of this.getEncodedExtraKeys(e))n(s)||(this._config.catchall?t[s]=this._config.catchall.encode(e[s]):this._config.passthrough&&(t[s]=e[s]))}strict(e){return new VldObject({...this._config,strict:!0,passthrough:!1,errorMessage:e})}passthrough(){return new VldObject({...this._config,strict:!1,passthrough:!0})}loose(){return this.passthrough()}strip(){const e={...this._config,strict:!1,passthrough:!1};return delete e.catchall,new VldObject(e)}partial(){const e={};for(const t in this._config.shape)e[t]=new s(this._config.shape[t]);return new VldObject({...this._config,shape:e})}deepPartial(){const e={};for(const t in this._config.shape){const i=this._config.shape[t];e[t]=new s(i instanceof VldObject?i.deepPartial():i)}return new VldObject({...this._config,shape:e})}pick(...e){const t={};let s=[];s=1!==e.length||"object"!=typeof e[0]||null===e[0]||Array.isArray(e[0])?e.flat():Object.keys(e[0]).filter(t=>e[0][t]);for(const e of s)e in this._config.shape&&(t[e]=this._config.shape[e]);return new VldObject({...this._config,shape:t})}omit(...e){let t;t=1!==e.length||"object"!=typeof e[0]||null===e[0]||Array.isArray(e[0])?new Set(e.flat()):new Set(Object.keys(e[0]).filter(t=>e[0][t]));const s={};for(const e in this._config.shape)t.has(e)||(s[e]=this._config.shape[e]);return new VldObject({...this._config,shape:s})}extend(e){return new VldObject({...this._config,shape:{...this._config.shape,...e}})}merge(e){return new VldObject({...this._config,shape:{...this._config.shape,...e.config.shape}})}required(){const e={};for(const t in this._config.shape){const i=this._config.shape[t];if(i instanceof s){const s=i.baseValidator;if(!s||"function"!=typeof s.parse)throw new Error(`Invalid VldOptional structure for field "${t}": missing or invalid baseValidator`);e[t]=s}else e[t]=i}return new VldObject({...this._config,shape:e})}catchall(e){return new VldObject({...this._config,catchall:e,passthrough:!1})}get shape(){return this._config.shape}keyof(){const e=Object.keys(this._config.shape);if(0===e.length)throw new Error("Cannot create keyof enum from empty object");return r.create(e)}safeExtend(e){const t=new Set(Object.keys(this._config.shape)),s=Object.keys(e),r=[];for(const e of s)t.has(e)&&r.push(e);if(r.length>0)throw new Error(`safeExtend: ${i().safeExtendOverlap(r)}`);return new VldObject({...this._config,shape:{...this._config.shape,...e}})}}export{VldObject};
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as t,VldOptional as s,VldExactOptional as i}from"./base.js";import{getMessages as r}from"../locales/runtime.js";import{VldEnum as n}from"./enum.js";import{i as o}from"../chunks/security-Dy24T8N7.js";import{V as a}from"../chunks/errors-core-BU14-Dk8.js";class VldObject extends e{createSafeParseError(e,t){if(e instanceof a)return void 0!==t?new a(e.issues.map(e=>({...e,path:e.path?[t,...e.path]:[t],message:e.message.startsWith("Invalid field")?e.message:r().objectField(String(t),e.message)}))):e;const s=e instanceof Error?e.message:String(e);return new a([{code:"invalid_type",path:void 0!==t?[t]:[],message:void 0===t||s.startsWith("Invalid field")?s:r().objectField(String(t),s)}])}constructor(s){super(t.OBJECT),this._config=s,this._shapeKeys=Object.keys(s.shape),this._shapeKeysSet=new Set(this._shapeKeys),this._validators=this._shapeKeys.map(e=>this.tryGetFieldValidator(e)),this._validatorTypes=this._shapeKeys.map((e,t)=>this._validators[t]?.validatorType||this.getValidatorType(e)),this._simpleFieldModes=this._validators.map((e,t)=>this.getSimpleFieldMode(e,this._validatorTypes[t])),this._simpleFieldValues=this._validators.map((e,t)=>"literal"===this._simpleFieldModes[t]?e.literal:void 0),this._canUseSimpleObjectFastPath=!s.strict&&!s.passthrough&&!s.catchall&&this._shapeKeys.length>0&&this._simpleFieldModes.every(e=>void 0!==e),this._canUseSafeParseFastPath=this._validators.every(t=>t instanceof e)&&(void 0===s.catchall||s.catchall instanceof e)}tryGetFieldValidator(e){try{const t=Object.getOwnPropertyDescriptor(this._config.shape,e);if(t?.get)return;return this.resolveFieldValidator(e)}catch{return}}resolveFieldValidator(e){try{const t=this._config.shape[e];if(!t||"function"!=typeof t.safeParse)return;return t}catch{return}}getFieldValidator(e,t){const s=(void 0===t?void 0:this._validators[t])||this.resolveFieldValidator(e);if(!s)throw new Error(`Invalid validator for field "${e}"`);return s}getValidatorType(e){try{const s=this._config.shape[e];return s?.validatorType||t.UNKNOWN}catch{return t.UNKNOWN}}getSimpleFieldMode(e,s){if(e&&!0===e.isSimple)switch(s){case t.STRING:return"string";case t.NUMBER:return"number";case t.BOOLEAN:return"boolean";case t.BIGINT:return"bigint";case t.SYMBOL:return"symbol";case t.NULL:return"null";case t.UNDEFINED:case t.VOID:return"undefinedValue";case t.LITERAL:return"literal";case t.ANY:case t.UNKNOWN:return"passthrough";default:return}}getSimpleFieldError(e,t,s){switch(e){case"string":return r().invalidString;case"number":return r().invalidNumber;case"boolean":return r().invalidBoolean;case"bigint":return r().invalidBigint;case"symbol":return r().invalidSymbol;case"null":return"Expected null, received "+typeof s;case"undefinedValue":return r().expectedUndefined;case"literal":return r().literalExpected(JSON.stringify(t),JSON.stringify(s));default:return r().invalidObject}}parseCheckedField(e,s,i){if(s===t.STRING&&"string"==typeof i){const t=e.parseKnownString;if("function"==typeof t)return t.call(e,i)}if(s===t.NUMBER&&"number"==typeof i&&!isNaN(i)){const t=e.parseKnownNumber;if("function"==typeof t)return t.call(e,i)}if(s===t.BOOLEAN&&"boolean"==typeof i){const t=e.parseKnownBoolean;if("function"==typeof t)return t.call(e,i)}if(s===t.BIGINT&&"bigint"==typeof i){const t=e.parseKnownBigInt;if("function"==typeof t)return t.call(e,i)}if(s===t.SYMBOL&&"symbol"==typeof i){const t=e.parseKnownSymbol;if("function"==typeof t)return t.call(e,i)}if(s===t.FUNCTION&&"function"==typeof i){const t=e.parseKnownFunction;if("function"==typeof t)return t.call(e,i)}if(s===t.FILE&&"object"==typeof i&&null!==i&&("size"in i&&"type"in i||"undefined"!=typeof File&&i instanceof File)){const t=e.parseKnownFile;if("function"==typeof t)return t.call(e,i)}if(s===t.DATE&&i instanceof Date){const t=e.parseKnownDate;if("function"==typeof t)return t.call(e,i)}if(s===t.OBJECT&&"object"==typeof i&&null!==i&&!Array.isArray(i)){const t=e.parseKnownObject;if("function"==typeof t)return t.call(e,i)}if(s===t.ARRAY&&Array.isArray(i)){const t=e.parseKnownArray;if("function"==typeof t)return t.call(e,i)}if(s===t.TUPLE&&Array.isArray(i)){const t=e.parseKnownTuple;if("function"==typeof t)return t.call(e,i)}if(s===t.RECORD&&"object"==typeof i&&null!==i&&!Array.isArray(i)){const t=e.parseKnownRecord;if("function"==typeof t)return t.call(e,i)}if(s===t.SET&&i instanceof Set){const t=e.parseKnownSet;if("function"==typeof t)return t.call(e,i)}if(s===t.MAP&&i instanceof Map){const t=e.parseKnownMap;if("function"==typeof t)return t.call(e,i)}return e.parse(i)}parseSimpleObjectValue(e,t,s=!1){if(2===this._shapeKeys.length&&"string"===this._simpleFieldModes[0]&&"number"===this._simpleFieldModes[1]){const t=this._shapeKeys[0],s=e[t];if("string"!=typeof s)throw new Error(r().objectField(t,r().invalidString));const i=this._shapeKeys[1],n=e[i];if("number"!=typeof n||isNaN(n))throw new Error(r().objectField(i,r().invalidNumber));const o={};return o[t]=s,o[i]=n,o}if(3===this._shapeKeys.length&&"literal"===this._simpleFieldModes[0]&&"string"===this._simpleFieldModes[1]&&"number"===this._simpleFieldModes[2]){const i=this._shapeKeys[0],n=e[i],o=this._simpleFieldValues[0];if((!s||i!==t)&&n!==o)throw new Error(r().objectField(i,this.getSimpleFieldError("literal",o,n)));const a=this._shapeKeys[1],c=e[a];if("string"!=typeof c)throw new Error(r().objectField(a,r().invalidString));const l=this._shapeKeys[2],h=e[l];if("number"!=typeof h||isNaN(h))throw new Error(r().objectField(l,r().invalidNumber));const f={};return f[i]=o,f[a]=c,f[l]=h,f}const i={};for(let n=0;n<this._shapeKeys.length;n++){const o=this._shapeKeys[n],a=e[o],c=this._simpleFieldModes[n];switch(c){case"string":if("string"!=typeof a)throw new Error(r().objectField(o,r().invalidString));i[o]=a;break;case"number":if("number"!=typeof a||isNaN(a))throw new Error(r().objectField(o,r().invalidNumber));i[o]=a;break;case"boolean":if("boolean"!=typeof a)throw new Error(r().objectField(o,r().invalidBoolean));i[o]=a;break;case"bigint":if("bigint"!=typeof a)throw new Error(r().objectField(o,r().invalidBigint));i[o]=a;break;case"symbol":if("symbol"!=typeof a)throw new Error(r().objectField(o,r().invalidSymbol));i[o]=a;break;case"null":if(null!==a)throw new Error(r().objectField(o,this.getSimpleFieldError(c,void 0,a)));i[o]=null;break;case"undefinedValue":if(void 0!==a)throw new Error(r().objectField(o,r().expectedUndefined));i[o]=void 0;break;case"literal":if(s&&o===t){i[o]=this._simpleFieldValues[n];break}if(a!==this._simpleFieldValues[n])throw new Error(r().objectField(o,this.getSimpleFieldError(c,this._simpleFieldValues[n],a)));i[o]=this._simpleFieldValues[n];break;case"passthrough":i[o]=a;break;default:throw new Error(r().objectField(o,r().invalidObject))}}return i}get config(){return this._config}get shapeKeys(){return this._shapeKeys}get shapeKeysSet(){return this._shapeKeysSet}static create(e){return new VldObject({shape:e})}parse(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this._config.errorMessage||r().invalidObject);return this.parseObjectValue(e)}parseKnownObject(e,t){return this.parseObjectValue(e,t)}parseTrustedKnownObject(e,t){return this.parseObjectValue(e,t,!0)}parseObjectValue(e,t,s=!1){if(this._canUseSimpleObjectFastPath)return this.parseSimpleObjectValue(e,t,s);const i={};let n="";try{for(let o=0;o<this._shapeKeys.length;o++){if(n=this._shapeKeys[o],s&&n===t&&"literal"===this._simpleFieldModes[o]){i[n]=this._simpleFieldValues[o];continue}const a=this._simpleFieldModes[o];if(void 0!==a){const t=e[n];switch(a){case"string":if("string"!=typeof t)throw new Error(r().invalidString);i[n]=t;continue;case"number":if("number"!=typeof t||isNaN(t))throw new Error(r().invalidNumber);i[n]=t;continue;case"boolean":if("boolean"!=typeof t)throw new Error(r().invalidBoolean);i[n]=t;continue;case"bigint":if("bigint"!=typeof t)throw new Error(r().invalidBigint);i[n]=t;continue;case"symbol":if("symbol"!=typeof t)throw new Error(r().invalidSymbol);i[n]=t;continue;case"null":if(null!==t)throw new Error(this.getSimpleFieldError(a,void 0,t));i[n]=null;continue;case"undefinedValue":if(void 0!==t)throw new Error(r().expectedUndefined);i[n]=void 0;continue;case"literal":if(t!==this._simpleFieldValues[o])throw new Error(this.getSimpleFieldError(a,this._simpleFieldValues[o],t));i[n]=this._simpleFieldValues[o];continue;case"passthrough":i[n]=t;continue}continue}const c=this.getFieldValidator(n,o);i[n]=this.parseCheckedField(c,this._validatorTypes[o],e[n])}}catch(e){if(e instanceof a)throw new a(e.issues.map(e=>({...e,path:e.path?[n,...e.path]:[n],message:r().objectField(n,e.message.startsWith("Invalid field")?e.message.replace(/^Invalid field "[^"]+": /,""):e.message)})));const t=e instanceof Error?e.message:String(e);throw new a([{code:"invalid_type",path:[n],message:t.startsWith("Invalid field")?t:r().objectField(n,t)}])}if(this._config.strict||this._config.passthrough||this._config.catchall){const t=Object.keys(e);if(this._config.strict){const e=[];for(let s=0;s<t.length;s++){const i=t[s];this._shapeKeysSet.has(i)||e.push(i)}if(e.length>0)throw new Error(r().unexpectedKeys(e))}if(this._config.passthrough)for(let s=0;s<t.length;s++){const r=t[s];this._shapeKeysSet.has(r)||o(r)||(i[r]=e[r])}if(this._config.catchall)for(let s=0;s<t.length;s++){const n=t[s];if(!this._shapeKeysSet.has(n)&&!o(n))try{i[n]=this._config.catchall.parse(e[n])}catch(e){throw new Error(r().objectField(n,e.message))}}}return i}safeParse(t){if("object"!=typeof t||null===t||Array.isArray(t))return{success:!1,error:this.createSafeParseError(this._config.errorMessage||r().invalidObject)};const s=t;if(this._canUseSimpleObjectFastPath)try{return{success:!0,data:this.parseSimpleObjectValue(s)}}catch{}if(this._canUseSafeParseFastPath)try{return{success:!0,data:this.parseObjectValue(s)}}catch{}const i={},n=[];for(let t=0;t<this._shapeKeys.length;t++){const o=this._shapeKeys[t],a=s[o],c=this._simpleFieldModes[t];if(void 0!==c){if("string"===c&&"string"==typeof a||"number"===c&&"number"==typeof a&&!isNaN(a)||"boolean"===c&&"boolean"==typeof a||"bigint"===c&&"bigint"==typeof a||"symbol"===c&&"symbol"==typeof a||"null"===c&&null===a||"undefinedValue"===c&&void 0===a||"literal"===c&&a===this._simpleFieldValues[t]||"passthrough"===c){i[o]="literal"===c?this._simpleFieldValues[t]:"null"===c?null:a;continue}n.push({code:"invalid_type",path:[o],message:r().objectField(o,this.getSimpleFieldError(c,this._simpleFieldValues[t],a))});continue}let l;try{l=this.getFieldValidator(o,t)}catch(e){const t=this.createSafeParseError(e,o);n.push(...t.issues);continue}try{if(l instanceof e)i[o]=this.parseCheckedField(l,this._validatorTypes[t],a);else{const e=l.safeParse(a);if(e.success)i[o]=e.data;else{const t=this.createSafeParseError(e.error,o);n.push(...t.issues)}}}catch(e){const t=this.createSafeParseError(e,o);n.push(...t.issues)}}if(this._config.strict||this._config.passthrough||this._config.catchall){const t=Object.keys(s);if(this._config.strict){const e=[];for(let s=0;s<t.length;s++){const i=t[s];this._shapeKeysSet.has(i)||e.push(i)}e.length>0&&n.push(...e.map(e=>({code:"unrecognized_keys",path:[e],message:r().unexpectedKeys([e])})))}if(this._config.passthrough)for(let e=0;e<t.length;e++){const r=t[e];this._shapeKeysSet.has(r)||o(r)||(i[r]=s[r])}if(this._config.catchall){const r=this._config.catchall;for(let a=0;a<t.length;a++){const c=t[a];if(!this._shapeKeysSet.has(c)&&!o(c))try{if(r instanceof e)i[c]=r.parse(s[c]);else{const e=r.safeParse(s[c]);if(e.success)i[c]=e.data;else{const t=this.createSafeParseError(e.error,c);n.push(...t.issues)}}}catch(e){const t=this.createSafeParseError(e,c);n.push(...t.issues)}}}}return n.length>0?{success:!1,error:new a(n)}:{success:!0,data:i}}encode(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this._config.errorMessage||r().invalidObject);return this.encodeObjectSync(e)}safeEncode(e){try{return{success:!0,data:this.encode(e)}}catch(e){return{success:!1,error:this.createSafeParseError(e.message)}}}async encodeAsync(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this._config.errorMessage||r().invalidObject);return this.encodeObjectAsync(e)}async safeEncodeAsync(e){try{return{success:!0,data:await this.encodeAsync(e)}}catch(e){return{success:!1,error:this.createSafeParseError(e.message)}}}encodeObjectSync(e){const t={};for(let s=0;s<this._shapeKeys.length;s++){const i=this._shapeKeys[s],r=this.getFieldValidator(i,s).encode(e[i]);(void 0!==r||Object.prototype.hasOwnProperty.call(e,i))&&(t[i]=r)}return this.encodeExtraKeysSync(e,t),t}async encodeObjectAsync(e){const t={};for(let s=0;s<this._shapeKeys.length;s++){const i=this._shapeKeys[s],r=await this.getFieldValidator(i,s).encodeAsync(e[i]);(void 0!==r||Object.prototype.hasOwnProperty.call(e,i))&&(t[i]=r)}const s=this.getEncodedExtraKeys(e);for(const i of s)o(i)||(this._config.catchall?t[i]=await this._config.catchall.encodeAsync(e[i]):this._config.passthrough&&(t[i]=e[i]));return t}getEncodedExtraKeys(e){const t=Object.keys(e).filter(e=>!this._shapeKeysSet.has(e));if(this._config.strict&&t.length>0)throw new Error(r().unexpectedKeys(t));return t}encodeExtraKeysSync(e,t){for(const s of this.getEncodedExtraKeys(e))o(s)||(this._config.catchall?t[s]=this._config.catchall.encode(e[s]):this._config.passthrough&&(t[s]=e[s]))}strict(e){return new VldObject({...this._config,strict:!0,passthrough:!1,errorMessage:e})}passthrough(){return new VldObject({...this._config,strict:!1,passthrough:!0})}loose(){return this.passthrough()}strip(){const e={...this._config,strict:!1,passthrough:!1};return delete e.catchall,new VldObject(e)}partial(){const e={};for(const t in this._config.shape)e[t]=new s(this._config.shape[t]);return new VldObject({...this._config,shape:e})}deepPartial(){const e={};for(const t in this._config.shape){const i=this._config.shape[t];e[t]=new s(i instanceof VldObject?i.deepPartial():i)}return new VldObject({...this._config,shape:e})}exactPartial(){const e={};for(const t in this._config.shape)e[t]=new i(this._config.shape[t]);return new VldObject({...this._config,shape:e})}pick(...e){const t={};let s=[];s=1!==e.length||"object"!=typeof e[0]||null===e[0]||Array.isArray(e[0])?e.flat():Object.keys(e[0]).filter(t=>e[0][t]);for(const e of s)e in this._config.shape&&(t[e]=this._config.shape[e]);return new VldObject({...this._config,shape:t})}omit(...e){let t;t=1!==e.length||"object"!=typeof e[0]||null===e[0]||Array.isArray(e[0])?new Set(e.flat()):new Set(Object.keys(e[0]).filter(t=>e[0][t]));const s={};for(const e in this._config.shape)t.has(e)||(s[e]=this._config.shape[e]);return new VldObject({...this._config,shape:s})}extend(e){return new VldObject({...this._config,shape:{...this._config.shape,...e}})}merge(e){return new VldObject({...this._config,shape:{...this._config.shape,...e.config.shape}})}required(){const e={};for(const t in this._config.shape){const i=this._config.shape[t];if(i instanceof s){const s=i.baseValidator;if(!s||"function"!=typeof s.parse)throw new Error(`Invalid VldOptional structure for field "${t}": missing or invalid baseValidator`);e[t]=s}else e[t]=i}return new VldObject({...this._config,shape:e})}catchall(e){return new VldObject({...this._config,catchall:e,passthrough:!1})}get shape(){return this._config.shape}keyof(){const e=Object.keys(this._config.shape);if(0===e.length)throw new Error("Cannot create keyof enum from empty object");return n.create(e)}safeExtend(e){const t=new Set(Object.keys(this._config.shape)),s=Object.keys(e),i=[];for(const e of s)t.has(e)&&i.push(e);if(i.length>0)throw new Error(`safeExtend: ${r().safeExtendOverlap(i)}`);return new VldObject({...this._config,shape:{...this._config.shape,...e}})}}export{VldObject};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{getMessages as t}from"../locales/runtime.js";import{i}from"../chunks/security-Dy24T8N7.js";import{V as a}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as r}from"./base.js";import{getMessages as t}from"../locales/runtime.js";import{i}from"../chunks/security-Dy24T8N7.js";import{V as a}from"../chunks/errors-core-BU14-Dk8.js";function o(e){return new a([{code:"invalid_object",path:[],message:e}])}class VldRecord extends e{constructor(e,t,i){super(r.RECORD),this.valueValidator=e,this.keyValidator=t,this.errorMessage=i,this._simpleValueMode=this.getSimpleValueMode(e),this._simpleValue="literal"===this._simpleValueMode?e.literal:void 0}get valueSchema(){return this.valueValidator}get keySchema(){return this.keyValidator}get valueType(){return this.valueValidator}get keyType(){return this.keyValidator}static create(e,r){return new VldRecord(e,r)}getSimpleValueMode(e){if(!0===e.isSimple)switch(e.validatorType){case r.STRING:return"string";case r.NUMBER:return"number";case r.BOOLEAN:return"boolean";case r.BIGINT:return"bigint";case r.SYMBOL:return"symbol";case r.NULL:return"null";case r.UNDEFINED:case r.VOID:return"undefinedValue";case r.LITERAL:return"literal";case r.ANY:case r.UNKNOWN:return"passthrough";default:return}}getSimpleValueError(e){switch(this._simpleValueMode){case"string":return t().invalidString;case"number":return t().invalidNumber;case"boolean":return t().invalidBoolean;case"bigint":return t().invalidBigint;case"symbol":return t().invalidSymbol;case"null":return"Expected null, received "+typeof e;case"undefinedValue":return t().expectedUndefined;case"literal":return t().literalExpected(JSON.stringify(this._simpleValue),JSON.stringify(e));default:return t().invalidRecord}}parse(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(this.errorMessage||t().invalidRecord);return this.parseKnownRecord(e)}parseKnownRecord(e){if(void 0!==this.keyValidator)return this.parseKeyedRecord(e);const r={},a=Object.keys(e),o=this._simpleValueMode;for(let s=0;s<a.length;s++){const n=a[s];if(i(n))continue;const l=e[n];if(void 0!==o)switch(o){case"string":if("string"!=typeof l)throw new Error(t().objectField(n,t().invalidString));r[n]=l;continue;case"number":if("number"!=typeof l||isNaN(l))throw new Error(t().objectField(n,t().invalidNumber));r[n]=l;continue;case"boolean":if("boolean"!=typeof l)throw new Error(t().objectField(n,t().invalidBoolean));r[n]=l;continue;case"bigint":if("bigint"!=typeof l)throw new Error(t().objectField(n,t().invalidBigint));r[n]=l;continue;case"symbol":if("symbol"!=typeof l)throw new Error(t().objectField(n,t().invalidSymbol));r[n]=l;continue;case"null":if(null!==l)throw new Error(t().objectField(n,this.getSimpleValueError(l)));r[n]=null;continue;case"undefinedValue":if(void 0!==l)throw new Error(t().objectField(n,t().expectedUndefined));r[n]=void 0;continue;case"literal":if(l!==this._simpleValue)throw new Error(t().objectField(n,this.getSimpleValueError(l)));r[n]=this._simpleValue;continue;case"passthrough":r[n]=l;continue}try{r[n]=this.valueValidator.parse(l)}catch(e){throw new Error(t().objectField(n,e.message))}}return r}parseKeyedRecord(e){const r={},o=Reflect.ownKeys(e);for(const s of o){if(!Object.prototype.propertyIsEnumerable.call(e,s))continue;if("string"==typeof s&&i(s))continue;const o=this.keyValidator.safeParse(s);if(!o.success)throw new a([{code:"invalid_key",path:[String(s)],message:o.error.message}]);if("string"!=typeof o.data&&"number"!=typeof o.data&&"symbol"!=typeof o.data)throw new a([{code:"invalid_key",path:[String(s)],message:"Record key transform must return a property key"}]);if("string"!=typeof o.data||!i(o.data))try{r[o.data]=this.valueValidator.parse(e[s])}catch(e){throw new Error(t().objectField(String(s),e.message))}}return r}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return e instanceof a?{success:!1,error:e}:{success:!1,error:o(e.message)}}}partial(){const e=this.valueValidator.optional();return new VldRecord(e,this.keyValidator)}loose(){return new VldLooseRecord(this.valueValidator,this.keyValidator)}}class VldLooseRecord extends e{constructor(e,t){super(r.RECORD),this.valueValidator=e,this.keyValidator=t}get valueSchema(){return this.valueValidator}parse(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(t().invalidRecord);const r={},a=e;for(const e of Reflect.ownKeys(a)){if(!Object.prototype.propertyIsEnumerable.call(a,e))continue;if("string"==typeof e&&i(e))continue;const t=this.keyValidator?.safeParse(e);if(t&&!t.success)continue;const o=t?.data??e;if("string"!=typeof o&&"number"!=typeof o&&"symbol"!=typeof o)continue;if("string"==typeof o&&i(o))continue;const s=this.valueValidator.safeParse(a[e]);s.success&&(r[o]=s.data)}return r}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:o(e.message)}}}partial(){const e=this.valueValidator.optional();return new VldLooseRecord(e,this.keyValidator)}loose(){return this}}export{VldRecord};
|
package/dist/validators/set.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as e,VLD_VALIDATOR_TYPES as t}from"./base.js";import{getMessages as r}from"../locales/runtime.js";import{V as s}from"../chunks/errors-core-
|
|
1
|
+
import{VldBase as e,VLD_VALIDATOR_TYPES as t}from"./base.js";import{getMessages as r}from"../locales/runtime.js";import{V as s}from"../chunks/errors-core-BU14-Dk8.js";class VldSet extends e{constructor(e,r,s=[]){super(t.SET),this.itemValidator=e,this.errorMessage=r,this._checks=s,this._simpleItemMode=this.getSimpleItemMode(e),this._simpleItemValue="literal"===this._simpleItemMode?e.literal:void 0}get itemSchema(){return this.itemValidator}static create(e){return new VldSet(e)}getSimpleItemMode(e){if(!0===e.isSimple)switch(e.validatorType){case t.STRING:return"string";case t.NUMBER:return"number";case t.BOOLEAN:return"boolean";case t.BIGINT:return"bigint";case t.SYMBOL:return"symbol";case t.NULL:return"null";case t.UNDEFINED:case t.VOID:return"undefinedValue";case t.LITERAL:return"literal";case t.ANY:case t.UNKNOWN:return"passthrough";default:return}}getSimpleItemError(e){switch(this._simpleItemMode){case"string":return r().invalidString;case"number":return r().invalidNumber;case"boolean":return r().invalidBoolean;case"bigint":return r().invalidBigint;case"symbol":return r().invalidSymbol;case"null":return"Expected null, received "+typeof e;case"undefinedValue":return r().expectedUndefined;case"literal":return r().literalExpected(JSON.stringify(this._simpleItemValue),JSON.stringify(e));default:return r().invalidSet}}parse(e){if(!(e instanceof Set))throw new Error(this.errorMessage||r().invalidSet);return this.parseKnownSet(e)}parseKnownSet(e){const t=new Set,r=this._simpleItemMode;if("string"===r)for(const r of e){if("string"!=typeof r)throw new Error(this.getSimpleItemError(r));t.add(r)}else if("number"===r)for(const r of e){if("number"!=typeof r||isNaN(r))throw new Error(this.getSimpleItemError(r));t.add(r)}else if("boolean"===r)for(const r of e){if("boolean"!=typeof r)throw new Error(this.getSimpleItemError(r));t.add(r)}else if("bigint"===r)for(const r of e){if("bigint"!=typeof r)throw new Error(this.getSimpleItemError(r));t.add(r)}else if("symbol"===r)for(const r of e){if("symbol"!=typeof r)throw new Error(this.getSimpleItemError(r));t.add(r)}else if("null"===r)for(const r of e){if(null!==r)throw new Error(this.getSimpleItemError(r));t.add(null)}else if("undefinedValue"===r)for(const r of e){if(void 0!==r)throw new Error(this.getSimpleItemError(r));t.add(void 0)}else if("literal"===r)for(const r of e){if(r!==this._simpleItemValue)throw new Error(this.getSimpleItemError(r));t.add(this._simpleItemValue)}else if("passthrough"===r)for(const r of e)t.add(r);else for(const r of e)try{t.add(this.itemValidator.parse(r))}catch(e){throw new Error(e.message)}for(const e of this._checks)if(!e.fn(t))throw new Error(e.message);return t}safeParse(e){try{return{success:!0,data:this.parse(e)}}catch(e){return{success:!1,error:(t=e.message,new s([{code:"invalid_type",path:[],message:t}]))}}var t}min(e,t){return new VldSet(this.itemValidator,this.errorMessage,[...this._checks,{fn:t=>t.size>=e,message:t||`Set must contain at least ${e} elements`}])}max(e,t){return new VldSet(this.itemValidator,this.errorMessage,[...this._checks,{fn:t=>t.size<=e,message:t||`Set must contain at most ${e} elements`}])}size(e,t){return new VldSet(this.itemValidator,this.errorMessage,[...this._checks,{fn:t=>t.size===e,message:t||`Set must contain exactly ${e} elements`}])}nonempty(e){return this.min(1,e||"Set cannot be empty")}}export{VldSet};
|
|
@@ -28,6 +28,7 @@ declare function stringRegex(options?: {
|
|
|
28
28
|
declare function macRegex(delimiter?: string): RegExp;
|
|
29
29
|
type StaticRegexName = 'base64' | 'base64url' | 'bigint' | 'boolean' | 'browserEmail' | 'cidrv4' | 'cidrv6' | 'creditCard' | 'cuid' | 'cuid2' | 'date' | 'domain' | 'duration' | 'e164' | 'email' | 'extendedDuration' | 'guid' | 'hex' | 'hostname' | 'html5Email' | 'httpProtocol' | 'httpUrl' | 'idnEmail' | 'integer' | 'ipv4' | 'ipv6' | 'jwt' | 'ksuid' | 'lowercase' | 'md5' | 'md5_base64' | 'md5_base64url' | 'md5_hex' | 'nanoid' | 'null' | 'number' | 'rfc5322Email' | 'sha1' | 'sha1_base64' | 'sha1_base64url' | 'sha1_hex' | 'sha256' | 'sha256_base64' | 'sha256_base64url' | 'sha256_hex' | 'sha384' | 'sha384_base64' | 'sha384_base64url' | 'sha384_hex' | 'sha512' | 'sha512_base64' | 'sha512_base64url' | 'sha512_hex' | 'ulid' | 'undefined' | 'unicodeEmail' | 'uppercase' | 'uuid4' | 'uuid6' | 'uuid7' | 'xid';
|
|
30
30
|
export type RegexNamespace = Readonly<Record<StaticRegexName, RegExp> & {
|
|
31
|
+
nanoidOfLength: (length: number) => RegExp;
|
|
31
32
|
datetime: typeof dateTimeRegex;
|
|
32
33
|
emoji: () => RegExp;
|
|
33
34
|
mac: typeof macRegex;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{VldBase as t,VLD_VALIDATOR_TYPES as a}from"./base.js";import{getMessages as
|
|
1
|
+
import{VldBase as t,VLD_VALIDATOR_TYPES as a}from"./base.js";import{getMessages as e}from"../locales/runtime.js";import{i as r}from"../chunks/ip-validation-g5LWgy9t.js";import{V as i,c as n,g as d}from"../chunks/errors-core-BU14-Dk8.js";const o="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function s(t,a){return t.lastIndex=0,t.test(a)}function c(t,a){return new RegExp(`^[A-Za-z0-9+/]{${t}}${a}$`)}function u(t){return new RegExp(`^[A-Za-z0-9_-]{${t}}$`)}function f(t){const a="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"!=typeof t.precision?`${a}(?::[0-5]\\d(?:\\.\\d+)?)?`:-1===t.precision?a:0===t.precision?`${a}:[0-5]\\d`:`${a}:[0-5]\\d\\.\\d{${t.precision}}`}function m(t){return void 0===t?/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/:new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)}const l={cuid:/^[cC][0-9a-z]{6,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid:/^[0-9a-vA-V]{20}$/,ksuid:/^[A-Za-z0-9]{27}$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,nanoidOfLength:t=>new RegExp(`^[a-zA-Z0-9_-]{${t}}$`),duration:/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,extendedDuration:/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,guid:/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,creditCard:/^\d(?:[ -]?\d){11,18}$/,uuid:m,uuid4:m(4),uuid6:m(6),uuid7:m(7),email:/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+.-]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/,html5Email:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,rfc5322Email:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}))$/,unicodeEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,idnEmail:/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,browserEmail:/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,emoji:()=>/^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,mac:function(t=":"){const a=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^(?:[0-9A-F]{2}${a}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${a}){5}[0-9a-f]{2}$`)},cidrv4:/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6:/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url:/^[A-Za-z0-9_-]*$/,hostname:/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,domain:/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,httpProtocol:/^https?$/,e164:/^\+[1-9]\d{6,14}$/,date:new RegExp(`^${o}$`),time:function(t={}){return new RegExp(`^${f(t)}$`)},datetime:function(t={}){const a=["Z"];return t.local&&a.push(""),t.offset&&a.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)"),new RegExp(`^${o}T${f(t)}(?:${a.join("|")})$`)},string:function(t){const a=t?`[\\s\\S]{${t.minimum??0},${t.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${a}$`)},bigint:/^-?\d+n?$/,integer:/^-?\d+$/,number:/^-?\d+(?:\.\d+)?$/,boolean:/^(?:true|false)$/i,null:/^null$/i,undefined:/^undefined$/i,lowercase:/^[^A-Z]*$/,uppercase:/^[^a-z]*$/,hex:/^[0-9a-fA-F]*$/,md5_hex:/^[0-9a-fA-F]{32}$/,md5_base64:c(22,"=="),md5_base64url:u(22),sha1_hex:/^[0-9a-fA-F]{40}$/,sha1_base64:c(27,"="),sha1_base64url:u(27),sha256_hex:/^[0-9a-fA-F]{64}$/,sha256_base64:c(43,"="),sha256_base64url:u(43),sha384_hex:/^[0-9a-fA-F]{96}$/,sha384_base64:c(64,""),sha384_base64url:u(64),sha512_hex:/^[0-9a-fA-F]{128}$/,sha512_base64:c(86,"=="),sha512_base64url:u(86),jwt:/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/,httpUrl:/^https?:\/\/[^\s/$.?#].[^\s]*$/,md5:/^[a-f0-9]{32}$/i,sha1:/^[a-f0-9]{40}$/i,sha256:/^[a-f0-9]{64}$/i,sha384:/^[a-f0-9]{96}$/i,sha512:/^[a-f0-9]{128}$/i};class VldStringFormat extends t{constructor(t,e,r,i=t=>t,n){super(a.STRING_FORMAT),this._format=t,this._validator=e,this._errorMessage=r,this._normalize=i,this._patternSource=n}static create(t,a,e,r,i){return new VldStringFormat(t,a,e,r,i)}_createFormatIssue(){const t={code:"invalid_format",path:[],origin:"string",format:this._format,message:this._errorMessage||`Invalid ${this._format}`};return this._patternSource&&(t.pattern=this._patternSource),new i([t])}parse(t){if("string"!=typeof t)throw new i([n("string",d(t),e().invalidString)]);if(!this._validator(t))throw this._createFormatIssue();return this._normalize(t)}safeParse(t){return"string"!=typeof t?{success:!1,error:new i([n("string",d(t),e().invalidString)])}:this._validator(t)?{success:!0,data:this._normalize(t)}:{success:!1,error:this._createFormatIssue()}}}const $=t=>{const a=t?.pattern??l.email;return VldStringFormat.create("email",t=>s(a,t),void 0,void 0,a.source)},A=(t={})=>VldStringFormat.create("url",a=>{const e=(t=>{try{return new URL(t)}catch{return}})(a);return void 0!==e&&(!t.hostname||s(t.hostname,e.hostname))&&(!t.protocol||s(t.protocol,e.protocol.slice(0,-1)))},void 0,t.normalize?t=>new URL(t).href:void 0),F=t=>{const a=m(void 0===t?.version?void 0:Number(t.version.slice(1)));return VldStringFormat.create("uuid",t=>s(a,t))},g=()=>VldStringFormat.create("uuid",t=>s(l.uuid4,t)),h=()=>VldStringFormat.create("uuid",t=>s(l.uuid6,t)),p=()=>VldStringFormat.create("uuid",t=>s(l.uuid7,t)),S=()=>VldStringFormat.create("hostname",t=>s(l.hostname,t)),z=()=>VldStringFormat.create("emoji",t=>s(l.emoji(),t)),Z=()=>VldStringFormat.create("base64",t=>s(l.base64,t)),_=()=>VldStringFormat.create("base64url",t=>s(l.base64url,t)),V=()=>VldStringFormat.create("hex",t=>s(l.hex,t)),v=()=>VldStringFormat.create("jwt",t=>s(l.jwt,t)),x=()=>VldStringFormat.create("nanoid",t=>s(l.nanoid,t)),b=()=>VldStringFormat.create("cuid",t=>s(l.cuid,t)),w=()=>VldStringFormat.create("cuid2",t=>s(l.cuid2,t)),E=()=>VldStringFormat.create("ulid",t=>s(l.ulid,t)),R=()=>VldStringFormat.create("ipv4",t=>s(l.ipv4,t)),j=()=>VldStringFormat.create("ipv6",t=>s(l.ipv6,t)),I=t=>{const a=l.mac(t?.delimiter);return VldStringFormat.create("mac",t=>s(a,t))},M=()=>VldStringFormat.create("cidrv4",t=>s(l.cidrv4,t)),T=()=>VldStringFormat.create("cidrv6",t=>{const a=t.lastIndexOf("/");if(a<=0)return!1;const e=Number(t.slice(a+1));return Number.isInteger(e)&&e>=0&&e<=128&&r(t.slice(0,a))}),D=()=>VldStringFormat.create("e164",t=>s(l.e164,t)),O=()=>VldStringFormat.create("xid",t=>s(l.xid,t)),k=()=>VldStringFormat.create("guid",t=>s(l.guid,t)),C=()=>VldStringFormat.create("httpUrl",t=>s(l.httpUrl,t)),P=()=>VldStringFormat.create("ksuid",t=>s(l.ksuid,t)),N=t=>VldStringFormat.create("hash",a=>l[t]?.test(a)??!1,`Invalid ${t} hash`),U=/[ -]/g;function y(t){return!!l.creditCard.test(t)&&function(t){let a=0,e=!1;for(let r=t.length-1;r>=0;r--){let i=t.charCodeAt(r)-48;e&&(i*=2,i>9&&(i-=9)),a+=i,e=!e}return a%10==0}(t.replace(U,""))}const H=t=>VldStringFormat.create("credit_card",y,t?.message,void 0,l.creditCard.source),W={ZodISODate:VldStringFormat,ZodISODateTime:VldStringFormat,ZodISODuration:VldStringFormat,ZodISOTime:VldStringFormat,date:()=>VldStringFormat.create("date",t=>s(l.date,t)),time:(t={})=>{const a=l.time(t);return VldStringFormat.create("time",t=>s(a,t))},datetime:(t={})=>{const a=l.datetime(t);return VldStringFormat.create("datetime",t=>s(a,t))},dateTime:(t={local:!0})=>{const a=l.datetime(t);return VldStringFormat.create("datetime",t=>s(a,t))},duration:()=>VldStringFormat.create("duration",t=>s(l.duration,t))},L=(t,a)=>{const e=a instanceof RegExp?t=>s(a,t):a;return VldStringFormat.create(t,e)};export{VldStringFormat,Z as base64,_ as base64url,M as cidrv4,T as cidrv6,H as creditCard,b as cuid,w as cuid2,D as e164,$ as email,z as emoji,k as guid,N as hash,V as hex,S as hostname,C as httpUrl,R as ipv4,j as ipv6,y as isValidCreditCard,W as iso,v as jwt,P as ksuid,I as mac,x as nanoid,l as regexes,L as stringFormat,E as ulid,A as url,F as uuid,g as uuidv4,h as uuidv6,p as uuidv7,O as xid};
|