-
Notifications
You must be signed in to change notification settings - Fork 328
/
Copy pathDecoder.ts
620 lines (542 loc) · 15.7 KB
/
Decoder.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
/**
* **This module is experimental**
*
* Experimental features are published in order to get early feedback from the community, see these tracking
* [issues](https://github.com/gcanti/io-ts/issues?q=label%3Av2.2+) for further discussions and enhancements.
*
* A feature tagged as _Experimental_ is in a high state of flux, you're at risk of it changing without notice.
*
* @since 2.2.7
*/
import { Alt2, Alt2C } from 'fp-ts/lib/Alt'
import { Bifunctor2 } from 'fp-ts/lib/Bifunctor'
import { Category2 } from 'fp-ts/lib/Category'
import * as E from 'fp-ts/lib/Either'
import { identity, Refinement } from 'fp-ts/lib/function'
import { Functor2 } from 'fp-ts/lib/Functor'
import { MonadThrow2C } from 'fp-ts/lib/MonadThrow'
import * as O from 'fp-ts/lib/Option'
import { pipe } from 'fp-ts/lib/pipeable'
import * as DE from './DecodeError'
import * as FS from './FreeSemigroup'
import * as G from './Guard'
import * as K from './Kleisli'
import * as S from './Schemable'
// -------------------------------------------------------------------------------------
// Kleisli config
// -------------------------------------------------------------------------------------
/**
* @internal
*/
export const SE =
/*#__PURE__*/
DE.getSemigroup<string>()
/**
* @internal
*/
export const ap = <A, B>(
fab: E.Either<DecodeError, (a: A) => B>,
fa: E.Either<DecodeError, A>
): E.Either<DecodeError, B> =>
E.isLeft(fab)
? E.isLeft(fa)
? E.left(SE.concat(fab.left, fa.left))
: fab
: E.isLeft(fa)
? fa
: E.right(fab.right(fa.right))
const M: MonadThrow2C<E.URI, DecodeError> & Bifunctor2<E.URI> & Alt2C<E.URI, DecodeError> = {
URI: E.URI,
_E: undefined as any,
map: (fa, f) => pipe(fa, E.map(f)),
ap,
of: E.right,
chain: (ma, f) => pipe(ma, E.chain(f)),
throwError: E.left,
bimap: (fa, f, g) => pipe(fa, E.bimap(f, g)),
mapLeft: (fa, f) => pipe(fa, E.mapLeft(f)),
alt: (me, that) => {
if (E.isRight(me)) {
return me
}
const ea = that()
return E.isLeft(ea) ? E.left(SE.concat(me.left, ea.left)) : ea
}
}
// -------------------------------------------------------------------------------------
// model
// -------------------------------------------------------------------------------------
/**
* @category model
* @since 2.2.8
*/
export interface Decoder<I, A> extends K.Kleisli<E.URI, I, DecodeError, A> {}
// -------------------------------------------------------------------------------------
// DecodeError
// -------------------------------------------------------------------------------------
/**
* @category DecodeError
* @since 2.2.7
*/
export type DecodeError = FS.FreeSemigroup<DE.DecodeError<string>>
/**
* @category DecodeError
* @since 2.2.7
*/
export const error = (actual: unknown, message: string): DecodeError => FS.of(DE.leaf(actual, message))
/**
* @category DecodeError
* @since 2.2.7
*/
export const success: <A>(a: A) => E.Either<DecodeError, A> = E.right
/**
* @category DecodeError
* @since 2.2.7
*/
export const failure = <A = never>(actual: unknown, message: string): E.Either<DecodeError, A> =>
E.left(error(actual, message))
// -------------------------------------------------------------------------------------
// constructors
// -------------------------------------------------------------------------------------
/**
* @category constructors
* @since 2.2.8
*/
export const fromRefinement = <I, A extends I>(refinement: Refinement<I, A>, expected: string): Decoder<I, A> =>
K.fromRefinement(M)(refinement, (u) => error(u, expected))
/**
* @category constructors
* @since 2.2.8
*/
export const fromGuard = <I, A extends I>(guard: G.Guard<I, A>, expected: string): Decoder<I, A> =>
fromRefinement(guard.is, expected)
/**
* @category constructors
* @since 2.2.7
*/
export const literal: <A extends readonly [S.Literal, ...Array<S.Literal>]>(
...values: A
) => Decoder<unknown, A[number]> =
/*#__PURE__*/
K.literal(M)((u, values) => error(u, values.map((value) => JSON.stringify(value)).join(' | ')))
// -------------------------------------------------------------------------------------
// primitives
// -------------------------------------------------------------------------------------
/**
* @category primitives
* @since 2.2.7
*/
export const string: Decoder<unknown, string> =
/*#__PURE__*/
fromGuard(G.string, 'string')
/**
* @category primitives
* @since 2.2.7
*/
export const number: Decoder<unknown, number> =
/*#__PURE__*/
fromGuard(G.number, 'number')
/**
* @category primitives
* @since 2.2.7
*/
export const boolean: Decoder<unknown, boolean> =
/*#__PURE__*/
fromGuard(G.boolean, 'boolean')
/**
* @category primitives
* @since 2.2.7
*/
export const UnknownArray: Decoder<unknown, Array<unknown>> =
/*#__PURE__*/
fromGuard(G.UnknownArray, 'Array<unknown>')
/**
* @category primitives
* @since 2.2.7
*/
export const UnknownRecord: Decoder<unknown, Record<string, unknown>> =
/*#__PURE__*/
fromGuard(G.UnknownRecord, 'Record<string, unknown>')
// -------------------------------------------------------------------------------------
// combinators
// -------------------------------------------------------------------------------------
/**
* @category combinators
* @since 2.2.7
*/
export const mapLeftWithInput: <I>(
f: (input: I, e: DecodeError) => DecodeError
) => <A>(decoder: Decoder<I, A>) => Decoder<I, A> =
/*#__PURE__*/
K.mapLeftWithInput(M)
/**
* @category combinators
* @since 2.2.9
*/
export const withMessage = <I>(
message: (input: I, e: DecodeError) => string
): (<A>(decoder: Decoder<I, A>) => Decoder<I, A>) =>
mapLeftWithInput((input, e) => FS.of(DE.wrap(message(input, e), e)))
/**
* @category combinators
* @since 2.2.7
*/
export const refine = <A, B extends A>(
refinement: Refinement<A, B>,
id: string
): (<I>(from: Decoder<I, A>) => Decoder<I, B>) => K.refine(M)(refinement, (a) => error(a, id))
/**
* @category combinators
* @since 2.2.7
*/
export const parse: <A, B>(parser: (a: A) => E.Either<DecodeError, B>) => <I>(from: Decoder<I, A>) => Decoder<I, B> =
/*#__PURE__*/
K.parse(M)
/**
* @category combinators
* @since 2.2.7
*/
export const nullable: <I, A>(or: Decoder<I, A>) => Decoder<null | I, null | A> =
/*#__PURE__*/
K.nullable(M)((u, e) => FS.concat(FS.of(DE.member(0, error(u, 'null'))), FS.of(DE.member(1, e))))
/**
* @category combinators
* @since 2.2.15
*/
export const fromStruct = <P extends Record<string, Decoder<any, any>>>(
properties: P
): Decoder<{ [K in keyof P]: InputOf<P[K]> }, { [K in keyof P]: TypeOf<P[K]> }> =>
K.fromStruct(M)((k, e) => FS.of(DE.key(k, DE.required, e)))(properties)
/**
* Use `fromStruct` instead.
*
* @category combinators
* @since 2.2.8
* @deprecated
*/
export const fromType = fromStruct
/**
* @category combinators
* @since 2.2.15
*/
export const struct = <A>(
properties: { [K in keyof A]: Decoder<unknown, A[K]> }
): Decoder<unknown, { [K in keyof A]: A[K] }> => pipe(UnknownRecord as any, compose(fromStruct(properties)))
/**
* Use `struct` instead.
*
* @category combinators
* @since 2.2.7
* @deprecated
*/
export const type = struct
/**
* @category combinators
* @since 2.2.8
*/
export const fromPartial = <P extends Record<string, Decoder<any, any>>>(
properties: P
): Decoder<Partial<{ [K in keyof P]: InputOf<P[K]> }>, Partial<{ [K in keyof P]: TypeOf<P[K]> }>> =>
K.fromPartial(M)((k, e) => FS.of(DE.key(k, DE.optional, e)))(properties)
/**
* @category combinators
* @since 2.2.7
*/
export const partial = <A>(
properties: { [K in keyof A]: Decoder<unknown, A[K]> }
): Decoder<unknown, Partial<{ [K in keyof A]: A[K] }>> => pipe(UnknownRecord as any, compose(fromPartial(properties)))
/**
* @category combinators
* @since 2.2.8
*/
export const fromArray = <I, A>(item: Decoder<I, A>): Decoder<Array<I>, Array<A>> =>
K.fromArray(M)((i, e) => FS.of(DE.index(i, DE.optional, e)))(item)
/**
* @category combinators
* @since 2.2.7
*/
export const array = <A>(item: Decoder<unknown, A>): Decoder<unknown, Array<A>> =>
pipe(UnknownArray, compose(fromArray(item)))
/**
* @category combinators
* @since 2.2.8
*/
export const fromRecord = <I, A>(codomain: Decoder<I, A>): Decoder<Record<string, I>, Record<string, A>> =>
K.fromRecord(M)((k, e) => FS.of(DE.key(k, DE.optional, e)))(codomain)
/**
* @category combinators
* @since 2.2.7
*/
export const record = <A>(codomain: Decoder<unknown, A>): Decoder<unknown, Record<string, A>> =>
pipe(UnknownRecord, compose(fromRecord(codomain)))
/**
* @category combinators
* @since 2.2.8
*/
export const fromTuple = <C extends ReadonlyArray<Decoder<any, any>>>(
...components: C
): Decoder<{ [K in keyof C]: InputOf<C[K]> }, { [K in keyof C]: TypeOf<C[K]> }> =>
K.fromTuple(M)((i, e) => FS.of(DE.index(i, DE.required, e)))(...components) as any
/**
* @category combinators
* @since 2.2.7
*/
export const tuple = <A extends ReadonlyArray<unknown>>(
...components: { [K in keyof A]: Decoder<unknown, A[K]> }
): Decoder<unknown, A> => pipe(UnknownArray as any, compose(fromTuple(...components))) as any
/**
* @category combinators
* @since 2.2.7
*/
export const union: <MS extends readonly [Decoder<any, any>, ...Array<Decoder<any, any>>]>(
...members: MS
) => Decoder<InputOf<MS[keyof MS]>, TypeOf<MS[keyof MS]>> =
/*#__PURE__*/
K.union(M)((i, e) => FS.of(DE.member(i, e)))
/**
* @category combinators
* @since 2.2.7
*/
export const intersect: <IB, B>(right: Decoder<IB, B>) => <IA, A>(left: Decoder<IA, A>) => Decoder<IA & IB, A & B> =
/*#__PURE__*/
K.intersect(M)
/**
* @category combinators
* @since 2.2.8
*/
export const fromSum = <T extends string>(tag: T) => <MS extends Record<string, Decoder<any, any>>>(
members: MS
): Decoder<InputOf<MS[keyof MS]>, TypeOf<MS[keyof MS]>> =>
K.fromSum(M)((tag, value, keys) =>
FS.of(
DE.key(
tag,
DE.required,
error(value, keys.length === 0 ? 'never' : keys.map((k) => JSON.stringify(k)).join(' | '))
)
)
)(tag)(members)
/**
* @category combinators
* @since 2.2.7
*/
export const sum = <T extends string>(tag: T) => <A>(
members: { [K in keyof A]: Decoder<unknown, A[K] & Record<T, K>> }
): Decoder<unknown, A[keyof A]> => pipe(UnknownRecord as any, compose(fromSum(tag)(members)))
/**
* @category combinators
* @since 2.2.7
*/
export const lazy: <I, A>(id: string, f: () => Decoder<I, A>) => Decoder<I, A> =
/*#__PURE__*/
K.lazy(M)((id, e) => FS.of(DE.lazy(id, e)))
/**
* @category combinators
* @since 2.2.15
*/
export const readonly: <I, A>(decoder: Decoder<I, A>) => Decoder<I, Readonly<A>> = identity
/**
* @category combinators
* @since 2.2.17
*/
export const optional: <I, A>(or: Decoder<I, A>) => Decoder<I | undefined, O.Option<A>> = (or) => ({
decode: (i) => (i === undefined ? E.right(O.none) : pipe(i, or.decode, E.map(O.some)))
})
// -------------------------------------------------------------------------------------
// non-pipeables
// -------------------------------------------------------------------------------------
const map_: Functor2<URI>['map'] = (fa, f) => pipe(fa, map(f))
const alt_: Alt2<URI>['alt'] = (me, that) => pipe(me, alt(that))
const compose_: Category2<URI>['compose'] = (ab, la) => pipe(la, compose(ab))
// -------------------------------------------------------------------------------------
// pipeables
// -------------------------------------------------------------------------------------
/**
* @category Functor
* @since 2.2.7
*/
export const map: <A, B>(f: (a: A) => B) => <I>(fa: Decoder<I, A>) => Decoder<I, B> =
/*#__PURE__*/
K.map(M)
/**
* @category Alt
* @since 2.2.7
*/
export const alt: <I, A>(that: () => Decoder<I, A>) => (me: Decoder<I, A>) => Decoder<I, A> =
/*#__PURE__*/
K.alt(M)
/**
* @category Semigroupoid
* @since 2.2.8
*/
export const compose: <A, B>(to: Decoder<A, B>) => <I>(from: Decoder<I, A>) => Decoder<I, B> =
/*#__PURE__*/
K.compose(M)
/**
* @category Category
* @since 2.2.8
*/
export const id: <A>() => Decoder<A, A> =
/*#__PURE__*/
K.id(M)
// -------------------------------------------------------------------------------------
// instances
// -------------------------------------------------------------------------------------
/**
* @category instances
* @since 2.2.7
*/
export const URI = 'io-ts/Decoder'
/**
* @category instances
* @since 2.2.7
*/
export type URI = typeof URI
declare module 'fp-ts/lib/HKT' {
interface URItoKind2<E, A> {
readonly [URI]: Decoder<E, A>
}
}
/**
* @category instances
* @since 2.2.8
*/
export const Functor: Functor2<URI> = {
URI,
map: map_
}
/**
* @category instances
* @since 2.2.8
*/
export const Alt: Alt2<URI> = {
URI,
map: map_,
alt: alt_
}
/**
* @category instances
* @since 2.2.8
*/
export const Category: Category2<URI> = {
URI,
compose: compose_,
id
}
/**
* @category instances
* @since 2.2.8
*/
export const Schemable: S.Schemable2C<URI, unknown> = {
URI,
literal,
string,
number,
boolean,
nullable,
type,
struct,
partial,
record,
array,
tuple: tuple as S.Schemable2C<URI, unknown>['tuple'],
intersect,
sum,
lazy,
readonly
}
/**
* @category instances
* @since 2.2.8
*/
export const WithUnknownContainers: S.WithUnknownContainers2C<URI, unknown> = {
UnknownArray,
UnknownRecord
}
/**
* @category instances
* @since 2.2.8
*/
export const WithUnion: S.WithUnion2C<URI, unknown> = {
union: union as S.WithUnion2C<URI, unknown>['union']
}
/**
* @category instances
* @since 2.2.8
*/
export const WithRefine: S.WithRefine2C<URI, unknown> = {
refine: refine as S.WithRefine2C<URI, unknown>['refine']
}
// -------------------------------------------------------------------------------------
// utils
// -------------------------------------------------------------------------------------
/**
* @since 2.2.8
*/
export type InputOf<D> = K.InputOf<E.URI, D>
/**
* @since 2.2.7
*/
export type TypeOf<D> = K.TypeOf<E.URI, D>
interface Tree<A> {
readonly value: A
readonly forest: ReadonlyArray<Tree<A>>
}
const empty: Array<never> = []
const make = <A>(value: A, forest: ReadonlyArray<Tree<A>> = empty): Tree<A> => ({
value,
forest
})
const drawTree = (tree: Tree<string>): string => tree.value + drawForest('\n', tree.forest)
const drawForest = (indentation: string, forest: ReadonlyArray<Tree<string>>): string => {
let r = ''
const len = forest.length
let tree: Tree<string>
for (let i = 0; i < len; i++) {
tree = forest[i]
const isLast = i === len - 1
r += indentation + (isLast ? '└' : '├') + '─ ' + tree.value
r += drawForest(indentation + (len > 1 && !isLast ? '│ ' : ' '), tree.forest)
}
return r
}
const toTree: (e: DE.DecodeError<string>) => Tree<string> = DE.fold({
Leaf: (input, error) => make(`cannot decode ${JSON.stringify(input)}, should be ${error}`),
Key: (key, kind, errors) => make(`${kind} property ${JSON.stringify(key)}`, toForest(errors)),
Index: (index, kind, errors) => make(`${kind} index ${index}`, toForest(errors)),
Member: (index, errors) => make(`member ${index}`, toForest(errors)),
Lazy: (id, errors) => make(`lazy type ${id}`, toForest(errors)),
Wrap: (error, errors) => make(error, toForest(errors))
})
const toForest = (e: DecodeError): ReadonlyArray<Tree<string>> => {
const stack = []
let focus = e
const res = []
while (true) {
switch (focus._tag) {
case 'Of':
res.push(toTree(focus.value))
const tmp = stack.pop()
if (tmp === undefined) {
return res
} else {
focus = tmp
}
break
case 'Concat':
stack.push(focus.right)
focus = focus.left
break
}
}
}
/**
* @since 2.2.7
*/
export const draw = (e: DecodeError): string => toForest(e).map(drawTree).join('\n')
/**
* @internal
*/
export const stringify: <A>(e: E.Either<DecodeError, A>) => string =
/*#__PURE__*/
E.fold(draw, (a) => JSON.stringify(a, null, 2))