-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathtypes.ts
1728 lines (1601 loc) · 58.1 KB
/
types.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const keySignature = Symbol('keySignature');
export { keySignature };
function shallowClone<T extends AnyType>(value: T): T {
// create a new object with the same prototype then copy all enumerable own properties
return Object.assign(Object.create(Object.getPrototypeOf(value)), value)
}
const typeErrSym = Symbol('typeError');
const coercionTypeSymbol = Symbol('coercion');
export abstract class Type<T> {
public [typeErrSym]?: string | (() => string);
public [coercionTypeSymbol]?: boolean;
constructor() {}
abstract parse(value: unknown): T;
abstract and<K extends AnyType>(schema: K): any;
or<K extends AnyType>(schema: K): UnionType<[this, K]> {
return new UnionType([this, schema]);
}
optional(this: NullableType<any>): OptionalType<this>;
optional(this: OptionalType<any>): this;
optional(): OptionalType<this>;
optional(): any {
if (this instanceof OptionalType) {
return shallowClone(this);
}
return new OptionalType(this);
}
nullable(this: OptionalType<any>): NullableType<this>;
nullable(this: NullableType<any>): this;
nullable(): NullableType<this>;
nullable(): any {
if (this instanceof NullableType) {
return shallowClone(this);
}
return new NullableType(this);
}
try(value: unknown): T | ValidationError {
try {
return (this as any).parse.apply(this, arguments);
} catch (err: any) {
return err;
}
}
map<K>(fn: (value: T) => K): MappedType<K> {
return new MTypeClass(this, fn) as any;
}
onTypeError(msg: string | (() => string)): this {
const cpy = shallowClone(this);
cpy[typeErrSym] = msg;
return cpy;
}
protected typeError(msg: string): ValidationError {
const errMsg: string = (() => {
const typErrValue = (this as any)[typeErrSym];
if (typErrValue === undefined) {
return msg;
}
if (typeof typErrValue === 'function') {
return typErrValue();
}
return typErrValue;
})();
return new ValidationError(errMsg);
}
}
// TODO remove once we can get mapped types inferred properly or Predicate and default funcs move to abstract class Type
export type MappedType<T> = Type<T> & {
withPredicate: (fn: Predicate<T>['func'], errMsg?: ErrMsg<T>) => Type<T> & MappedType<T>;
default: (value: T | (() => T)) => Type<T> & MappedType<T>;
};
class MTypeClass<T extends AnyType, K> extends Type<K> implements WithPredicate<K>, Defaultable<K> {
private predicates: Predicate<K>[] | null = null;
private defaultValue?: K | (() => K);
constructor(protected schema: T, protected mapFn: (value: Infer<T>) => K) {
super();
this[coercionTypeSymbol] = true;
}
parse(value: unknown): K {
const ret =
value === undefined && this.defaultValue
? typeof this.defaultValue === 'function'
? (this.defaultValue as any)()
: this.defaultValue
: this.mapFn(this.schema.parse(value));
if (this.predicates) {
applyPredicates(this.predicates, ret);
}
return ret;
}
and<O extends AnyType>(other: O): never {
throw new Error('mapped types cannot be intersected');
}
withPredicate(fn: Predicate<K>['func'], errMsg?: ErrMsg<K>): MTypeClass<T, K> {
return withPredicate(this, { func: fn, errMsg });
}
default(value: K | (() => K)): MTypeClass<T, K> {
return withDefault(this, value);
}
}
function flattenCollectedErrorsTreeIntoMessages(
collectedErrors: Record<string, ValidationError | undefined>,
path: (string | number)[] = []
): string[] {
const messages: string[] = [];
for (const [key, value] of Object.entries(collectedErrors)) {
if (value === undefined) {
continue;
}
const newPath = [...path, key];
if (value.collectedErrors) {
messages.push(...flattenCollectedErrorsTreeIntoMessages(value.collectedErrors, newPath));
} else {
messages.push(`error parsing object at path: "${prettyPrintPath(newPath)}" - ${value.message}`);
}
}
return messages;
}
export class ValidationError extends Error {
name = 'MyZodError';
path?: (string | number)[];
collectedErrors?: Record<string, ValidationError | undefined>;
// @ts-ignore
constructor(
message: string,
path?: (string | number)[],
collectedErrors?: Record<string, ValidationError | undefined>
) {
if (collectedErrors !== undefined) {
message = flattenCollectedErrorsTreeIntoMessages(collectedErrors).join('\n');
}
super(message);
this.path = path;
this.collectedErrors = collectedErrors;
}
}
function typeOf(value: unknown): string {
if (value === null) {
return 'null';
}
if (Array.isArray(value)) {
return 'array';
}
return typeof value;
}
function prettyPrintPath(path: (number | string)[]): string {
return path.reduce<string>((acc, elem, idx) => {
if (typeof elem === 'number') {
acc += `[${elem}]`;
} else if (idx === 0) {
acc += elem;
} else {
acc += '.' + elem;
}
return acc;
}, '');
}
export type Eval<T> = T extends any[] | Date | unknown ? T : Flat<T>;
export type AnyType = Type<any>;
export type Infer<T> = T extends AnyType ? (T extends Type<infer K> ? K : any) : T;
const allowUnknownSymbol = Symbol('allowUnknown');
const shapekeysSymbol = Symbol('shapeKeys');
type ObjectIntersection<O1 extends ObjectType<any>, O2 extends ObjectType<any>> = O1 extends ObjectType<infer Shape1>
? O2 extends ObjectType<infer Shape2>
? ObjectType<MergeShapes<Shape1, Shape2> extends infer T extends ObjectShape ? Flat<T> : never>
: never
: never;
type ArrayIntersection<A1 extends ArrayType<any>, A2 extends ArrayType<any>> = A1 extends ArrayType<infer S1>
? A2 extends ArrayType<infer S2>
? ArrayType<IntersectionResult<S1, S2>>
: never
: never;
type TupleIntersection<T1 extends TupleType<any>, T2 extends TupleType<any>> = T1 extends TupleType<infer S1>
? T2 extends TupleType<infer S2>
? TupleType<Join<S1, S2>>
: never
: never;
export type IntersectionResult<T extends AnyType, K extends AnyType> =
//
T extends ObjectType<any>
? K extends ObjectType<any>
? ObjectIntersection<
T extends infer X extends ObjectType<any> ? X : never,
K extends infer X extends ObjectType<any> ? X : never
>
: IntersectionType<T extends infer X extends ObjectType<any> ? X : never, K>
: T extends ArrayType<any>
? K extends ArrayType<any>
? ArrayIntersection<T, K>
: IntersectionType<T, K>
: T extends TupleType<any>
? K extends TupleType<any>
? TupleIntersection<T, K>
: IntersectionType<T, K>
: T extends MTypeClass<any, any>
? never
: K extends MTypeClass<any, any>
? never
: IntersectionType<T, K>;
type ErrMsg<T> = string | ((value: T) => string);
type Predicate<T> = { func: (value: T) => boolean; errMsg?: ErrMsg<T> };
const normalizePredicates = <T>(
predicate?: Predicate<T>['func'] | Predicate<T> | Predicate<T>[]
): Predicate<T>[] | null => {
if (!predicate) {
return null;
}
if (typeof predicate === 'function') {
return [{ func: predicate }];
}
if (Array.isArray(predicate)) {
return predicate;
}
return [predicate];
};
const applyPredicates = (predicates: Predicate<any>[], value: any) => {
try {
for (const predicate of predicates) {
if (!predicate.func(value)) {
throw new ValidationError(
predicate.errMsg
? typeof predicate.errMsg === 'function'
? predicate.errMsg(value)
: predicate.errMsg
: 'failed anonymous predicate function'
);
}
}
} catch (err: any) {
if (err instanceof ValidationError) {
throw err;
}
throw new ValidationError(err.message);
}
};
const appendPredicate = <T>(
predicates: Predicate<T>[] | null | undefined,
pred: {
func: (value: T) => boolean;
errMsg?: string | ((value: T) => string);
}
): Predicate<T>[] => {
if (!predicates) {
return [pred];
}
return [...predicates, pred];
};
interface WithPredicate<T> {
withPredicate(fn: Predicate<T>['func'], errMsg?: ErrMsg<T>): any;
}
const withPredicate = (schema: any, predicate: any) => {
const cpy = shallowClone(schema);
cpy.predicates = appendPredicate(cpy.predicates, predicate);
return cpy;
};
interface Defaultable<T> {
default(value: T | (() => T)): any;
}
const withDefault = (schema: any, value: any) => {
const cpy = shallowClone(schema);
(cpy as any)[coercionTypeSymbol] = true;
cpy.defaultValue = value;
return cpy;
};
// Primitives
export type StringOptions = {
min?: number;
max?: number;
pattern?: RegExp;
valid?: string[];
predicate?: Predicate<string>['func'] | Predicate<string> | Predicate<string>[];
default?: string | (() => string);
};
export class StringType extends Type<string> implements WithPredicate<string>, Defaultable<string> {
private predicates: Predicate<string>[] | null;
private defaultValue?: string | (() => string);
constructor(opts?: StringOptions) {
super();
this.predicates = normalizePredicates(opts?.predicate);
this.defaultValue = opts?.default;
(this as any)[coercionTypeSymbol] = opts?.default !== undefined;
let self: StringType = this;
if (typeof opts?.min !== 'undefined') {
self = self.min(opts.min);
}
if (typeof opts?.max !== 'undefined') {
self = self.max(opts.max);
}
if (typeof opts?.pattern !== 'undefined') {
self = self.pattern(opts.pattern);
}
if (opts?.valid) {
self = self.valid(opts.valid);
}
return self;
}
parse(value: unknown = typeof this.defaultValue === 'function' ? this.defaultValue() : this.defaultValue): string {
if (typeof value !== 'string') {
throw this.typeError('expected type to be string but got ' + typeOf(value));
}
if (this.predicates) {
applyPredicates(this.predicates, value);
}
return value;
}
and<K extends AnyType>(schema: K): IntersectionType<this, K> {
return new IntersectionType(this, schema);
}
pattern(regexp: RegExp, errMsg?: ErrMsg<string>): StringType {
return this.withPredicate(
value => regexp.test(value),
errMsg || `expected string to match pattern ${regexp} but did not`
);
}
min(x: number, errMsg?: ErrMsg<string>): StringType {
return this.withPredicate(
(value: string) => value.length >= x,
errMsg ||
((value: string) =>
`expected string to have length greater than or equal to ${x} but had length ${value.length}`)
);
}
max(x: number, errMsg?: ErrMsg<string>): StringType {
return this.withPredicate(
(value: string) => value.length <= x,
errMsg ||
((value: string) => `expected string to have length less than or equal to ${x} but had length ${value.length}`)
);
}
valid(list: string[], errMsg?: ErrMsg<string>): StringType {
return this.withPredicate(
(value: string) => list.includes(value),
errMsg || `expected string to be one of: ${JSON.stringify(list)}`
);
}
withPredicate(fn: Predicate<string>['func'], errMsg?: ErrMsg<string>): StringType {
return withPredicate(this, { func: fn, errMsg });
}
default(value: string | (() => string)): StringType {
return withDefault(this, value);
}
}
export class BooleanType extends Type<boolean> implements Defaultable<boolean> {
constructor(private defaultValue?: boolean | (() => boolean)) {
super();
(this as any)[coercionTypeSymbol] = defaultValue !== undefined;
}
parse(value: unknown = typeof this.defaultValue === 'function' ? this.defaultValue() : this.defaultValue): boolean {
if (typeof value !== 'boolean') {
throw this.typeError('expected type to be boolean but got ' + typeOf(value));
}
return value;
}
and<K extends AnyType>(schema: K): IntersectionType<this, K> {
return new IntersectionType(this, schema);
}
default(value: boolean | (() => boolean)): BooleanType {
return withDefault(this, value);
}
}
export type NumberOptions = {
min?: number;
max?: number;
coerce?: boolean;
predicate?: Predicate<number>['func'] | Predicate<number> | Predicate<number>[];
default?: number | (() => number);
};
export class NumberType extends Type<number> implements WithPredicate<number>, Defaultable<number> {
private predicates: Predicate<number>[] | null;
private defaultValue?: number | (() => number);
private coerceFlag?: boolean;
constructor(opts: NumberOptions = {}) {
super();
this.coerceFlag = opts.coerce;
this.predicates = normalizePredicates(opts.predicate);
this.defaultValue = opts.default;
(this as any)[coercionTypeSymbol] = !!opts.coerce || opts.default !== undefined;
let self: NumberType = this;
if (typeof opts.max !== 'undefined') {
self = self.max(opts.max);
}
if (typeof opts.min !== 'undefined') {
self = self.min(opts.min);
}
return self;
}
parse(value: unknown = typeof this.defaultValue === 'function' ? this.defaultValue() : this.defaultValue): number {
if (this.coerceFlag && typeof value === 'string') {
const number = parseFloat(value);
if (isNaN(number)) {
throw this.typeError('expected type to be number but got string');
}
return this.parse(number);
}
if (typeof value !== 'number') {
throw this.typeError('expected type to be number but got ' + typeOf(value));
}
if (this.predicates) {
applyPredicates(this.predicates, value);
}
return value;
}
and<K extends AnyType>(schema: K): IntersectionType<this, K> {
return new IntersectionType(this, schema);
}
min(x: number, errMsg?: ErrMsg<number>): NumberType {
return this.withPredicate(
value => value >= x,
errMsg || (value => `expected number to be greater than or equal to ${x} but got ${value}`)
);
}
max(x: number, errMsg?: ErrMsg<number>): NumberType {
return this.withPredicate(
value => value <= x,
errMsg || (value => `expected number to be less than or equal to ${x} but got ${value}`)
);
}
coerce(value?: boolean): NumberType {
return new NumberType({
predicate: this.predicates || undefined,
coerce: value !== undefined ? value : true,
default: this.defaultValue,
});
}
withPredicate(fn: Predicate<number>['func'], errMsg?: ErrMsg<number>): NumberType {
return withPredicate(this, { func: fn, errMsg });
}
default(value: number | (() => number)): NumberType {
return withDefault(this, value);
}
}
export type BigIntOptions = {
min?: number | bigint;
max?: number | bigint;
predicate?: Predicate<bigint>['func'] | Predicate<bigint> | Predicate<bigint>[];
default?: bigint | (() => bigint);
};
export class BigIntType extends Type<bigint> implements WithPredicate<bigint>, Defaultable<bigint> {
private readonly predicates: Predicate<bigint>[] | null;
private readonly defaultValue?: bigint | (() => bigint);
constructor(opts: BigIntOptions = {}) {
super();
this[coercionTypeSymbol] = true;
this.predicates = normalizePredicates(opts.predicate);
this.defaultValue = opts.default;
}
parse(value: unknown = typeof this.defaultValue === 'function' ? this.defaultValue() : this.defaultValue): bigint {
try {
const int = BigInt(value as any);
if (this.predicates) {
applyPredicates(this.predicates, int);
}
return int;
} catch (err: any) {
if (err instanceof ValidationError) {
throw err;
}
throw this.typeError('expected type to be bigint interpretable - ' + err.message.toLowerCase());
}
}
and<K extends AnyType>(schema: K): IntersectionType<this, K> {
return new IntersectionType(this, schema);
}
min(x: number | bigint, errMsg?: ErrMsg<bigint>): BigIntType {
return this.withPredicate(
value => value >= x,
errMsg || (value => `expected bigint to be greater than or equal to ${x} but got ${value}`)
);
}
max(x: number | bigint, errMsg?: ErrMsg<bigint>): BigIntType {
return this.withPredicate(
value => value <= x,
errMsg || (value => `expected bigint to be less than or equal to ${x} but got ${value}`)
);
}
withPredicate(fn: Predicate<bigint>['func'], errMsg?: ErrMsg<bigint>): BigIntType {
return withPredicate(this, { func: fn, errMsg });
}
default(value: bigint | (() => bigint)): BigIntType {
return withDefault(this, value);
}
}
export class UndefinedType extends Type<undefined> {
parse(value: unknown): undefined {
if (value !== undefined) {
throw this.typeError('expected type to be undefined but got ' + typeOf(value));
}
return value;
}
and<K extends AnyType>(schema: K): IntersectionType<this, K> {
return new IntersectionType(this, schema);
}
}
export class NullType extends Type<null> implements Defaultable<null> {
private defaultValue: null | undefined;
constructor() {
super();
}
parse(value: unknown = this.defaultValue): null {
if (value !== null) {
throw this.typeError('expected type to be null but got ' + typeOf(value));
}
return value;
}
and<K extends AnyType>(schema: K): IntersectionType<this, K> {
return new IntersectionType(this, schema);
}
default(): NullType {
return withDefault(this, null);
}
}
export type Literal = string | number | boolean | undefined | null;
export class LiteralType<T extends Literal> extends Type<T> implements Defaultable<T> {
private readonly defaultValue?: T;
constructor(private readonly literal: T) {
super();
}
parse(value: unknown = this.defaultValue): T {
if (value !== this.literal) {
const typeofValue = typeof value !== 'object' ? JSON.stringify(value) : typeOf(value);
throw this.typeError(`expected value to be literal ${JSON.stringify(this.literal)} but got ${typeofValue}`);
}
return value as T;
}
and<K extends AnyType>(schema: K): IntersectionType<this, K> {
return new IntersectionType(this, schema);
}
default(): LiteralType<T> {
return withDefault(this, this.literal);
}
}
export class UnknownType extends Type<unknown> implements Defaultable<unknown> {
private readonly defaultValue?: any;
constructor() {
super();
}
parse(value: unknown = typeof this.defaultValue === 'function' ? this.defaultValue() : this.defaultValue): unknown {
return value;
}
and<K extends AnyType>(schema: K): IntersectionType<this, K> {
return new IntersectionType(this, schema);
}
default(value: any | (() => any)) {
return withDefault(this, value);
}
}
export class OptionalType<T extends AnyType> extends Type<Infer<T> | undefined> {
constructor(readonly schema: T) {
super();
this[coercionTypeSymbol] = (this.schema as any)[coercionTypeSymbol];
(this as any)[shapekeysSymbol] = (this.schema as any)[shapekeysSymbol];
(this as any)[allowUnknownSymbol] = (this.schema as any)[allowUnknownSymbol];
}
parse(value: unknown, opts?: any): Infer<T> | undefined {
if (value === undefined) {
return undefined;
}
//@ts-ignore
return this.schema.parse(value, opts);
}
required(): T {
return shallowClone(this.schema);
}
and<K extends AnyType>(schema: K): IntersectionType<this, K> {
return new IntersectionType(this, schema);
}
}
type Nullable<T> = T | null;
export class NullableType<T extends AnyType> extends Type<Infer<T> | null> implements Defaultable<Infer<T> | null> {
private readonly defaultValue?: Nullable<Infer<T>> | (() => Nullable<Infer<T>>);
constructor(readonly schema: T) {
super();
(this as any)[coercionTypeSymbol] = (this.schema as any)[coercionTypeSymbol];
(this as any)[shapekeysSymbol] = (this.schema as any)[shapekeysSymbol];
(this as any)[allowUnknownSymbol] = (this.schema as any)[allowUnknownSymbol];
}
parse(
//@ts-ignore
value: unknown = typeof this.defaultValue === 'function' ? this.defaultValue() : this.defaultValue
): Infer<T> | null {
if (value === null) {
return null;
}
return this.schema.parse(value);
}
and<K extends AnyType>(schema: K): IntersectionType<this, K> {
return new IntersectionType(this, schema);
}
required(): T {
return shallowClone(this.schema);
}
default(value: Nullable<Infer<T>> | (() => Nullable<Infer<T>>)) {
return withDefault(this, value);
}
}
// Non Primitive types
export type DateOptions = {
predicate?: Predicate<Date>['func'] | Predicate<Date> | Predicate<Date>[];
default?: Date | (() => Date);
};
export class DateType extends Type<Date> implements WithPredicate<Date>, Defaultable<Date> {
private readonly predicates: Predicate<Date>[] | null;
private readonly defaultValue?: Date | (() => Date);
constructor(opts?: DateOptions) {
super();
(this as any)[coercionTypeSymbol] = true;
this.predicates = normalizePredicates(opts?.predicate);
this.defaultValue = opts?.default;
}
parse(value: unknown = typeof this.defaultValue === 'function' ? this.defaultValue() : this.defaultValue): Date {
const date = typeof value === 'string' ? this.stringToDate(value) : this.assertDate(value);
if (this.predicates) {
applyPredicates(this.predicates, date);
}
return date;
}
and<K extends AnyType>(schema: K): IntersectionType<this, K> {
return new IntersectionType(this, schema);
}
withPredicate(fn: Predicate<Date>['func'], errMsg?: ErrMsg<Date>): DateType {
return withPredicate(this, { func: fn, errMsg });
}
default(value: Date | (() => Date)): DateType {
return withDefault(this, value);
}
private stringToDate(str: string): Date {
const date = new Date(str);
if (isNaN(date.getTime())) {
throw this.typeError(`expected date string to be valid date`);
}
return date;
}
private assertDate(date: any): Date {
if (!(date instanceof Date)) {
throw this.typeError('expected type Date but got ' + typeOf(date));
}
return date;
}
}
export type ObjectShape = { [key: string]: AnyType; [keySignature]?: AnyType };
type OptionalKeys<T extends ObjectShape> = {
[key in keyof T]: undefined extends Infer<T[key]> ? (key extends symbol ? never : key) : never;
}[keyof T];
type RequiredKeys<T extends ObjectShape> = Exclude<string & keyof T, OptionalKeys<T>>;
type InferKeySignature<T extends ObjectShape> = T extends { [keySignature]: AnyType }
? T extends { [keySignature]: infer KeySig }
? KeySig extends AnyType
? { [key: string]: Infer<KeySig> }
: {}
: {}
: {};
type Flat<T> = T extends {} ? (T extends Date ? T : { [key in keyof T]: T[key] }) : T;
type InferObjectShape<T extends ObjectShape> = Flat<
Eval<
InferKeySignature<T> & { [key in OptionalKeys<T>]?: T[key] extends Type<infer K> ? K : any } & {
[key in RequiredKeys<T>]: T[key] extends Type<infer K> ? K : any;
}
>
>;
export type ToUnion<T extends any[]> = T[number];
export type PartialShape<T extends ObjectShape> = {
[key in keyof T]: T[key] extends OptionalType<any> ? T[key] : OptionalType<T[key]>;
};
export type DeepPartialShape<T extends ObjectShape> = {
[key in keyof T]: T[key] extends ObjectType<infer K>
? OptionalType<ObjectType<DeepPartialShape<K>>>
: T[key] extends OptionalType<any>
? T[key]
: OptionalType<T[key]>;
};
type MergeShapes<T extends ObjectShape, K extends ObjectShape> = {
[key in keyof (T & K)]: key extends keyof T
? key extends keyof K
? IntersectionResult<T[key], K[key]>
: T[key]
: key extends keyof K
? K[key]
: never;
};
export type StringTypes<T> = T extends string ? T : never;
export type PathOptions = { suppressPathErrMsg?: boolean };
export type ObjectOptions<T extends ObjectShape> = {
allowUnknown?: boolean;
predicate?:
| Predicate<InferObjectShape<T>>['func']
| Predicate<InferObjectShape<T>>
| Predicate<InferObjectShape<T>>[];
default?: InferObjectShape<T> | (() => InferObjectShape<T>);
collectErrors?: boolean;
};
export class ObjectType<T extends ObjectShape>
extends Type<InferObjectShape<T>>
implements WithPredicate<InferObjectShape<T>>, Defaultable<InferObjectShape<T>>
{
private readonly predicates: Predicate<InferObjectShape<T>>[] | null;
private readonly defaultValue?: InferObjectShape<T> | (() => InferObjectShape<T>);
public [allowUnknownSymbol]: boolean;
public [shapekeysSymbol]: string[];
public [coercionTypeSymbol]: boolean;
public [keySignature]: AnyType | undefined;
private shouldCollectErrors: boolean;
private _parse: (value: any, parseOpts: ObjectOptions<any> & PathOptions) => InferObjectShape<T>;
constructor(private readonly objectShape: T, opts?: ObjectOptions<T>) {
super();
this.predicates = normalizePredicates(opts?.predicate);
this.defaultValue = opts?.default;
this.shouldCollectErrors = opts?.collectErrors === true;
const keys = Object.keys(this.objectShape);
this[keySignature] = this.objectShape[keySignature];
this[allowUnknownSymbol] = opts?.allowUnknown === true;
this[shapekeysSymbol] = keys;
this[coercionTypeSymbol] =
this.defaultValue !== undefined ||
this[allowUnknownSymbol] ||
Object.values(this.objectShape).some(schema => (schema as any)[coercionTypeSymbol]) ||
!!(this.objectShape[keySignature] && (this.objectShape[keySignature] as any)[coercionTypeSymbol]);
this._parse = this.selectParser();
}
parse(
value: unknown = typeof this.defaultValue === 'function' ? this.defaultValue() : this.defaultValue,
parseOpts: ObjectOptions<any> & PathOptions = {}
): InferObjectShape<T> {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw this.typeError('expected type to be object but got ' + typeOf(value));
}
const keys: string[] = this[shapekeysSymbol];
const allowUnknown = parseOpts.allowUnknown || this[allowUnknownSymbol];
if (!allowUnknown && !this.objectShape[keySignature]) {
const illegalKeys: string[] = [];
for (const k in value) {
if (!keys.includes(k)) {
illegalKeys.push(k);
}
}
if (illegalKeys.length > 0) {
throw this.typeError('unexpected keys on object: ' + JSON.stringify(illegalKeys));
}
}
return this._parse(value, parseOpts);
}
private buildPathError(err: ValidationError, key: string, parseOpts: PathOptions): ValidationError {
const path = err.path ? [key, ...err.path] : [key];
const msg = parseOpts.suppressPathErrMsg
? err.message
: `error parsing object at path: "${prettyPrintPath(path)}" - ${err.message}`;
return new ValidationError(msg, path, err.collectedErrors);
}
private selectParser(): (value: any, parseOpts: ObjectOptions<any> & PathOptions) => InferObjectShape<T> {
if (this[shapekeysSymbol].length === 0 && this[keySignature]) {
if (this[coercionTypeSymbol] && this.shouldCollectErrors) {
return this.parseRecordConvCollect;
}
if (this[coercionTypeSymbol]) {
return this.parseRecordConv;
}
if (this.shouldCollectErrors) {
return this.parseRecordCollect;
}
return this.parseRecord;
}
if (this[keySignature]) {
if (this[coercionTypeSymbol] && this.shouldCollectErrors) {
return this.parseMixRecordConvCollect;
}
if (this[coercionTypeSymbol]) {
return this.parseMixRecordConv;
}
if (this.shouldCollectErrors) {
return this.parseMixRecordCollect;
}
return this.parseMixRecord;
}
if (this[coercionTypeSymbol] && this.shouldCollectErrors) {
return this.parseObjectConvCollect;
}
if (this[coercionTypeSymbol]) {
return this.parseObjectConv;
}
if (this.shouldCollectErrors) {
return this.parseObjectCollect;
}
return this.parseObject;
}
private parseObject(value: Object, parseOpts: ObjectOptions<any> & PathOptions): InferObjectShape<T> {
for (const key of this[shapekeysSymbol]) {
try {
const schema = (this.objectShape as any)[key];
if (schema instanceof UnknownType && !(value as any).hasOwnProperty(key)) {
throw (schema as any).typeError(`expected key "${key}" of unknown type to be present on object`);
}
schema.parse((value as any)[key], { suppressPathErrMsg: true });
} catch (err: any) {
throw this.buildPathError(err, key, parseOpts);
}
}
if (this.predicates) {
applyPredicates(this.predicates, value);
}
return value as any;
}
private parseObjectCollect(value: Object, parseOpts: ObjectOptions<any> & PathOptions): InferObjectShape<T> {
let hasError = false;
const errs: Record<string, ValidationError> = {};
for (const key of this[shapekeysSymbol]) {
const schema = (this.objectShape as any)[key];
if (schema instanceof UnknownType && !(value as any).hasOwnProperty(key)) {
hasError = true;
errs[key] = this.buildPathError(
(schema as any).typeError(`expected key "${key}" of unknown type to be present on object`),
key,
{ suppressPathErrMsg: true }
);
continue;
}
const result = (schema as any).try((value as any)[key], { suppressPathErrMsg: true });
if (result instanceof ValidationError) {
hasError = true;
errs[key] = this.buildPathError(result, key, { suppressPathErrMsg: true });
}
}
if (hasError) {
throw new ValidationError('', undefined, errs);
}
if (this.predicates) {
applyPredicates(this.predicates, value);
}
return value as any;
}
private parseObjectConv(value: Object, parseOpts: ObjectOptions<any> & PathOptions): InferObjectShape<T> {
const convVal: any = {};
for (const key of this[shapekeysSymbol]) {
try {
const schema = (this.objectShape as any)[key];
if (schema instanceof UnknownType && !(value as any).hasOwnProperty(key)) {
throw (schema as any).typeError(`expected key "${key}" of unknown type to be present on object`);
}
convVal[key] = (schema as any).parse((value as any)[key], { suppressPathErrMsg: true });
} catch (err: any) {
throw this.buildPathError(err, key, parseOpts);
}
}
if (this.predicates) {
applyPredicates(this.predicates, convVal);
}
return convVal;
}
private parseObjectConvCollect(value: Object, parseOpts: ObjectOptions<any> & PathOptions): InferObjectShape<T> {
const convVal: any = {};
const errs: any = {};
let hasError = false;
for (const key of this[shapekeysSymbol]) {
const schema = (this.objectShape as any)[key];
if (schema instanceof UnknownType && !(value as any).hasOwnProperty(key)) {
hasError = true;
errs[key] = this.buildPathError(
(schema as any).typeError(`expected key "${key}" of unknown type to be present on object`),
key,
{ suppressPathErrMsg: true }
);
continue;
}
const result = (schema as any).try((value as any)[key], { suppressPathErrMsg: true });
if (result instanceof ValidationError) {
hasError = true;
errs[key] = this.buildPathError(result, key, { suppressPathErrMsg: true });
} else {
convVal[key] = result;
}
}
if (hasError) {
throw new ValidationError('', undefined, errs);
}
if (this.predicates) {
applyPredicates(this.predicates, convVal);
}
return convVal;
}
private parseRecord(value: Object, parseOpts: ObjectOptions<any> & PathOptions): InferObjectShape<T> {
for (const key in value) {
try {
(this[keySignature] as any).parse((value as any)[key], { suppressPathErrMsg: true });
} catch (err: any) {
throw this.buildPathError(err, key, parseOpts);
}
}
if (this.predicates) {
applyPredicates(this.predicates, value);
}
return value as any;
}
private parseRecordCollect(value: Object, parseOpts: ObjectOptions<any> & PathOptions): InferObjectShape<T> {
let hasError = false;
const errs: Record<string, ValidationError> = {};
for (const key in value) {
const result = (this[keySignature] as any).try((value as any)[key], { suppressPathErrMsg: true });
if (result instanceof ValidationError) {
hasError = true;
errs[key] = this.buildPathError(result, key, { suppressPathErrMsg: true });
}
}
if (hasError) {
throw new ValidationError('', undefined, errs);
}
if (this.predicates) {
applyPredicates(this.predicates, value);
}
return value as any;
}
private parseRecordConv(value: Object, parseOpts: ObjectOptions<any> & PathOptions): InferObjectShape<T> {
const convVal: any = {};
for (const key in value) {
try {
convVal[key] = (this[keySignature] as any).parse((value as any)[key], { suppressPathErrMsg: true });
} catch (err: any) {
throw this.buildPathError(err, key, parseOpts);
}
}
if (this.predicates) {
applyPredicates(this.predicates, convVal);
}
return convVal;
}
private parseRecordConvCollect(value: Object, parseOpts: ObjectOptions<any> & PathOptions): InferObjectShape<T> {