-
Notifications
You must be signed in to change notification settings - Fork 327
/
index.ts
2167 lines (1984 loc) · 52.8 KB
/
index.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
import { Either, either, isLeft, left, right } from 'fp-ts/lib/Either'
import { Predicate, Refinement } from 'fp-ts/lib/function'
const map = either.map
const chain = either.chain
/**
* @since 1.0.0
*/
export interface ContextEntry {
readonly key: string
readonly type: Decoder<any, any>
/** the input data */
readonly actual?: unknown
}
/**
* @since 1.0.0
*/
export interface Context extends ReadonlyArray<ContextEntry> {}
/**
* @since 1.0.0
*/
export interface ValidationError {
/** the offending (sub)value */
readonly value: unknown
/** where the error originated */
readonly context: Context
/** optional custom error message */
readonly message?: string
}
/**
* @since 1.0.0
*/
export interface Errors extends Array<ValidationError> {}
/**
* @since 1.0.0
*/
export type Validation<A> = Either<Errors, A>
/**
* @since 1.0.0
*/
export type Is<A> = (u: unknown) => u is A
/**
* @since 1.0.0
*/
export type Validate<I, A> = (i: I, context: Context) => Validation<A>
/**
* @since 1.0.0
*/
export type Decode<I, A> = (i: I) => Validation<A>
/**
* @since 1.0.0
*/
export type Encode<A, O> = (a: A) => O
/**
* @since 1.0.0
*/
export interface Any extends Type<any, any, any> {}
/**
* @since 1.0.0
*/
export interface Mixed extends Type<any, any, unknown> {}
/**
* @since 1.0.0
*/
export type TypeOf<C extends Any> = C['_A']
/**
* @since 1.0.0
*/
export type InputOf<C extends Any> = C['_I']
/**
* @since 1.0.0
*/
export type OutputOf<C extends Any> = C['_O']
/**
* @since 1.0.0
*/
export interface Decoder<I, A> {
readonly name: string
readonly validate: Validate<I, A>
readonly decode: Decode<I, A>
}
/**
* @since 1.0.0
*/
export interface Encoder<A, O> {
readonly encode: Encode<A, O>
}
/**
* @since 1.0.0
*/
export class Type<A, O = A, I = unknown> implements Decoder<I, A>, Encoder<A, O> {
readonly _A!: A
readonly _O!: O
readonly _I!: I
constructor(
/** a unique name for this codec */
readonly name: string,
/** a custom type guard */
readonly is: Is<A>,
/** succeeds if a value of type I can be decoded to a value of type A */
readonly validate: Validate<I, A>,
/** converts a value of type A to a value of type O */
readonly encode: Encode<A, O>
) {
this.decode = this.decode.bind(this)
}
/**
* @since 1.0.0
*/
pipe<B, IB, A extends IB, OB extends A>(
this: Type<A, O, I>,
ab: Type<B, OB, IB>,
name: string = `pipe(${this.name}, ${ab.name})`
): Type<B, O, I> {
return new Type(
name,
ab.is,
(i, c) => chain(this.validate(i, c), a => ab.validate(a, c)),
this.encode === identity && ab.encode === identity ? (identity as any) : b => this.encode(ab.encode(b))
)
}
/**
* @since 1.0.0
*/
asDecoder(): Decoder<I, A> {
return this
}
/**
* @since 1.0.0
*/
asEncoder(): Encoder<A, O> {
return this
}
/**
* a version of `validate` with a default context
* @since 1.0.0
*/
decode(i: I): Validation<A> {
return this.validate(i, [{ key: '', type: this, actual: i }])
}
}
/**
* @since 1.0.0
*/
export const identity = <A>(a: A): A => a
/**
* @since 1.0.0
*/
export const getFunctionName = (f: Function): string =>
(f as any).displayName || (f as any).name || `<function${f.length}>`
/**
* @since 1.0.0
*/
export const getContextEntry = (key: string, decoder: Decoder<any, any>): ContextEntry => ({ key, type: decoder })
/**
* @since 1.0.0
*/
export const appendContext = (c: Context, key: string, decoder: Decoder<any, any>, actual?: unknown): Context => {
const len = c.length
const r = Array(len + 1)
for (let i = 0; i < len; i++) {
r[i] = c[i]
}
r[len] = { key, type: decoder, actual }
return r
}
/**
* @since 1.0.0
*/
export const failures: <T>(errors: Errors) => Validation<T> = left
/**
* @since 1.0.0
*/
export const failure = <T>(value: unknown, context: Context, message?: string): Validation<T> =>
failures([{ value, context, message }])
/**
* @since 1.0.0
*/
export const success: <T>(value: T) => Validation<T> = right
const pushAll = <A>(xs: Array<A>, ys: Array<A>): void => {
const l = ys.length
for (let i = 0; i < l; i++) {
xs.push(ys[i])
}
}
const getIsCodec = <T extends Any>(tag: string) => (codec: Any): codec is T => (codec as any)._tag === tag
const isUnknownCodec = getIsCodec<UnknownType>('UnknownType')
// tslint:disable-next-line: deprecation
const isAnyCodec = getIsCodec<AnyType>('AnyType')
const isInterfaceCodec = getIsCodec<InterfaceType<Props>>('InterfaceType')
const isPartialCodec = getIsCodec<PartialType<Props>>('PartialType')
//
// basic types
//
/**
* @since 1.0.0
*/
export class NullType extends Type<null> {
readonly _tag: 'NullType' = 'NullType'
constructor() {
super(
'null',
(u): u is null => u === null,
(u, c) => (this.is(u) ? success(u) : failure(u, c)),
identity
)
}
}
/**
* @since 1.5.3
*/
export interface NullC extends NullType {}
/**
* @since 1.0.0
*/
export const nullType: NullC = new NullType()
/**
* @since 1.0.0
*/
export class UndefinedType extends Type<undefined> {
readonly _tag: 'UndefinedType' = 'UndefinedType'
constructor() {
super(
'undefined',
(u): u is undefined => u === void 0,
(u, c) => (this.is(u) ? success(u) : failure(u, c)),
identity
)
}
}
/**
* @since 1.5.3
*/
export interface UndefinedC extends UndefinedType {}
const undefinedType: UndefinedC = new UndefinedType()
/**
* @since 1.2.0
*/
export class VoidType extends Type<void> {
readonly _tag: 'VoidType' = 'VoidType'
constructor() {
super('void', undefinedType.is, undefinedType.validate, identity)
}
}
/**
* @since 1.5.3
*/
export interface VoidC extends VoidType {}
/**
* @since 1.2.0
*/
export const voidType: VoidC = new VoidType()
/**
* @since 1.5.0
*/
export class UnknownType extends Type<unknown> {
readonly _tag: 'UnknownType' = 'UnknownType'
constructor() {
super('unknown', (_): _ is unknown => true, success, identity)
}
}
/**
* @since 1.5.3
*/
export interface UnknownC extends UnknownType {}
/**
* @since 1.5.0
*/
export const unknown: UnknownC = new UnknownType()
/**
* @since 1.0.0
*/
export class StringType extends Type<string> {
readonly _tag: 'StringType' = 'StringType'
constructor() {
super(
'string',
(u): u is string => typeof u === 'string',
(u, c) => (this.is(u) ? success(u) : failure(u, c)),
identity
)
}
}
/**
* @since 1.5.3
*/
export interface StringC extends StringType {}
/**
* @since 1.0.0
*/
export const string: StringC = new StringType()
/**
* @since 1.0.0
*/
export class NumberType extends Type<number> {
readonly _tag: 'NumberType' = 'NumberType'
constructor() {
super(
'number',
(u): u is number => typeof u === 'number',
(u, c) => (this.is(u) ? success(u) : failure(u, c)),
identity
)
}
}
/**
* @since 1.5.3
*/
export interface NumberC extends NumberType {}
/**
* @since 1.0.0
*/
export const number: NumberC = new NumberType()
/**
* @since 1.0.0
*/
export class BooleanType extends Type<boolean> {
readonly _tag: 'BooleanType' = 'BooleanType'
constructor() {
super(
'boolean',
(u): u is boolean => typeof u === 'boolean',
(u, c) => (this.is(u) ? success(u) : failure(u, c)),
identity
)
}
}
/**
* @since 1.5.3
*/
export interface BooleanC extends BooleanType {}
/**
* @since 1.0.0
*/
export const boolean: BooleanC = new BooleanType()
/**
* @since 1.0.0
*/
export class AnyArrayType extends Type<Array<unknown>> {
readonly _tag: 'AnyArrayType' = 'AnyArrayType'
constructor() {
super('UnknownArray', Array.isArray, (u, c) => (this.is(u) ? success(u) : failure(u, c)), identity)
}
}
/**
* @since 1.5.3
*/
export interface UnknownArrayC extends AnyArrayType {}
/**
* @since 1.7.1
*/
export const UnknownArray: UnknownArrayC = new AnyArrayType()
/**
* @since 1.0.0
*/
export class AnyDictionaryType extends Type<{ [key: string]: unknown }> {
readonly _tag: 'AnyDictionaryType' = 'AnyDictionaryType'
constructor() {
super(
'UnknownRecord',
(u): u is { [key: string]: unknown } => u !== null && typeof u === 'object',
(u, c) => (this.is(u) ? success(u) : failure(u, c)),
identity
)
}
}
/**
* @since 1.7.1
*/
export const UnknownRecord: UnknownRecordC = new AnyDictionaryType()
/**
* @since 1.5.3
*/
export interface UnknownRecordC extends AnyDictionaryType {}
/**
* @since 1.0.0
* @deprecated
*/
export class FunctionType extends Type<Function> {
readonly _tag: 'FunctionType' = 'FunctionType'
constructor() {
super(
'Function',
// tslint:disable-next-line:strict-type-predicates
(u): u is Function => typeof u === 'function',
(u, c) => (this.is(u) ? success(u) : failure(u, c)),
identity
)
}
}
/**
* @since 1.5.3
* @deprecated
*/
// tslint:disable-next-line: deprecation
export interface FunctionC extends FunctionType {}
/**
* @since 1.0.0
* @deprecated
*/
// tslint:disable-next-line: deprecation
export const Function: FunctionC = new FunctionType()
/**
* @since 1.0.0
*/
export class RefinementType<C extends Any, A = any, O = A, I = unknown> extends Type<A, O, I> {
readonly _tag: 'RefinementType' = 'RefinementType'
constructor(
name: string,
is: RefinementType<C, A, O, I>['is'],
validate: RefinementType<C, A, O, I>['validate'],
encode: RefinementType<C, A, O, I>['encode'],
readonly type: C,
readonly predicate: Predicate<A>
) {
super(name, is, validate, encode)
}
}
declare const _brand: unique symbol
/**
* @since 1.8.1
*/
export interface Brand<B> {
readonly [_brand]: B
}
/**
* @since 1.8.1
*/
export type Branded<A, B> = A & Brand<B>
/**
* @since 1.8.1
*/
export interface BrandC<C extends Any, B> extends RefinementType<C, Branded<TypeOf<C>, B>, OutputOf<C>, InputOf<C>> {}
/**
* @since 1.8.1
*/
export const brand = <C extends Any, N extends string, B extends { readonly [K in N]: symbol }>(
codec: C,
predicate: Refinement<TypeOf<C>, Branded<TypeOf<C>, B>>,
name: N
): BrandC<C, B> => {
// tslint:disable-next-line: deprecation
return refinement(codec, predicate, name)
}
/**
* @since 1.8.1
*/
export interface IntBrand {
readonly Int: unique symbol
}
/**
* A branded codec representing an integer
* @since 1.8.1
*/
export const Int = brand(number, (n): n is Branded<number, IntBrand> => Number.isInteger(n), 'Int')
/**
* @since 1.8.1
*/
export type Int = Branded<number, IntBrand>
type LiteralValue = string | number | boolean
/**
* @since 1.0.0
*/
export class LiteralType<V extends LiteralValue> extends Type<V> {
readonly _tag: 'LiteralType' = 'LiteralType'
constructor(
name: string,
is: LiteralType<V>['is'],
validate: LiteralType<V>['validate'],
encode: LiteralType<V>['encode'],
readonly value: V
) {
super(name, is, validate, encode)
}
}
/**
* @since 1.5.3
*/
export interface LiteralC<V extends LiteralValue> extends LiteralType<V> {}
/**
* @since 1.0.0
*/
export const literal = <V extends LiteralValue>(value: V, name: string = JSON.stringify(value)): LiteralC<V> => {
const is = (u: unknown): u is V => u === value
return new LiteralType(name, is, (u, c) => (is(u) ? success(value) : failure(u, c)), identity, value)
}
/**
* @since 1.0.0
*/
export class KeyofType<D extends { [key: string]: unknown }> extends Type<keyof D> {
readonly _tag: 'KeyofType' = 'KeyofType'
constructor(
name: string,
is: KeyofType<D>['is'],
validate: KeyofType<D>['validate'],
encode: KeyofType<D>['encode'],
readonly keys: D
) {
super(name, is, validate, encode)
}
}
const hasOwnProperty = Object.prototype.hasOwnProperty
/**
* @since 1.5.3
*/
export interface KeyofC<D extends { [key: string]: unknown }> extends KeyofType<D> {}
/**
* @since 1.0.0
*/
export const keyof = <D extends { [key: string]: unknown }>(
keys: D,
name: string = Object.keys(keys)
.map(k => JSON.stringify(k))
.join(' | ')
): KeyofC<D> => {
const is = (u: unknown): u is keyof D => string.is(u) && hasOwnProperty.call(keys, u)
return new KeyofType(name, is, (u, c) => (is(u) ? success(u) : failure(u, c)), identity, keys)
}
/**
* @since 1.0.0
*/
export class RecursiveType<C extends Any, A = any, O = A, I = unknown> extends Type<A, O, I> {
readonly _tag: 'RecursiveType' = 'RecursiveType'
constructor(
name: string,
is: RecursiveType<C, A, O, I>['is'],
validate: RecursiveType<C, A, O, I>['validate'],
encode: RecursiveType<C, A, O, I>['encode'],
private runDefinition: () => C
) {
super(name, is, validate, encode)
}
get type(): C {
return this.runDefinition()
}
}
/**
* @since 1.0.0
*/
export const recursion = <A, O = A, I = unknown, C extends Type<A, O, I> = Type<A, O, I>>(
name: string,
definition: (self: C) => C
): RecursiveType<C, A, O, I> => {
let cache: C
const runDefinition = (): C => {
if (!cache) {
cache = definition(Self)
;(cache as any).name = name
}
return cache
}
const Self: any = new RecursiveType<C, A, O, I>(
name,
(u): u is A => runDefinition().is(u),
(u, c) => runDefinition().validate(u, c),
a => runDefinition().encode(a),
runDefinition
)
return Self
}
/**
* @since 1.0.0
*/
export class ArrayType<C extends Any, A = any, O = A, I = unknown> extends Type<A, O, I> {
readonly _tag: 'ArrayType' = 'ArrayType'
constructor(
name: string,
is: ArrayType<C, A, O, I>['is'],
validate: ArrayType<C, A, O, I>['validate'],
encode: ArrayType<C, A, O, I>['encode'],
readonly type: C
) {
super(name, is, validate, encode)
}
}
/**
* @since 1.5.3
*/
export interface ArrayC<C extends Mixed> extends ArrayType<C, Array<TypeOf<C>>, Array<OutputOf<C>>, unknown> {}
/**
* @since 1.0.0
*/
export const array = <C extends Mixed>(codec: C, name: string = `Array<${codec.name}>`): ArrayC<C> =>
new ArrayType(
name,
(u): u is Array<TypeOf<C>> => UnknownArray.is(u) && u.every(codec.is),
(u, c) =>
chain(UnknownArray.validate(u, c), us => {
const len = us.length
let as: Array<TypeOf<C>> = us
const errors: Errors = []
for (let i = 0; i < len; i++) {
const ui = us[i]
const result = codec.validate(ui, appendContext(c, String(i), codec, ui))
if (isLeft(result)) {
pushAll(errors, result.left)
} else {
const ai = result.right
if (ai !== ui) {
if (as === us) {
as = us.slice()
}
as[i] = ai
}
}
}
return errors.length > 0 ? failures(errors) : success(as)
}),
codec.encode === identity ? identity : a => a.map(codec.encode),
codec
)
/**
* @since 1.0.0
*/
export class InterfaceType<P, A = any, O = A, I = unknown> extends Type<A, O, I> {
readonly _tag: 'InterfaceType' = 'InterfaceType'
constructor(
name: string,
is: InterfaceType<P, A, O, I>['is'],
validate: InterfaceType<P, A, O, I>['validate'],
encode: InterfaceType<P, A, O, I>['encode'],
readonly props: P
) {
super(name, is, validate, encode)
}
}
/**
* @since 1.0.0
*/
export interface AnyProps {
[key: string]: Any
}
const getNameFromProps = (props: Props): string =>
Object.keys(props)
.map(k => `${k}: ${props[k].name}`)
.join(', ')
const useIdentity = (codecs: Array<Any>): boolean => {
for (let i = 0; i < codecs.length; i++) {
if (codecs[i].encode !== identity) {
return false
}
}
return true
}
/**
* @since 1.0.0
*/
export type TypeOfProps<P extends AnyProps> = { [K in keyof P]: TypeOf<P[K]> }
/**
* @since 1.0.0
*/
export type OutputOfProps<P extends AnyProps> = { [K in keyof P]: OutputOf<P[K]> }
/**
* @since 1.0.0
*/
export interface Props {
[key: string]: Mixed
}
/**
* @since 1.5.3
*/
export interface TypeC<P extends Props>
extends InterfaceType<P, { [K in keyof P]: TypeOf<P[K]> }, { [K in keyof P]: OutputOf<P[K]> }, unknown> {}
const getInterfaceTypeName = (props: Props): string => {
return `{ ${getNameFromProps(props)} }`
}
/**
* @since 1.0.0
*/
export const type = <P extends Props>(props: P, name: string = getInterfaceTypeName(props)): TypeC<P> => {
const keys = Object.keys(props)
const types = keys.map(key => props[key])
const len = keys.length
return new InterfaceType(
name,
(u): u is { [K in keyof P]: TypeOf<P[K]> } => {
if (!UnknownRecord.is(u)) {
return false
}
for (let i = 0; i < len; i++) {
const k = keys[i]
if (!hasOwnProperty.call(u, k) || !types[i].is(u[k])) {
return false
}
}
return true
},
(u, c) =>
chain(UnknownRecord.validate(u, c), o => {
let a = o
const errors: Errors = []
for (let i = 0; i < len; i++) {
const k = keys[i]
if (!hasOwnProperty.call(a, k)) {
if (a === o) {
a = { ...o }
}
a[k] = a[k]
}
const ak = a[k]
const type = types[i]
const result = type.validate(ak, appendContext(c, k, type, ak))
if (isLeft(result)) {
pushAll(errors, result.left)
} else {
const vak = result.right
if (vak !== ak) {
/* istanbul ignore next */
if (a === o) {
a = { ...o }
}
a[k] = vak
}
}
}
return errors.length > 0 ? failures(errors) : success(a as any)
}),
useIdentity(types)
? identity
: a => {
const s: { [x: string]: any } = { ...a }
for (let i = 0; i < len; i++) {
const k = keys[i]
const encode = types[i].encode
if (encode !== identity) {
s[k] = encode(a[k])
}
}
return s as any
},
props
)
}
/**
* @since 1.0.0
*/
export class PartialType<P, A = any, O = A, I = unknown> extends Type<A, O, I> {
readonly _tag: 'PartialType' = 'PartialType'
constructor(
name: string,
is: PartialType<P, A, O, I>['is'],
validate: PartialType<P, A, O, I>['validate'],
encode: PartialType<P, A, O, I>['encode'],
readonly props: P
) {
super(name, is, validate, encode)
}
}
/**
* @since 1.0.0
*/
export type TypeOfPartialProps<P extends AnyProps> = { [K in keyof P]?: TypeOf<P[K]> }
/**
* @since 1.0.0
*/
export type OutputOfPartialProps<P extends AnyProps> = { [K in keyof P]?: OutputOf<P[K]> }
/**
* @since 1.5.3
*/
export interface PartialC<P extends Props>
extends PartialType<P, { [K in keyof P]?: TypeOf<P[K]> }, { [K in keyof P]?: OutputOf<P[K]> }, unknown> {}
const getPartialTypeName = (inner: string): string => {
return `Partial<${inner}>`
}
/**
* @since 1.0.0
*/
export const partial = <P extends Props>(
props: P,
name: string = getPartialTypeName(getInterfaceTypeName(props))
): PartialC<P> => {
const keys = Object.keys(props)
const types = keys.map(key => props[key])
const len = keys.length
return new PartialType(
name,
(u): u is { [K in keyof P]?: TypeOf<P[K]> } => {
if (!UnknownRecord.is(u)) {
return false
}
for (let i = 0; i < len; i++) {
const k = keys[i]
const uk = u[k]
if (uk !== undefined && !props[k].is(uk)) {
return false
}
}
return true
},
(u, c) =>
chain(UnknownRecord.validate(u, c), o => {
let a = o
const errors: Errors = []
for (let i = 0; i < len; i++) {
const k = keys[i]
const ak = a[k]
const type = props[k]
const result = type.validate(ak, appendContext(c, k, type, ak))
if (isLeft(result)) {
if (ak !== undefined) {
pushAll(errors, result.left)
}
} else {
const vak = result.right
if (vak !== ak) {
/* istanbul ignore next */
if (a === o) {
a = { ...o }
}
a[k] = vak
}
}
}
return errors.length > 0 ? failures(errors) : success(a as any)
}),
useIdentity(types)
? identity
: a => {
const s: { [key: string]: any } = { ...a }
for (let i = 0; i < len; i++) {
const k = keys[i]
const ak = a[k]
if (ak !== undefined) {
s[k] = types[i].encode(ak)
}
}
return s as any
},
props
)
}
/**
* @since 1.0.0
*/
export class DictionaryType<D extends Any, C extends Any, A = any, O = A, I = unknown> extends Type<A, O, I> {
readonly _tag: 'DictionaryType' = 'DictionaryType'
constructor(
name: string,
is: DictionaryType<D, C, A, O, I>['is'],
validate: DictionaryType<D, C, A, O, I>['validate'],
encode: DictionaryType<D, C, A, O, I>['encode'],
readonly domain: D,
readonly codomain: C
) {
super(name, is, validate, encode)
}
}
/**
* @since 1.0.0
*/
export type TypeOfDictionary<D extends Any, C extends Any> = { [K in TypeOf<D>]: TypeOf<C> }
/**
* @since 1.0.0
*/
export type OutputOfDictionary<D extends Any, C extends Any> = { [K in OutputOf<D>]: OutputOf<C> }
/**
* @since 1.5.3
*/
export interface RecordC<D extends Mixed, C extends Mixed>
extends DictionaryType<D, C, { [K in TypeOf<D>]: TypeOf<C> }, { [K in OutputOf<D>]: OutputOf<C> }, unknown> {}
const isObject = (r: Record<string, unknown>) => Object.prototype.toString.call(r) === '[object Object]'
/**
* @since 1.7.1
*/
export const record = <D extends Mixed, C extends Mixed>(
domain: D,
codomain: C,
name: string = `{ [K in ${domain.name}]: ${codomain.name} }`
): RecordC<D, C> => {
return new DictionaryType(
name,
(u): u is { [K in TypeOf<D>]: TypeOf<C> } => {
if (!UnknownRecord.is(u)) {
return false
}
if (!isUnknownCodec(codomain) && !isAnyCodec(codomain) && !isObject(u)) {
return false
}
return Object.keys(u).every(k => domain.is(k) && codomain.is(u[k]))
},
(u, c) =>
chain(UnknownRecord.validate(u, c), o => {
if (!isUnknownCodec(codomain) && !isAnyCodec(codomain) && !isObject(o)) {
return failure(u, c)
}
const a: { [key: string]: any } = {}
const errors: Errors = []
const keys = Object.keys(o)
const len = keys.length
let changed: boolean = false
for (let i = 0; i < len; i++) {
let k = keys[i]
const ok = o[k]
const domainResult = domain.validate(k, appendContext(c, k, domain, k))