decoders 2.0.0-beta6 → 2.0.0-beta7

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.
Files changed (123) hide show
  1. package/NotSupportedTSVersion.d.ts +1 -0
  2. package/_guard.d.ts +7 -0
  3. package/_guard.js +2 -6
  4. package/_guard.js.flow +3 -3
  5. package/{_esm/_guard.js → _guard.mjs} +3 -3
  6. package/_types.d.ts +13 -0
  7. package/{_esm/_types.js → _types.mjs} +0 -0
  8. package/_utils.d.ts +10 -0
  9. package/{_esm/_utils.js → _utils.mjs} +0 -0
  10. package/annotate.d.ts +62 -0
  11. package/{_esm/annotate.js → annotate.mjs} +0 -0
  12. package/core/_helpers.d.ts +79 -0
  13. package/core/array.d.ts +5 -0
  14. package/core/array.js +5 -9
  15. package/core/array.js.flow +5 -5
  16. package/{_esm/core/array.js → core/array.mjs} +7 -7
  17. package/core/boolean.d.ts +5 -0
  18. package/core/boolean.js +4 -8
  19. package/core/boolean.js.flow +3 -5
  20. package/{_esm/core/boolean.js → core/boolean.mjs} +6 -6
  21. package/core/composition.d.ts +12 -0
  22. package/core/composition.js +6 -10
  23. package/core/composition.js.flow +6 -6
  24. package/{_esm/core/composition.js → core/composition.mjs} +7 -7
  25. package/core/constants.d.ts +11 -0
  26. package/core/constants.js +6 -10
  27. package/core/constants.js.flow +7 -9
  28. package/{_esm/core/constants.js → core/constants.mjs} +7 -7
  29. package/core/date.d.ts +4 -0
  30. package/core/date.js +3 -7
  31. package/core/date.js.flow +2 -4
  32. package/{_esm/core/date.js → core/date.mjs} +6 -6
  33. package/core/describe.d.ts +3 -0
  34. package/core/describe.js +2 -6
  35. package/core/describe.js.flow +2 -2
  36. package/{_esm/core/describe.js → core/describe.mjs} +3 -3
  37. package/core/dispatch.d.ts +8 -0
  38. package/core/dispatch.js +2 -6
  39. package/core/dispatch.js.flow +2 -2
  40. package/{_esm/core/dispatch.js → core/dispatch.mjs} +4 -4
  41. package/core/either.d.ts +61 -0
  42. package/core/either.js +7 -11
  43. package/core/either.js.flow +6 -6
  44. package/{_esm/core/either.js → core/either.mjs} +8 -8
  45. package/core/fail.d.ts +3 -0
  46. package/core/fail.js +2 -6
  47. package/core/fail.js.flow +2 -2
  48. package/{_esm/core/fail.js → core/fail.mjs} +3 -3
  49. package/core/instanceOf.d.ts +3 -0
  50. package/core/instanceOf.js +2 -6
  51. package/core/instanceOf.js.flow +3 -3
  52. package/core/instanceOf.mjs +8 -0
  53. package/core/json.d.ts +11 -0
  54. package/core/json.mjs +15 -0
  55. package/core/lazy.d.ts +3 -0
  56. package/{_esm/core/lazy.js → core/lazy.mjs} +0 -0
  57. package/core/mapping.d.ts +6 -0
  58. package/core/mapping.js +4 -8
  59. package/core/mapping.js.flow +3 -3
  60. package/{_esm/core/mapping.js → core/mapping.mjs} +7 -7
  61. package/core/number.d.ts +6 -0
  62. package/core/number.js +2 -6
  63. package/core/number.js.flow +3 -3
  64. package/{_esm/core/number.js → core/number.mjs} +4 -4
  65. package/core/object.d.ts +33 -0
  66. package/core/object.js +7 -11
  67. package/core/object.js.flow +7 -7
  68. package/{_esm/core/object.js → core/object.mjs} +9 -9
  69. package/core/optional.d.ts +5 -0
  70. package/core/optional.js +4 -8
  71. package/core/optional.js.flow +3 -3
  72. package/{_esm/core/optional.js → core/optional.mjs} +6 -6
  73. package/core/string.d.ts +7 -0
  74. package/core/string.js +5 -9
  75. package/core/string.js.flow +5 -7
  76. package/{_esm/core/string.js → core/string.mjs} +7 -7
  77. package/core/tuple.d.ts +30 -0
  78. package/{_esm/core/tuple.js → core/tuple.mjs} +4 -4
  79. package/format.d.ts +4 -0
  80. package/{format/inline.js → format.js} +6 -1
  81. package/{_esm/format/inline.js.flow → format.js.flow} +6 -2
  82. package/{_esm/format/inline.js → format.mjs} +4 -1
  83. package/{_esm/index.js.flow → index.d.ts} +3 -23
  84. package/{_esm/index.js → index.mjs} +19 -19
  85. package/package.json +15 -3
  86. package/result.d.ts +39 -0
  87. package/result.js +0 -62
  88. package/result.js.flow +0 -60
  89. package/{_esm/result.js → result.mjs} +0 -54
  90. package/_esm/_guard.js.flow +0 -20
  91. package/_esm/_types.js.flow +0 -20
  92. package/_esm/_utils.js.flow +0 -97
  93. package/_esm/annotate.js.flow +0 -218
  94. package/_esm/core/array.js.flow +0 -103
  95. package/_esm/core/boolean.js.flow +0 -29
  96. package/_esm/core/composition.js.flow +0 -43
  97. package/_esm/core/constants.js.flow +0 -46
  98. package/_esm/core/date.js.flow +0 -40
  99. package/_esm/core/describe.js.flow +0 -17
  100. package/_esm/core/dispatch.js.flow +0 -58
  101. package/_esm/core/either.js.flow +0 -151
  102. package/_esm/core/fail.js.flow +0 -12
  103. package/_esm/core/instanceOf.js +0 -8
  104. package/_esm/core/instanceOf.js.flow +0 -20
  105. package/_esm/core/json.js +0 -15
  106. package/_esm/core/json.js.flow +0 -28
  107. package/_esm/core/lazy.js.flow +0 -15
  108. package/_esm/core/mapping.js.flow +0 -54
  109. package/_esm/core/number.js.flow +0 -34
  110. package/_esm/core/object.js.flow +0 -203
  111. package/_esm/core/optional.js.flow +0 -41
  112. package/_esm/core/string.js.flow +0 -82
  113. package/_esm/core/tuple.js.flow +0 -214
  114. package/_esm/format/index.js +0 -2
  115. package/_esm/format/index.js.flow +0 -4
  116. package/_esm/format/short.js +0 -4
  117. package/_esm/format/short.js.flow +0 -8
  118. package/_esm/result.js.flow +0 -158
  119. package/format/index.js +0 -12
  120. package/format/index.js.flow +0 -4
  121. package/format/inline.js.flow +0 -122
  122. package/format/short.js +0 -10
  123. package/format/short.js.flow +0 -8
@@ -1,151 +0,0 @@
1
- // @flow strict
2
-
3
- import * as Result from '../result';
4
- import { annotate } from '../annotate';
5
- import { indent, summarize } from '../_utils';
6
- import type { Decoder, Scalar } from '../_types';
7
-
8
- /**
9
- * Indents and adds a dash in front of this (potentially multiline) string.
10
- */
11
- function itemize(s: string): string {
12
- return '-' + indent(s).substring(1);
13
- }
14
-
15
- /**
16
- * Nests another error as an item under a new-to-be-created "Either error". If
17
- * the given subitem already is an "Either error" of itself, don't indent, but
18
- * just "inject" its items at the same error level, for nicely flattened either
19
- * expressions.
20
- *
21
- * Avoids:
22
- *
23
- * Either:
24
- * - Either:
25
- * - Must be P
26
- * - Either:
27
- * - Must be Q
28
- * - Must be R
29
- * - Must be S
30
- *
31
- * And "flattens" these to:
32
- *
33
- * Either:
34
- * - Must be P
35
- * - Must be Q
36
- * - Must be R
37
- * - Must be S
38
- *
39
- */
40
- function nest(errText: string): string {
41
- const EITHER_PREFIX = 'Either:\n';
42
- return errText.startsWith(EITHER_PREFIX)
43
- ? errText.substr(EITHER_PREFIX.length)
44
- : itemize(errText);
45
- }
46
-
47
- export function either<T1, T2>(d1: Decoder<T1>, d2: Decoder<T2>): Decoder<T1 | T2> {
48
- return (blob: mixed) =>
49
- Result.orElse(d1(blob), (err1) =>
50
- Result.orElse(d2(blob), (err2) => {
51
- const serr1 = summarize(err1).join('\n');
52
- const serr2 = summarize(err2).join('\n');
53
- const text = ['Either:', nest(serr1), nest(serr2)].join('\n');
54
- return Result.err(annotate(blob, text));
55
- }),
56
- );
57
- }
58
-
59
- export function either3<T1, T2, T3>(
60
- d1: Decoder<T1>,
61
- d2: Decoder<T2>,
62
- d3: Decoder<T3>,
63
- ): Decoder<T1 | T2 | T3> {
64
- return either(d1, either(d2, d3));
65
- }
66
-
67
- export function either4<T1, T2, T3, T4>(
68
- d1: Decoder<T1>,
69
- d2: Decoder<T2>,
70
- d3: Decoder<T3>,
71
- d4: Decoder<T4>,
72
- ): Decoder<T1 | T2 | T3 | T4> {
73
- return either(d1, either3(d2, d3, d4));
74
- }
75
-
76
- export function either5<T1, T2, T3, T4, T5>(
77
- d1: Decoder<T1>,
78
- d2: Decoder<T2>,
79
- d3: Decoder<T3>,
80
- d4: Decoder<T4>,
81
- d5: Decoder<T5>,
82
- ): Decoder<T1 | T2 | T3 | T4 | T5> {
83
- return either(d1, either4(d2, d3, d4, d5));
84
- }
85
-
86
- export function either6<T1, T2, T3, T4, T5, T6>(
87
- d1: Decoder<T1>,
88
- d2: Decoder<T2>,
89
- d3: Decoder<T3>,
90
- d4: Decoder<T4>,
91
- d5: Decoder<T5>,
92
- d6: Decoder<T6>,
93
- ): Decoder<T1 | T2 | T3 | T4 | T5 | T6> {
94
- return either(d1, either5(d2, d3, d4, d5, d6));
95
- }
96
-
97
- export function either7<T1, T2, T3, T4, T5, T6, T7>(
98
- d1: Decoder<T1>,
99
- d2: Decoder<T2>,
100
- d3: Decoder<T3>,
101
- d4: Decoder<T4>,
102
- d5: Decoder<T5>,
103
- d6: Decoder<T6>,
104
- d7: Decoder<T7>,
105
- ): Decoder<T1 | T2 | T3 | T4 | T5 | T6 | T7> {
106
- return either(d1, either6(d2, d3, d4, d5, d6, d7));
107
- }
108
-
109
- export function either8<T1, T2, T3, T4, T5, T6, T7, T8>(
110
- d1: Decoder<T1>,
111
- d2: Decoder<T2>,
112
- d3: Decoder<T3>,
113
- d4: Decoder<T4>,
114
- d5: Decoder<T5>,
115
- d6: Decoder<T6>,
116
- d7: Decoder<T7>,
117
- d8: Decoder<T8>,
118
- ): Decoder<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8> {
119
- return either(d1, either7(d2, d3, d4, d5, d6, d7, d8));
120
- }
121
-
122
- export function either9<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
123
- d1: Decoder<T1>,
124
- d2: Decoder<T2>,
125
- d3: Decoder<T3>,
126
- d4: Decoder<T4>,
127
- d5: Decoder<T5>,
128
- d6: Decoder<T6>,
129
- d7: Decoder<T7>,
130
- d8: Decoder<T8>,
131
- d9: Decoder<T9>,
132
- ): Decoder<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9> {
133
- return either(d1, either8(d2, d3, d4, d5, d6, d7, d8, d9));
134
- }
135
-
136
- export function oneOf<T: Scalar>(constants: $ReadOnlyArray<T>): Decoder<T> {
137
- return (blob: mixed) => {
138
- const winner = constants.find((c) => c === blob);
139
- if (winner !== undefined) {
140
- return Result.ok(winner);
141
- }
142
- return Result.err(
143
- annotate(
144
- blob,
145
- `Must be one of ${constants
146
- .map((value) => JSON.stringify(value))
147
- .join(', ')}`,
148
- ),
149
- );
150
- };
151
- }
@@ -1,12 +0,0 @@
1
- // @flow strict
2
-
3
- import * as Result from '../result';
4
- import { annotate } from '../annotate';
5
- import type { Decoder } from '../_types';
6
-
7
- /**
8
- * Decoder that always fails with the given error message, no matter what the input.
9
- */
10
- export function fail(msg: string): Decoder<empty> {
11
- return (blob: mixed) => Result.err(annotate(blob, msg));
12
- }
@@ -1,8 +0,0 @@
1
- import * as Result from '../result';
2
- import { annotate } from '../annotate';
3
- export function instanceOf(klass) {
4
- return function (blob) {
5
- return blob instanceof klass ? Result.ok(blob) : Result.err(annotate(blob, "Must be " + // $FlowFixMe[incompatible-use] - klass.name is fine?
6
- klass.name + " instance"));
7
- };
8
- }
@@ -1,20 +0,0 @@
1
- // @flow strict
2
-
3
- import * as Result from '../result';
4
- import { annotate } from '../annotate';
5
- import type { Decoder } from '../_types';
6
-
7
- export function instanceOf<T>(klass: Class<T>): Decoder<T> {
8
- return (blob: mixed) =>
9
- blob instanceof klass
10
- ? Result.ok(blob)
11
- : Result.err(
12
- annotate(
13
- blob,
14
- `Must be ${
15
- // $FlowFixMe[incompatible-use] - klass.name is fine?
16
- klass.name
17
- } instance`,
18
- ),
19
- );
20
- }
package/_esm/core/json.js DELETED
@@ -1,15 +0,0 @@
1
- import { array } from './array';
2
- import { boolean as _boolean } from './boolean';
3
- import { dict } from './mapping';
4
- import { either6 } from './either';
5
- import { lazy } from './lazy';
6
- import { null_ } from './constants';
7
- import { number } from './number';
8
- import { string } from './string';
9
- export var jsonObject = lazy(function () {
10
- return dict(json);
11
- });
12
- export var jsonArray = lazy(function () {
13
- return array(json);
14
- });
15
- export var json = either6(null_, string, number, _boolean, jsonObject, jsonArray);
@@ -1,28 +0,0 @@
1
- // @flow strict
2
-
3
- import { array } from './array';
4
- import { boolean } from './boolean';
5
- import { dict } from './mapping';
6
- import { either6 } from './either';
7
- import { lazy } from './lazy';
8
- import { null_ } from './constants';
9
- import { number } from './number';
10
- import { string } from './string';
11
- import type { Decoder } from '../_types';
12
-
13
- export type JSONValue = null | string | number | boolean | JSONObject | JSONArray;
14
- export type JSONObject = { [string]: JSONValue };
15
- export type JSONArray = Array<JSONValue>;
16
-
17
- export const jsonObject: Decoder<JSONObject> = lazy(() => dict(json));
18
-
19
- export const jsonArray: Decoder<JSONArray> = lazy(() => array(json));
20
-
21
- export const json: Decoder<JSONValue> = either6(
22
- null_,
23
- string,
24
- number,
25
- boolean,
26
- jsonObject,
27
- jsonArray,
28
- );
@@ -1,15 +0,0 @@
1
- // @flow strict
2
-
3
- import type { Decoder } from '../_types';
4
-
5
- /**
6
- * Given an function returning a Decoder, will use that decoder to decode the
7
- * value. This is typically used to build decoders for recursive or
8
- * self-referential types.
9
- */
10
- export function lazy<T>(decoderFn: () => Decoder<T>): Decoder<T> {
11
- return (blob: mixed) => {
12
- const decoder = decoderFn();
13
- return decoder(blob);
14
- };
15
- }
@@ -1,54 +0,0 @@
1
- // @flow strict
2
-
3
- import * as Result from '../result';
4
- import { annotateObject } from '../annotate';
5
- import { compose, map } from './composition';
6
- import { merge } from '../annotate';
7
- import { pojo } from './object';
8
- import type { Annotation } from '../annotate';
9
- import type { Decoder } from '../_types';
10
-
11
- /**
12
- * Given an object, will decode a Map of string keys to whatever values.
13
- *
14
- * For example, given a decoder for a Person, we can verify a Person lookup
15
- * table structure (of type Map<string, Person>) like so:
16
- *
17
- * mapping(person)
18
- *
19
- */
20
- export function mapping<T>(decoder: Decoder<T>): Decoder<Map<string, T>> {
21
- return compose(pojo, (blob: { +[key: string]: mixed }) => {
22
- let tuples: Array<[string, T]> = [];
23
- let errors: { [key: string]: Annotation } | null = null;
24
-
25
- Object.keys(blob).forEach((key: string) => {
26
- const value = blob[key];
27
- const result = decoder(value);
28
- if (result.type === 'ok') {
29
- if (errors === null) {
30
- tuples.push([key, result.value]);
31
- }
32
- } else {
33
- tuples.length = 0; // Clear the tuples array
34
- if (errors === null) {
35
- errors = {};
36
- }
37
- errors[key] = result.error;
38
- }
39
- });
40
-
41
- if (errors !== null) {
42
- return Result.err(merge(annotateObject(blob), errors));
43
- } else {
44
- return Result.ok(new Map(tuples));
45
- }
46
- });
47
- }
48
-
49
- /**
50
- * Like mapping(), but returns an object rather than a Map instance.
51
- */
52
- export function dict<T>(decoder: Decoder<T>): Decoder<{ [string]: T }> {
53
- return map(mapping(decoder), (m) => Object.fromEntries(m));
54
- }
@@ -1,34 +0,0 @@
1
- // @flow strict
2
-
3
- import * as Result from '../result';
4
- import { annotate } from '../annotate';
5
- import { compose, predicate } from './composition';
6
- import type { Decoder } from '../_types';
7
-
8
- const anyNumber: Decoder<number> = (blob: mixed) => {
9
- return typeof blob === 'number' && !Number.isNaN(blob)
10
- ? Result.ok(blob)
11
- : Result.err(annotate(blob, 'Must be number'));
12
- };
13
-
14
- const isInteger = (n: number) => Number.isInteger(n);
15
- const isFinite = (n: number) => Number.isFinite(n);
16
-
17
- export const number: Decoder<number> = compose(
18
- anyNumber,
19
- predicate(isFinite, 'Number must be finite'),
20
- );
21
- export const positiveNumber: Decoder<number> = compose(
22
- number,
23
- predicate((n) => n >= 0, 'Number must be positive'),
24
- );
25
-
26
- // Integers
27
- export const integer: Decoder<number> = compose(
28
- number,
29
- predicate(isInteger, 'Number must be an integer'),
30
- );
31
- export const positiveInteger: Decoder<number> = compose(
32
- integer,
33
- predicate((n) => n >= 0, 'Number must be positive'),
34
- );
@@ -1,203 +0,0 @@
1
- // @flow strict
2
-
3
- import * as Result from '../result';
4
- import { annotate, annotateObject, merge, updateText } from '../annotate';
5
- import { compose, map } from './composition';
6
- import type { Annotation } from '../annotate';
7
- import type { Decoder, DecoderType } from '../_types';
8
-
9
- // $FlowFixMe[unclear-type] (not really an issue) - deliberate use of `any` - not sure how we should get rid of this
10
- type AnyDecoder = any;
11
-
12
- // $FlowFixMe[unclear-type] (not really an issue) - deliberately casting
13
- type cast = any;
14
-
15
- function isPojo(o: mixed): boolean %checks {
16
- return (
17
- o !== null &&
18
- o !== undefined &&
19
- typeof o === 'object' &&
20
- // This still seems to be the only reliable way to determine whether
21
- // something is a pojo... ¯\_(ツ)_/¯
22
- // $FlowFixMe[method-unbinding]
23
- Object.prototype.toString.call(o) === '[object Object]'
24
- );
25
- }
26
-
27
- function subtract(xs: Set<string>, ys: Set<string>): Set<string> {
28
- const result = new Set();
29
- xs.forEach((x) => {
30
- if (!ys.has(x)) {
31
- result.add(x);
32
- }
33
- });
34
- return result;
35
- }
36
-
37
- export const pojo: Decoder<{| [string]: mixed |}> = (blob: mixed) => {
38
- return isPojo(blob)
39
- ? Result.ok(
40
- // NOTE:
41
- // Since Flow 0.98, typeof o === 'object' refines to
42
- // {| +[string]: mixed |}
43
- // instead of
44
- // {| [string]: mixed |}
45
- //
46
- // For rationale, see https://github.com/facebook/flow/issues/7685.
47
- // In this case, we don't want to output a read-only version of
48
- // the object because it's up to the user of decoders to
49
- // determine what they want to do with the decoded output. If they
50
- // want to write items into the array, that's fine! The fastest
51
- // way to turn a read-only Object to a writeable one in ES6 seems
52
- // to be to use object-spread. (Going off this benchmark:
53
- // https://thecodebarbarian.com/object-assign-vs-object-spread.html)
54
- { ...blob },
55
- )
56
- : Result.err(annotate(blob, 'Must be an object'));
57
- };
58
-
59
- /**
60
- * Given a mapping of fields-to-decoders, builds a decoder for an object type.
61
- *
62
- * For example, given decoders for a number and a string, we can construct an
63
- * "object description" like so:
64
- *
65
- * { id: number, name: string }
66
- *
67
- * Which is of type:
68
- *
69
- * { id: Decoder<number>, name: Decoder<string> }
70
- *
71
- * Passing this to object() will produce the following return type:
72
- *
73
- * Decoder<{ id: number, name: string }>
74
- *
75
- * Put simply: it'll "peel off" all of the nested Decoders, puts them together
76
- * in an object, and wraps it in a Decoder<...>.
77
- */
78
- export function object<O: { +[field: string]: AnyDecoder, ... }>(
79
- mapping: O,
80
- ): Decoder<$ObjMap<O, DecoderType>> {
81
- const known = new Set(Object.keys(mapping));
82
- return compose(pojo, (blob: { +[string]: mixed }) => {
83
- const actual = new Set(Object.keys(blob));
84
-
85
- // At this point, "missing" will also include all fields that may
86
- // validly be optional. We'll let the underlying decoder decide and
87
- // remove the key from this missing set if the decoder accepts the
88
- // value.
89
- const missing = subtract(known, actual);
90
-
91
- let record = {};
92
- let errors: { [key: string]: Annotation } | null = null;
93
-
94
- Object.keys(mapping).forEach((key) => {
95
- const decoder = mapping[key];
96
- const rawValue = blob[key];
97
- const result = decoder(rawValue);
98
-
99
- if (result.type === 'ok') {
100
- const value = result.value;
101
- if (value !== undefined) {
102
- record[key] = value;
103
- }
104
-
105
- // If this succeeded, remove the key from the missing keys
106
- // tracker
107
- missing.delete(key);
108
- } else {
109
- const ann = result.error;
110
-
111
- // Keep track of the annotation, but don't return just yet. We
112
- // want to collect more error information.
113
- if (rawValue === undefined) {
114
- // Explicitly add it to the missing set if the value is
115
- // undefined. This covers explicit undefineds to be
116
- // treated the same as implicit undefineds (aka missing
117
- // keys).
118
- missing.add(key);
119
- } else {
120
- if (errors === null) {
121
- errors = {};
122
- }
123
- errors[key] = ann;
124
- }
125
- }
126
- });
127
-
128
- // Deal with errors now. There are two classes of errors we want to
129
- // report. First of all, we want to report any inline errors in this
130
- // object. Lastly, any fields that are missing should be annotated on
131
- // the outer object itself.
132
- if (errors || missing.size > 0) {
133
- let objAnn = annotateObject(blob);
134
-
135
- if (errors) {
136
- objAnn = merge(objAnn, errors);
137
- }
138
-
139
- if (missing.size > 0) {
140
- const errMsg = Array.from(missing)
141
- .map((key) => `"${key}"`)
142
- .join(', ');
143
- const pluralized = missing.size > 1 ? 'keys' : 'key';
144
- objAnn = updateText(objAnn, `Missing ${pluralized}: ${errMsg}`);
145
- }
146
-
147
- return Result.err(objAnn);
148
- }
149
-
150
- return Result.ok(record);
151
- });
152
- }
153
-
154
- export function exact<O: { +[field: string]: AnyDecoder, ... }>(
155
- mapping: O,
156
- ): Decoder<$ObjMap<$Exact<O>, DecoderType>> {
157
- // Check the inputted object for any superfluous keys
158
- const allowed = new Set(Object.keys(mapping));
159
- const checked = compose(pojo, (blob: {| [string]: mixed |}) => {
160
- const actual = new Set(Object.keys(blob));
161
- const superfluous = subtract(actual, allowed);
162
- if (superfluous.size > 0) {
163
- return Result.err(
164
- annotate(blob, `Superfluous keys: ${Array.from(superfluous).join(', ')}`),
165
- );
166
- }
167
- return Result.ok(blob);
168
- });
169
-
170
- // Defer to the "object" decoder for doing the real decoding work. Since
171
- // we made sure there are no superfluous keys in this structure, it's now
172
- // safe to force-cast it to an $Exact<> type.
173
- const decoder = ((object(mapping): cast): Decoder<$ObjMap<$Exact<O>, DecoderType>>);
174
- return compose(checked, decoder);
175
- }
176
-
177
- export function inexact<O: { +[field: string]: AnyDecoder }>(
178
- mapping: O,
179
- ): Decoder<$ObjMap<O, DecoderType> & { +[string]: mixed }> {
180
- return compose(pojo, (blob: {| [string]: mixed |}) => {
181
- const allkeys = new Set(Object.keys(blob));
182
- const decoder = map(object(mapping), (safepart: $ObjMap<O, DecoderType>) => {
183
- const safekeys = new Set(Object.keys(mapping));
184
-
185
- // To account for hard-coded keys that aren't part of the input
186
- safekeys.forEach((k) => allkeys.add(k));
187
-
188
- const rv = {};
189
- allkeys.forEach((k) => {
190
- if (safekeys.has(k)) {
191
- const value = safepart[k];
192
- if (value !== undefined) {
193
- rv[k] = value;
194
- }
195
- } else {
196
- rv[k] = blob[k];
197
- }
198
- });
199
- return rv;
200
- });
201
- return decoder(blob);
202
- });
203
- }
@@ -1,41 +0,0 @@
1
- // @flow strict
2
-
3
- import * as Result from '../result';
4
- import { annotate } from '../annotate';
5
- import { either } from './either';
6
- import { null_, undefined_ } from './constants';
7
- import type { Decoder } from '../_types';
8
-
9
- /**
10
- * Builds a Decoder that returns Ok for either `undefined` or `T` values,
11
- * given a Decoder for `T`. Err otherwise.
12
- */
13
- export function optional<T>(decoder: Decoder<T>): Decoder<void | T> {
14
- return either(undefined_, decoder);
15
- }
16
-
17
- /**
18
- * Builds a Decoder that returns Ok for either `null` or `T` values,
19
- * given a Decoder for `T`. Err otherwise.
20
- */
21
- export function nullable<T>(decoder: Decoder<T>): Decoder<null | T> {
22
- return either(null_, decoder);
23
- }
24
-
25
- /**
26
- * Decoder that only returns Ok for `null` or `undefined` inputs.
27
- * This is effectively equivalent to either(null_, undefined_), but combines
28
- * their error message output into a single line for convenience.
29
- */
30
- const undefined_or_null: Decoder<null | void> = (blob: mixed) =>
31
- blob === undefined || blob === null
32
- ? Result.ok(blob)
33
- : // Combine error message into a single line
34
- Result.err(annotate(blob, 'Must be undefined or null'));
35
-
36
- /**
37
- * Decoder that only returns Ok for `null` or `undefined` inputs.
38
- */
39
- export function maybe<T>(decoder: Decoder<T>): Decoder<?T> {
40
- return either(undefined_or_null, decoder);
41
- }
@@ -1,82 +0,0 @@
1
- // @flow strict
2
-
3
- import * as Result from '../result';
4
- import { annotate } from '../annotate';
5
- import { compose, predicate } from './composition';
6
- import type { Decoder } from '../_types';
7
-
8
- /** Match groups in this regex:
9
- * \1 - the scheme
10
- * \2 - the username/password (optional)
11
- * \3 - the host
12
- * \4 - the port (optional)
13
- * \5 - the path (optional)
14
- */
15
- const url_re =
16
- /^([A-Za-z]{3,9}(?:[+][A-Za-z]{3,9})?):\/\/(?:([-;:&=+$,\w]+)@)?(?:([A-Za-z0-9.-]+)(?::([0-9]{2,5}))?)(\/(?:[-+~%/.,\w]*)?(?:\?[-+=&;%@.,\w]*)?(?:#[.,!/\w]*)?)?$/;
17
-
18
- // The URL schemes the url() decoder accepts by default
19
- const DEFAULT_SCHEMES = ['https'];
20
-
21
- /**
22
- * Decoder that only returns Ok for string inputs. Err otherwise.
23
- */
24
- export const string: Decoder<string> = (blob: mixed) => {
25
- return typeof blob === 'string'
26
- ? Result.ok(blob)
27
- : Result.err(annotate(blob, 'Must be string'));
28
- };
29
-
30
- /**
31
- * Decoder that only returns Ok for non-empty string inputs. Err otherwise.
32
- */
33
- export const nonEmptyString: Decoder<string> = regex(/\S/, 'Must be non-empty string');
34
-
35
- /**
36
- * Decoder that only returns Ok for string inputs that match the regular
37
- * expression. Err otherwise. Will always validate that the input is a string
38
- * before testing the regex.
39
- */
40
- export function regex(regex: RegExp, msg: string): Decoder<string> {
41
- return compose(
42
- string,
43
- predicate((s) => regex.test(s), msg),
44
- );
45
- }
46
-
47
- /**
48
- * Decoder that only returns Ok for string inputs that match the almost perfect
49
- * email regex, taken from http://emailregex.com. Err otherwise.
50
- */
51
- export const email: Decoder<string> = regex(
52
- /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
53
- 'Must be email',
54
- );
55
-
56
- /**
57
- * Decoder that only returns Ok for string inputs that match URLs of the
58
- * expected scheme. Defaults to only accept HTTPS URLs. Err otherwise.
59
- *
60
- * Variants that can be used:
61
- *
62
- * - url() accepts only https:// URLs
63
- * - url([]) accepts any URL scheme
64
- * - url(['http']) accepts only HTTP
65
- * - url(['https', 'git+ssh']) accepts both https:// and git+ssh:// URLs
66
- */
67
- export const url = (schemes: $ReadOnlyArray<string> = DEFAULT_SCHEMES): Decoder<string> =>
68
- compose(string, (value: string) => {
69
- const matches = value.match(url_re);
70
- if (!matches) {
71
- return Result.err(annotate(value, 'Must be URL'));
72
- } else {
73
- const scheme = matches[1];
74
- if (schemes.length === 0 || schemes.includes(scheme.toLowerCase())) {
75
- return Result.ok(value);
76
- } else {
77
- return Result.err(
78
- annotate(value, `URL scheme must be any of: ${schemes.join(', ')}`),
79
- );
80
- }
81
- }
82
- });