decoders 2.0.0-beta1 → 2.0.0-beta5

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 (136) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/{es → _esm}/_guard.js +0 -0
  3. package/{cjs → _esm}/_guard.js.flow +0 -0
  4. package/{es → _esm}/_types.js +0 -0
  5. package/{cjs → _esm}/_types.js.flow +0 -0
  6. package/{es → _esm}/_utils.js +0 -0
  7. package/{cjs → _esm}/_utils.js.flow +0 -0
  8. package/{es → _esm}/annotate.js +0 -0
  9. package/{cjs → _esm}/annotate.js.flow +0 -0
  10. package/{es/stdlib → _esm/core}/array.js +0 -0
  11. package/{cjs/stdlib → _esm/core}/array.js.flow +0 -0
  12. package/{es/stdlib → _esm/core}/boolean.js +0 -0
  13. package/{cjs/stdlib → _esm/core}/boolean.js.flow +0 -0
  14. package/{es/stdlib → _esm/core}/composition.js +0 -0
  15. package/{cjs/stdlib → _esm/core}/composition.js.flow +0 -0
  16. package/{es/stdlib → _esm/core}/constants.js +0 -0
  17. package/{cjs/stdlib → _esm/core}/constants.js.flow +0 -0
  18. package/{es/stdlib → _esm/core}/date.js +0 -0
  19. package/{cjs/stdlib → _esm/core}/date.js.flow +0 -0
  20. package/{es/stdlib → _esm/core}/describe.js +0 -0
  21. package/{cjs/stdlib → _esm/core}/describe.js.flow +0 -0
  22. package/{es/stdlib → _esm/core}/dispatch.js +0 -0
  23. package/{cjs/stdlib → _esm/core}/dispatch.js.flow +0 -0
  24. package/{es/stdlib → _esm/core}/either.js +0 -0
  25. package/{cjs/stdlib → _esm/core}/either.js.flow +0 -0
  26. package/{es/stdlib → _esm/core}/fail.js +0 -0
  27. package/{cjs/stdlib → _esm/core}/fail.js.flow +0 -0
  28. package/{es/stdlib → _esm/core}/instanceOf.js +0 -0
  29. package/{cjs/stdlib → _esm/core}/instanceOf.js.flow +0 -0
  30. package/{es/stdlib → _esm/core}/json.js +0 -0
  31. package/{cjs/stdlib → _esm/core}/json.js.flow +0 -0
  32. package/{es/stdlib → _esm/core}/lazy.js +0 -0
  33. package/{cjs/stdlib → _esm/core}/lazy.js.flow +0 -0
  34. package/{es/stdlib → _esm/core}/mapping.js +0 -0
  35. package/{cjs/stdlib → _esm/core}/mapping.js.flow +0 -0
  36. package/{es/stdlib → _esm/core}/number.js +0 -0
  37. package/{cjs/stdlib → _esm/core}/number.js.flow +0 -0
  38. package/{es/stdlib → _esm/core}/object.js +0 -0
  39. package/{cjs/stdlib → _esm/core}/object.js.flow +0 -0
  40. package/{es/stdlib → _esm/core}/optional.js +0 -0
  41. package/{cjs/stdlib → _esm/core}/optional.js.flow +0 -0
  42. package/{es/stdlib → _esm/core}/string.js +0 -0
  43. package/{cjs/stdlib → _esm/core}/string.js.flow +0 -0
  44. package/{es/stdlib → _esm/core}/tuple.js +7 -7
  45. package/{cjs/stdlib → _esm/core}/tuple.js.flow +21 -26
  46. package/{es → _esm}/format/index.js +0 -0
  47. package/{cjs → _esm}/format/index.js.flow +0 -0
  48. package/{es → _esm}/format/inline.js +0 -0
  49. package/{cjs → _esm}/format/inline.js.flow +0 -0
  50. package/{es → _esm}/format/short.js +0 -0
  51. package/{cjs → _esm}/format/short.js.flow +0 -0
  52. package/{es → _esm}/index.js +18 -18
  53. package/{cjs → _esm}/index.js.flow +29 -29
  54. package/{es → _esm}/result.js +14 -5
  55. package/{cjs → _esm}/result.js.flow +14 -6
  56. package/{cjs/_guard.js → _guard.js} +0 -0
  57. package/_guard.js.flow +20 -0
  58. package/{cjs/_types.js → _types.js} +0 -0
  59. package/_types.js.flow +20 -0
  60. package/{cjs/_utils.js → _utils.js} +0 -0
  61. package/_utils.js.flow +97 -0
  62. package/{cjs/annotate.js → annotate.js} +0 -0
  63. package/annotate.js.flow +218 -0
  64. package/{cjs/stdlib → core}/array.js +0 -0
  65. package/core/array.js.flow +103 -0
  66. package/{cjs/stdlib → core}/boolean.js +0 -0
  67. package/core/boolean.js.flow +29 -0
  68. package/{cjs/stdlib → core}/composition.js +0 -0
  69. package/core/composition.js.flow +43 -0
  70. package/{cjs/stdlib → core}/constants.js +0 -0
  71. package/core/constants.js.flow +46 -0
  72. package/{cjs/stdlib → core}/date.js +0 -0
  73. package/core/date.js.flow +40 -0
  74. package/{cjs/stdlib → core}/describe.js +0 -0
  75. package/core/describe.js.flow +17 -0
  76. package/{cjs/stdlib → core}/dispatch.js +0 -0
  77. package/core/dispatch.js.flow +58 -0
  78. package/{cjs/stdlib → core}/either.js +0 -0
  79. package/core/either.js.flow +151 -0
  80. package/{cjs/stdlib → core}/fail.js +0 -0
  81. package/core/fail.js.flow +12 -0
  82. package/{cjs/stdlib → core}/instanceOf.js +0 -0
  83. package/core/instanceOf.js.flow +20 -0
  84. package/{cjs/stdlib → core}/json.js +0 -0
  85. package/core/json.js.flow +28 -0
  86. package/{cjs/stdlib → core}/lazy.js +0 -0
  87. package/core/lazy.js.flow +15 -0
  88. package/{cjs/stdlib → core}/mapping.js +0 -0
  89. package/core/mapping.js.flow +54 -0
  90. package/{cjs/stdlib → core}/number.js +0 -0
  91. package/core/number.js.flow +34 -0
  92. package/{cjs/stdlib → core}/object.js +0 -0
  93. package/core/object.js.flow +203 -0
  94. package/{cjs/stdlib → core}/optional.js +0 -0
  95. package/core/optional.js.flow +41 -0
  96. package/{cjs/stdlib → core}/string.js +0 -0
  97. package/core/string.js.flow +82 -0
  98. package/{cjs/stdlib → core}/tuple.js +6 -6
  99. package/core/tuple.js.flow +215 -0
  100. package/{cjs/format → format}/index.js +0 -0
  101. package/format/index.js.flow +4 -0
  102. package/{cjs/format → format}/inline.js +0 -0
  103. package/format/inline.js.flow +122 -0
  104. package/{cjs/format → format}/short.js +0 -0
  105. package/format/short.js.flow +8 -0
  106. package/{cjs/index.js → index.js} +18 -18
  107. package/index.js.flow +63 -0
  108. package/package.json +3 -12
  109. package/{cjs/result.js → result.js} +18 -7
  110. package/result.js.flow +174 -0
  111. package/ts/_guard.d.ts +0 -7
  112. package/ts/_helpers.d.ts +0 -79
  113. package/ts/_types.d.ts +0 -16
  114. package/ts/_utils.d.ts +0 -13
  115. package/ts/annotate.d.ts +0 -58
  116. package/ts/array.d.ts +0 -5
  117. package/ts/boolean.d.ts +0 -5
  118. package/ts/constants.d.ts +0 -11
  119. package/ts/date.d.ts +0 -4
  120. package/ts/describe.d.ts +0 -3
  121. package/ts/dispatch.d.ts +0 -8
  122. package/ts/either.d.ts +0 -61
  123. package/ts/fail.d.ts +0 -3
  124. package/ts/index.d.ts +0 -42
  125. package/ts/inline.d.ts +0 -3
  126. package/ts/instanceOf.d.ts +0 -3
  127. package/ts/json.d.ts +0 -11
  128. package/ts/lazy.d.ts +0 -3
  129. package/ts/mapping.d.ts +0 -4
  130. package/ts/number.d.ts +0 -6
  131. package/ts/object.d.ts +0 -33
  132. package/ts/optional.d.ts +0 -5
  133. package/ts/result.d.ts +0 -39
  134. package/ts/short.d.ts +0 -3
  135. package/ts/string.d.ts +0 -7
  136. package/ts/tuple.d.ts +0 -30
package/_utils.js.flow ADDED
@@ -0,0 +1,97 @@
1
+ // @flow strict
2
+
3
+ import type { Annotation } from './annotate';
4
+
5
+ // $FlowFixMe[unclear-type] - deliberate casting
6
+ type cast = any;
7
+
8
+ // Two spaces of indentation
9
+ export const INDENT = ' ';
10
+
11
+ /**
12
+ * `x instanceof Date` checks are unreliable across stack frames (that information
13
+ * might get lost by the JS runtime), so we'll have to reside to more runtime
14
+ * inspection checks.
15
+ *
16
+ * Taken from https://stackoverflow.com/a/44198641
17
+ */
18
+ export function isDate(value: mixed): boolean {
19
+ return (
20
+ !!value &&
21
+ // $FlowFixMe[method-unbinding]
22
+ Object.prototype.toString.call(value) === '[object Date]' &&
23
+ !isNaN(value)
24
+ );
25
+ }
26
+
27
+ /**
28
+ * Is value is a valid Date instance, then return that. If not, then return
29
+ * null.
30
+ */
31
+ export function asDate(value: mixed): Date | null {
32
+ return isDate(value) ? ((value: cast): Date) : null;
33
+ }
34
+
35
+ export function isMultiline(s: string): boolean {
36
+ return s.indexOf('\n') >= 0;
37
+ }
38
+
39
+ export function indent(s: string, prefix: string = INDENT): string {
40
+ if (isMultiline(s)) {
41
+ return s
42
+ .split('\n')
43
+ .map((line) => prefix + line)
44
+ .join('\n');
45
+ } else {
46
+ return prefix + s;
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Walks the annotation tree and emits the annotation's key path within the
52
+ * object tree, and the message as a series of messages (array of strings).
53
+ */
54
+ export function summarize(
55
+ ann: Annotation,
56
+ keypath: $ReadOnlyArray<number | string> = [],
57
+ ): Array<string> {
58
+ const result: Array<string> = [];
59
+
60
+ if (ann.type === 'array') {
61
+ const items = ann.items;
62
+ let index = 0;
63
+ items.forEach((ann) => {
64
+ summarize(ann, [...keypath, index++]).forEach((item) =>
65
+ // Collect to results
66
+ result.push(item),
67
+ );
68
+ });
69
+ } else if (ann.type === 'object') {
70
+ const fields = ann.fields;
71
+ Object.keys(fields).forEach((key) => {
72
+ const value = fields[key];
73
+ summarize(value, [...keypath, key]).forEach((item) =>
74
+ // Collect to results
75
+ result.push(item),
76
+ );
77
+ });
78
+ }
79
+
80
+ const text = ann.text;
81
+ if (!text) {
82
+ return result;
83
+ }
84
+
85
+ let prefix: string;
86
+ if (keypath.length === 0) {
87
+ prefix = '';
88
+ } else if (keypath.length === 1) {
89
+ prefix =
90
+ typeof keypath[0] === 'number'
91
+ ? `Value at index ${keypath[0]}: `
92
+ : `Value at key ${JSON.stringify(keypath[0])}: `;
93
+ } else {
94
+ prefix = `Value at keypath ${keypath.map((x) => x.toString()).join('.')}: `;
95
+ }
96
+ return [...result, prefix + text];
97
+ }
File without changes
@@ -0,0 +1,218 @@
1
+ // @flow strict
2
+
3
+ type cast = $FlowFixMe;
4
+
5
+ const _register: WeakSet<{ ... }> = new WeakSet();
6
+
7
+ export type ObjectAnnotation = {|
8
+ +type: 'object',
9
+ +fields: { +[key: string]: Annotation },
10
+ +text?: string,
11
+ |};
12
+
13
+ export type ArrayAnnotation = {|
14
+ +type: 'array',
15
+ +items: $ReadOnlyArray<Annotation>,
16
+ +text?: string,
17
+ |};
18
+
19
+ export type ScalarAnnotation = {|
20
+ +type: 'scalar',
21
+ +value: mixed,
22
+ +text?: string,
23
+ |};
24
+
25
+ export type FunctionAnnotation = {|
26
+ +type: 'function',
27
+ +text?: string,
28
+ |};
29
+
30
+ export type CircularRefAnnotation = {|
31
+ +type: 'circular-ref',
32
+ +text?: string,
33
+ |};
34
+
35
+ export type UnknownAnnotation = {|
36
+ +type: 'unknown',
37
+ +value: mixed,
38
+ +text?: string,
39
+ |};
40
+
41
+ export type Annotation =
42
+ | ObjectAnnotation
43
+ | ArrayAnnotation
44
+ | ScalarAnnotation
45
+ | FunctionAnnotation
46
+ | CircularRefAnnotation
47
+ | UnknownAnnotation;
48
+
49
+ function brand<A: Annotation>(ann: A): A {
50
+ _register.add(ann);
51
+ return ann;
52
+ }
53
+
54
+ export function object(
55
+ fields: { +[key: string]: Annotation },
56
+ text?: string,
57
+ ): ObjectAnnotation {
58
+ return brand({ type: 'object', fields, text });
59
+ }
60
+
61
+ export function array(items: $ReadOnlyArray<Annotation>, text?: string): ArrayAnnotation {
62
+ return brand({
63
+ type: 'array',
64
+ items,
65
+ text,
66
+ });
67
+ }
68
+
69
+ export function func(text?: string): FunctionAnnotation {
70
+ return brand({
71
+ type: 'function',
72
+ text,
73
+ });
74
+ }
75
+
76
+ export function unknown(value: mixed, text?: string): UnknownAnnotation {
77
+ return brand({
78
+ type: 'unknown',
79
+ value,
80
+ text,
81
+ });
82
+ }
83
+
84
+ export function scalar(value: mixed, text?: string): ScalarAnnotation {
85
+ return brand({
86
+ type: 'scalar',
87
+ value,
88
+ text,
89
+ });
90
+ }
91
+
92
+ export function circularRef(text?: string): CircularRefAnnotation {
93
+ return brand({
94
+ type: 'circular-ref',
95
+ text,
96
+ });
97
+ }
98
+
99
+ /**
100
+ * Given an existing Annotation, set the annotation's text to a new value.
101
+ */
102
+ export function updateText<A: Annotation>(annotation: A, text?: string): A {
103
+ if (text !== undefined) {
104
+ return brand({ ...annotation, text });
105
+ } else {
106
+ return annotation;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Given an existing ObjectAnnotation, merges new Annotations in there.
112
+ */
113
+ export function merge(
114
+ objAnnotation: ObjectAnnotation,
115
+ fields: { +[key: string]: Annotation },
116
+ ): ObjectAnnotation {
117
+ const newFields = { ...objAnnotation.fields, ...fields };
118
+ return object(newFields, objAnnotation.text);
119
+ }
120
+
121
+ export function asAnnotation(thing: mixed): Annotation | void {
122
+ return typeof thing === 'object' && thing !== null && _register.has(thing)
123
+ ? ((thing: cast): Annotation)
124
+ : undefined;
125
+ }
126
+
127
+ type RefSet = WeakSet<{ ... } | $ReadOnlyArray<mixed>>;
128
+
129
+ function annotateArray(
130
+ value: $ReadOnlyArray<mixed>,
131
+ text?: string,
132
+ seen: RefSet,
133
+ ): ArrayAnnotation | CircularRefAnnotation {
134
+ seen.add(value);
135
+
136
+ const items = value.map((v) => annotate(v, undefined, seen));
137
+ return array(items, text);
138
+ }
139
+
140
+ function annotateObject(
141
+ obj: { +[string]: mixed },
142
+ text?: string,
143
+ seen: RefSet,
144
+ ): ObjectAnnotation {
145
+ seen.add(obj);
146
+
147
+ const fields = {};
148
+ Object.keys(obj).forEach((key) => {
149
+ const value = obj[key];
150
+ fields[key] = annotate(value, undefined, seen);
151
+ });
152
+ return object(fields, text);
153
+ }
154
+
155
+ function annotate(value: mixed, text?: string, seen: RefSet): Annotation {
156
+ if (
157
+ value === null ||
158
+ value === undefined ||
159
+ typeof value === 'string' ||
160
+ typeof value === 'number' ||
161
+ typeof value === 'boolean' ||
162
+ typeof value === 'symbol' ||
163
+ typeof value.getMonth === 'function'
164
+ ) {
165
+ return scalar(value, text);
166
+ }
167
+
168
+ const ann = asAnnotation(value);
169
+ if (ann) {
170
+ return updateText(ann, text);
171
+ }
172
+
173
+ if (Array.isArray(value)) {
174
+ // "Circular references" can only exist in objects or arrays
175
+ if (seen.has(value)) {
176
+ return circularRef(text);
177
+ } else {
178
+ return annotateArray(value, text, seen);
179
+ }
180
+ }
181
+
182
+ if (typeof value === 'object') {
183
+ // "Circular references" can only exist in objects or arrays
184
+ if (seen.has(value)) {
185
+ return circularRef(text);
186
+ } else {
187
+ return annotateObject(value, text, seen);
188
+ }
189
+ }
190
+
191
+ if (typeof value === 'function') {
192
+ return func(text);
193
+ }
194
+
195
+ return unknown(value, text);
196
+ }
197
+
198
+ function public_annotate(value: mixed, text?: string): Annotation {
199
+ return annotate(value, text, new WeakSet());
200
+ }
201
+
202
+ function public_annotateObject(
203
+ obj: { +[string]: mixed },
204
+ text?: string,
205
+ ): ObjectAnnotation {
206
+ return annotateObject(obj, text, new WeakSet());
207
+ }
208
+
209
+ export {
210
+ // This construct just ensures the "seen" weakmap (used for circular
211
+ // reference detection) isn't made part of the public API.
212
+ public_annotate as annotate,
213
+ public_annotateObject as annotateObject,
214
+ //
215
+ // NOTE: Don't acces theses private APIs directly. They are only exported here
216
+ // to better enable unit testing.
217
+ annotate as __private_annotate,
218
+ };
File without changes
@@ -0,0 +1,103 @@
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, DecodeResult } from '../_types';
7
+
8
+ /**
9
+ * Like a "Plain Old JavaScript Object", but for arrays: "Plain Old JavaScript
10
+ * Array" ^_^
11
+ */
12
+ export const poja: Decoder<Array<mixed>> = (blob: mixed) => {
13
+ if (!Array.isArray(blob)) {
14
+ return Result.err(annotate(blob, 'Must be an array'));
15
+ }
16
+ return Result.ok(
17
+ // NOTE: Since Flow 0.98, Array.isArray() returns $ReadOnlyArray<mixed>
18
+ // instead of Array<mixed>. For rationale, see
19
+ // https://github.com/facebook/flow/issues/7684. In this case, we
20
+ // don't want to output read-only types because it's up to the user of
21
+ // decoders to determine what they want to do with the decoded output.
22
+ // If they want to write items into the array, that's fine!
23
+ // The fastest way to turn a read-only array into a normal array in
24
+ // Javascript is to use .slice() on it, see this benchmark:
25
+ // http://jsben.ch/lO6C5
26
+ blob.slice(),
27
+ );
28
+ };
29
+
30
+ /**
31
+ * Given an array of Result instances, loop over them all and return:
32
+ * - An [index, err] tuple, indicating the (index of the) first Err instance
33
+ * encountered; or
34
+ * - a new Ok with an array of all unwrapped Ok'ed values
35
+ */
36
+ function all<T>(
37
+ items: $ReadOnlyArray<DecodeResult<T>>,
38
+ blobs: $ReadOnlyArray<mixed>,
39
+ ): DecodeResult<Array<T>> {
40
+ const results: Array<T> = [];
41
+ for (let index = 0; index < items.length; ++index) {
42
+ const result = items[index];
43
+ if (result.type === 'ok') {
44
+ results.push(result.value);
45
+ } else {
46
+ const ann = result.error;
47
+
48
+ // Rewrite the annotation to include the index information, and inject it into the original blob
49
+ const clone = [...blobs];
50
+ clone.splice(
51
+ index,
52
+ 1,
53
+ annotate(
54
+ ann,
55
+ ann.text ? `${ann.text} (at index ${index})` : `index ${index}`,
56
+ ),
57
+ );
58
+
59
+ // const errValue = [];
60
+ // if (index > 0) {
61
+ // errValue.push('...'); // TODO: make special mark, not string!
62
+ // }
63
+ // errValue.push(
64
+ // );
65
+ // if (index < iterable.length - 1) {
66
+ // errValue.push('...'); // TODO: make special mark, not string!
67
+ // }
68
+ return Result.err(annotate(clone));
69
+ }
70
+ }
71
+ return Result.ok(results);
72
+ }
73
+
74
+ /**
75
+ * Given a T, builds a decoder that assumes an array input and returns an
76
+ * Array<T>.
77
+ */
78
+ function members<T>(decoder: Decoder<T>): Decoder<Array<T>, Array<mixed>> {
79
+ return (blobs: $ReadOnlyArray<mixed>) => {
80
+ const results = blobs.map(decoder);
81
+ const result = all(results, blobs);
82
+ return result;
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Builds a Decoder that returns Ok for values of `Array<T>`, given a Decoder
88
+ * for `T`. Err otherwise.
89
+ */
90
+ export function array<T>(decoder: Decoder<T>): Decoder<Array<T>> {
91
+ return compose(poja, members(decoder));
92
+ }
93
+
94
+ /**
95
+ * Builds a Decoder that returns Ok for values of `Array<T>`, but will reject
96
+ * empty arrays.
97
+ */
98
+ export function nonEmptyArray<T>(decoder: Decoder<T>): Decoder<Array<T>> {
99
+ return compose(
100
+ array(decoder),
101
+ predicate((arr) => arr.length > 0, 'Must be non-empty array'),
102
+ );
103
+ }
File without changes
@@ -0,0 +1,29 @@
1
+ // @flow strict
2
+
3
+ import * as Result from '../result';
4
+ import { annotate } from '../annotate';
5
+ import { map } from './composition';
6
+ import { number } from './number';
7
+ import type { Decoder } from '../_types';
8
+
9
+ /**
10
+ * Decoder that only returns Ok for boolean inputs. Err otherwise.
11
+ */
12
+ export const boolean: Decoder<boolean> = (blob: mixed) => {
13
+ return typeof blob === 'boolean'
14
+ ? Result.ok(blob)
15
+ : Result.err(annotate(blob, 'Must be boolean'));
16
+ };
17
+
18
+ /**
19
+ * Decoder that returns true for all truthy values, and false otherwise. Never fails.
20
+ */
21
+ export const truthy: Decoder<boolean> = (blob: mixed) => {
22
+ return Result.ok(!!blob);
23
+ };
24
+
25
+ /**
26
+ * Decoder that only returns Ok for numeric input values representing booleans.
27
+ * Returns their boolean representation. Err otherwise.
28
+ */
29
+ export const numericBoolean: Decoder<boolean> = map(number, (n) => !!n);
File without changes
@@ -0,0 +1,43 @@
1
+ // @flow strict
2
+
3
+ import * as Result from '../result';
4
+ import { annotate } from '../annotate';
5
+ import type { Decoder } from '../_types';
6
+
7
+ /**
8
+ * Given a decoder T and a mapping function from T's to V's, returns a decoder
9
+ * for V's. This is useful to change the original input data.
10
+ */
11
+ export function map<T, V>(decoder: Decoder<T>, mapper: (T) => V): Decoder<V> {
12
+ return compose(decoder, (x) => {
13
+ try {
14
+ return Result.ok(mapper(x));
15
+ } catch (e) {
16
+ return Result.err(annotate(x, e instanceof Error ? e.message : String(e)));
17
+ }
18
+ });
19
+ }
20
+
21
+ /**
22
+ * Compose two decoders by passing the result of the first into the second.
23
+ * The second decoder may assume as its input type the output type of the first
24
+ * decoder (so it's not necessary to accept the typical "mixed"). This is
25
+ * useful for "narrowing down" the checks. For example, if you want to write
26
+ * a decoder for positive numbers, you can compose it from an existing decoder
27
+ * for any number, and a decoder that, assuming a number, checks if it's
28
+ * positive. Very often combined with the predicate() helper as the second
29
+ * argument.
30
+ */
31
+ export function compose<T, V>(decoder: Decoder<T>, next: Decoder<V, T>): Decoder<V> {
32
+ return (blob: mixed) => Result.andThen(decoder(blob), next);
33
+ }
34
+
35
+ /**
36
+ * Factory function returning a Decoder<T>, given a predicate function that
37
+ * accepts/rejects the input of type T.
38
+ */
39
+ export function predicate<T>(predicate: (T) => boolean, msg: string): Decoder<T, T> {
40
+ return (value: T) => {
41
+ return predicate(value) ? Result.ok(value) : Result.err(annotate(value, msg));
42
+ };
43
+ }
File without changes
@@ -0,0 +1,46 @@
1
+ // @flow strict
2
+
3
+ import * as Result from '../result';
4
+ import { annotate } from '../annotate';
5
+ import type { Decoder, Scalar } from '../_types';
6
+
7
+ /**
8
+ * Decoder that only returns Ok for `null` inputs. Err otherwise.
9
+ */
10
+ export const null_: Decoder<null> = (blob: mixed) =>
11
+ blob === null ? Result.ok(blob) : Result.err(annotate(blob, 'Must be null'));
12
+
13
+ /**
14
+ * Decoder that only returns Ok for `undefined` inputs. Err otherwise.
15
+ */
16
+ export const undefined_: Decoder<void> = (blob: mixed) =>
17
+ blob === undefined
18
+ ? Result.ok(blob)
19
+ : Result.err(annotate(blob, 'Must be undefined'));
20
+
21
+ /**
22
+ * Decoder that only returns Ok for the given value constant. Err otherwise.
23
+ */
24
+ export function constant<T: Scalar>(value: T): Decoder<T> {
25
+ return (blob: mixed) =>
26
+ blob === value
27
+ ? Result.ok(value)
28
+ : Result.err(annotate(blob, `Must be constant ${String(value)}`));
29
+ }
30
+
31
+ /**
32
+ * Decoder that always returns Ok for the given hardcoded value, no matter what the input.
33
+ */
34
+ export function hardcoded<T>(value: T): Decoder<T> {
35
+ return () => Result.ok(value);
36
+ }
37
+
38
+ /**
39
+ * Decoder that always returns Ok for the given hardcoded value, no matter what the input.
40
+ */
41
+ export const unknown: Decoder<mixed> = (blob: mixed) => Result.ok(blob);
42
+
43
+ /**
44
+ * Alias of unknown.
45
+ */
46
+ export const mixed: Decoder<mixed> = unknown;
File without changes
@@ -0,0 +1,40 @@
1
+ // @flow strict
2
+
3
+ import * as Result from '../result';
4
+ import { annotate } from '../annotate';
5
+ import { isDate } from '../_utils';
6
+ import { map } from './composition';
7
+ import { regex } from './string';
8
+ import type { Decoder } from '../_types';
9
+
10
+ // $FlowFixMe[unclear-type] (not really an issue) - deliberate casting
11
+ type cast = any;
12
+
13
+ // Only matches the shape. This "over-matches" some values that still aren't
14
+ // valid dates (like 9999-99-99), but those will be caught by JS Date's
15
+ // internal validations
16
+ const iso8601_re =
17
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.]\d+)?(?:Z|[+-]\d{2}:?\d{2})$/;
18
+
19
+ export const date: Decoder<Date> = (value: mixed) =>
20
+ isDate(value)
21
+ ? Result.ok(((value: cast): Date))
22
+ : Result.err(annotate(value, 'Must be a Date'));
23
+
24
+ /**
25
+ * Decoder that only returns Ok for strings that are valid ISO8601 date
26
+ * strings. Err otherwise.
27
+ */
28
+ export const iso8601: Decoder<Date> = map(
29
+ // Input itself needs to match the ISO8601 regex...
30
+ regex(iso8601_re, 'Must be ISO8601 format'),
31
+
32
+ // Make sure it is a _valid_ date
33
+ (value: string) => {
34
+ const date = new Date(value);
35
+ if (isNaN(date.getTime())) {
36
+ throw new Error('Must be valid date/time value');
37
+ }
38
+ return date;
39
+ },
40
+ );
File without changes
@@ -0,0 +1,17 @@
1
+ // @flow strict
2
+
3
+ import * as Result from '../result';
4
+ import { annotate } from '../annotate';
5
+ import type { Decoder } from '../_types';
6
+
7
+ /**
8
+ * Wrap another decoder, and override the error message in case it fails. This
9
+ * is useful to "simplify" otherwise potentially complex error messages, or to
10
+ * use language in those error messages that can be relayed to end users (for
11
+ * example to show in form errors).
12
+ */
13
+ export function describe<T>(decoder: Decoder<T>, message: string): Decoder<T> {
14
+ return (blob: mixed) => {
15
+ return Result.mapError(decoder(blob), (err) => annotate(err, message));
16
+ };
17
+ }
File without changes
@@ -0,0 +1,58 @@
1
+ // @flow strict
2
+
3
+ import * as Result from '../result';
4
+ import { object } from './object';
5
+ import { oneOf } from './either';
6
+ import type { Decoder, DecoderType } from '../_types';
7
+
8
+ // $FlowFixMe[unclear-type] (not really an issue) - deliberate use of `any` - not sure how we should get rid of this
9
+ type anything = any;
10
+
11
+ /**
12
+ * Dispatches to one of several given decoders, based on the value found at
13
+ * runtime in the given field. For example, suppose you have these decoders:
14
+ *
15
+ * const rectangle = object({
16
+ * type: constant('rect'),
17
+ * x: number,
18
+ * y: number,
19
+ * width: number,
20
+ * height: number,
21
+ * });
22
+ *
23
+ * const circle = object({
24
+ * type: constant('circle'),
25
+ * cx: number,
26
+ * cy: number,
27
+ * r: number,
28
+ * });
29
+ *
30
+ * Then these two decoders are equivalent:
31
+ *
32
+ * const shape = either(rectangle, circle)
33
+ * const shape = dispatch('type', { rectangle, circle })
34
+ *
35
+ * Will be of type Decoder<Rectangle | Circle>.
36
+ *
37
+ * But the dispatch version will typically be more runtime-efficient. The
38
+ * reason is that it will first do minimal work to "look ahead" into the `type`
39
+ * field here, and based on that value, pick the decoder to invoke.
40
+ *
41
+ * The `either` version will simply try to invoke each decoder, until it finds
42
+ * one that matches.
43
+ *
44
+ * Also, the error messages will be less ambiguous using `dispatch()`.
45
+ */
46
+ export function dispatch<O: { +[field: string]: Decoder<anything>, ... }>(
47
+ field: string,
48
+ mapping: O,
49
+ ): Decoder<$Values<$ObjMap<O, DecoderType>>> {
50
+ const base = object({ [field]: oneOf(Object.keys(mapping)) });
51
+ return (blob: mixed) => {
52
+ return Result.andThen(base(blob), (baseObj) => {
53
+ const decoderName = baseObj[field];
54
+ const decoder = mapping[decoderName];
55
+ return decoder(blob);
56
+ });
57
+ };
58
+ }
File without changes