decoders 2.0.0-beta9 → 2.0.0

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 +56 -29
  2. package/Decoder.d.ts +94 -0
  3. package/Decoder.js +222 -0
  4. package/Decoder.js.flow +286 -0
  5. package/Decoder.mjs +215 -0
  6. package/README.md +122 -1507
  7. package/_utils.d.ts +0 -1
  8. package/_utils.js +11 -17
  9. package/_utils.js.flow +13 -17
  10. package/_utils.mjs +10 -14
  11. package/format.d.ts +4 -2
  12. package/format.js +1 -1
  13. package/format.js.flow +3 -1
  14. package/format.mjs +1 -1
  15. package/index.d.ts +29 -31
  16. package/index.js +62 -84
  17. package/index.js.flow +30 -48
  18. package/index.mjs +11 -36
  19. package/{core → lib}/_helpers.d.ts +0 -0
  20. package/lib/arrays.d.ts +59 -0
  21. package/lib/arrays.js +139 -0
  22. package/lib/arrays.js.flow +138 -0
  23. package/lib/arrays.mjs +124 -0
  24. package/lib/basics.d.ts +93 -0
  25. package/lib/basics.js +144 -0
  26. package/lib/basics.js.flow +124 -0
  27. package/lib/basics.mjs +120 -0
  28. package/lib/booleans.d.ts +16 -0
  29. package/lib/booleans.js +35 -0
  30. package/lib/booleans.js.flow +22 -0
  31. package/lib/booleans.mjs +25 -0
  32. package/lib/dates.d.ts +15 -0
  33. package/lib/dates.js +44 -0
  34. package/lib/dates.js.flow +40 -0
  35. package/lib/dates.mjs +34 -0
  36. package/lib/json.d.ts +35 -0
  37. package/lib/json.js +55 -0
  38. package/lib/json.js.flow +50 -0
  39. package/lib/json.mjs +40 -0
  40. package/lib/numbers.d.ts +31 -0
  41. package/lib/numbers.js +51 -0
  42. package/lib/numbers.js.flow +48 -0
  43. package/lib/numbers.mjs +41 -0
  44. package/lib/objects.d.ts +75 -0
  45. package/{core/object.js → lib/objects.js} +78 -85
  46. package/{core/object.js.flow → lib/objects.js.flow} +89 -102
  47. package/{core/object.mjs → lib/objects.mjs} +77 -82
  48. package/lib/strings.d.ts +56 -0
  49. package/lib/strings.js +101 -0
  50. package/lib/strings.js.flow +90 -0
  51. package/lib/strings.mjs +82 -0
  52. package/lib/unions.d.ts +55 -0
  53. package/lib/unions.js +160 -0
  54. package/{core/either.js.flow → lib/unions.js.flow} +67 -17
  55. package/lib/unions.mjs +146 -0
  56. package/lib/utilities.d.ts +34 -0
  57. package/lib/utilities.js +75 -0
  58. package/lib/utilities.js.flow +65 -0
  59. package/lib/utilities.mjs +60 -0
  60. package/package.json +64 -17
  61. package/result.d.ts +0 -23
  62. package/result.js +0 -68
  63. package/result.js.flow +0 -72
  64. package/result.mjs +0 -54
  65. package/_guard.d.ts +0 -7
  66. package/_guard.js +0 -22
  67. package/_guard.js.flow +0 -20
  68. package/_guard.mjs +0 -15
  69. package/_types.d.ts +0 -13
  70. package/_types.js +0 -1
  71. package/_types.js.flow +0 -20
  72. package/_types.mjs +0 -0
  73. package/core/array.d.ts +0 -8
  74. package/core/array.js +0 -115
  75. package/core/array.js.flow +0 -107
  76. package/core/array.mjs +0 -100
  77. package/core/boolean.d.ts +0 -5
  78. package/core/boolean.js +0 -40
  79. package/core/boolean.js.flow +0 -27
  80. package/core/boolean.mjs +0 -28
  81. package/core/composition.d.ts +0 -18
  82. package/core/composition.js +0 -82
  83. package/core/composition.js.flow +0 -74
  84. package/core/composition.mjs +0 -70
  85. package/core/constants.d.ts +0 -11
  86. package/core/constants.js +0 -65
  87. package/core/constants.js.flow +0 -44
  88. package/core/constants.mjs +0 -46
  89. package/core/date.d.ts +0 -4
  90. package/core/date.js +0 -42
  91. package/core/date.js.flow +0 -38
  92. package/core/date.mjs +0 -28
  93. package/core/describe.d.ts +0 -3
  94. package/core/describe.js +0 -22
  95. package/core/describe.js.flow +0 -17
  96. package/core/describe.mjs +0 -16
  97. package/core/dispatch.d.ts +0 -8
  98. package/core/dispatch.js +0 -60
  99. package/core/dispatch.js.flow +0 -59
  100. package/core/dispatch.mjs +0 -52
  101. package/core/either.d.ts +0 -66
  102. package/core/either.js +0 -101
  103. package/core/either.mjs +0 -90
  104. package/core/fail.d.ts +0 -3
  105. package/core/fail.js +0 -17
  106. package/core/fail.js.flow +0 -12
  107. package/core/fail.mjs +0 -11
  108. package/core/instanceOf.d.ts +0 -3
  109. package/core/instanceOf.js +0 -15
  110. package/core/instanceOf.js.flow +0 -20
  111. package/core/instanceOf.mjs +0 -8
  112. package/core/json.d.ts +0 -11
  113. package/core/json.js +0 -31
  114. package/core/json.js.flow +0 -28
  115. package/core/json.mjs +0 -15
  116. package/core/lazy.d.ts +0 -3
  117. package/core/lazy.js +0 -16
  118. package/core/lazy.js.flow +0 -15
  119. package/core/lazy.mjs +0 -11
  120. package/core/number.d.ts +0 -6
  121. package/core/number.js +0 -36
  122. package/core/number.js.flow +0 -40
  123. package/core/number.mjs +0 -25
  124. package/core/object.d.ts +0 -38
  125. package/core/optional.d.ts +0 -5
  126. package/core/optional.js +0 -50
  127. package/core/optional.js.flow +0 -41
  128. package/core/optional.mjs +0 -38
  129. package/core/string.d.ts +0 -13
  130. package/core/string.js +0 -80
  131. package/core/string.js.flow +0 -72
  132. package/core/string.mjs +0 -58
  133. package/core/tuple.d.ts +0 -30
  134. package/core/tuple.js +0 -54
  135. package/core/tuple.js.flow +0 -51
  136. package/core/tuple.mjs +0 -45
package/lib/strings.js ADDED
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.nonEmptyString = exports.httpsUrl = exports.email = void 0;
5
+ exports.regex = regex;
6
+ exports.uuidv4 = exports.uuidv1 = exports.uuid = exports.url = exports.string = void 0;
7
+
8
+ var _Decoder = require("../Decoder");
9
+
10
+ var _unions = require("./unions");
11
+
12
+ var _utilities = require("./utilities");
13
+
14
+ /** Match groups in this regex:
15
+ * \1 - the scheme
16
+ * \2 - the username/password (optional)
17
+ * \3 - the host
18
+ * \4 - the port (optional)
19
+ * \5 - the path (optional)
20
+ */
21
+ var url_re = /^([A-Za-z]{3,9}(?:[+][A-Za-z]{3,9})?):\/\/(?:([-;:&=+$,\w]+)@)?(?:([A-Za-z0-9.-]+)(?::([0-9]{2,5}))?)(\/(?:[-+~%/.,\w]*)?(?:\?[-+=&;%@.,\w]*)?(?:#[.,!/\w]*)?)?$/;
22
+ /**
23
+ * Accepts and returns strings.
24
+ */
25
+
26
+ var string = (0, _Decoder.define)(function (blob, ok, err) {
27
+ return typeof blob === 'string' ? ok(blob) : err('Must be string');
28
+ });
29
+ /**
30
+ * Like `string`, but will reject the empty string or strings containing only whitespace.
31
+ */
32
+
33
+ exports.string = string;
34
+ var nonEmptyString = regex(/\S/, 'Must be non-empty string');
35
+ /**
36
+ * Accepts and returns strings that match the given regular expression.
37
+ */
38
+
39
+ exports.nonEmptyString = nonEmptyString;
40
+
41
+ function regex(regex, msg) {
42
+ return string.refine(function (s) {
43
+ return regex.test(s);
44
+ }, msg);
45
+ }
46
+ /**
47
+ * Accepts and returns strings that are syntactically valid email addresses.
48
+ * (This will not mean that the email address actually exist.)
49
+ */
50
+
51
+
52
+ var email = regex( // The almost perfect email regex, taken from https://emailregex.com/
53
+ /^(([^<>()[\]\\.,;:\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,}))$/, 'Must be email');
54
+ /**
55
+ * Accepts strings that are valid URLs, returns the value as a URL instance.
56
+ */
57
+
58
+ exports.email = email;
59
+ var url = (0, _unions.either)(regex(url_re, 'Must be URL').transform(function (value) {
60
+ return new URL(value);
61
+ }), (0, _utilities.instanceOf)(URL));
62
+ /**
63
+ * Accepts strings that are valid URLs, but only HTTPS ones. Returns the value
64
+ * as a URL instance.
65
+ */
66
+
67
+ exports.url = url;
68
+ var httpsUrl = url.refine(function (value) {
69
+ return value.protocol === 'https:';
70
+ }, 'Must be an HTTPS URL');
71
+ /**
72
+ * Accepts strings that are valid
73
+ * [UUIDs](https://en.wikipedia.org/wiki/universally_unique_identifier)
74
+ * (universally unique identifier).
75
+ */
76
+
77
+ exports.httpsUrl = httpsUrl;
78
+ var uuid = regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, 'Must be uuid');
79
+ /**
80
+ * Like `uuid`, but only accepts
81
+ * [UUIDv1](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_%28date-time_and_MAC_address%29)
82
+ * strings.
83
+ */
84
+
85
+ exports.uuid = uuid;
86
+ var uuidv1 = // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_(date-time_and_MAC_address)
87
+ uuid.refine(function (value) {
88
+ return value[14] === '1';
89
+ }, 'Must be uuidv1');
90
+ /**
91
+ * Like `uuid`, but only accepts
92
+ * [UUIDv4](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_%28random%29)
93
+ * strings.
94
+ */
95
+
96
+ exports.uuidv1 = uuidv1;
97
+ var uuidv4 = // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)
98
+ uuid.refine(function (value) {
99
+ return value[14] === '4';
100
+ }, 'Must be uuidv4');
101
+ exports.uuidv4 = uuidv4;
@@ -0,0 +1,90 @@
1
+ // @flow strict
2
+
3
+ import { define } from '../Decoder';
4
+ import { either } from './unions';
5
+ import { instanceOf } from './utilities';
6
+ import type { Decoder } from '../Decoder';
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
+ /**
19
+ * Accepts and returns strings.
20
+ */
21
+ export const string: Decoder<string> = define((blob, ok, err) =>
22
+ typeof blob === 'string' ? ok(blob) : err('Must be string'),
23
+ );
24
+
25
+ /**
26
+ * Like `string`, but will reject the empty string or strings containing only whitespace.
27
+ */
28
+ export const nonEmptyString: Decoder<string> = regex(/\S/, 'Must be non-empty string');
29
+
30
+ /**
31
+ * Accepts and returns strings that match the given regular expression.
32
+ */
33
+ export function regex(regex: RegExp, msg: string): Decoder<string> {
34
+ return string.refine((s) => regex.test(s), msg);
35
+ }
36
+
37
+ /**
38
+ * Accepts and returns strings that are syntactically valid email addresses.
39
+ * (This will not mean that the email address actually exist.)
40
+ */
41
+ export const email: Decoder<string> = regex(
42
+ // The almost perfect email regex, taken from https://emailregex.com/
43
+ /^(([^<>()[\]\\.,;:\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,}))$/,
44
+ 'Must be email',
45
+ );
46
+
47
+ /**
48
+ * Accepts strings that are valid URLs, returns the value as a URL instance.
49
+ */
50
+ export const url: Decoder<URL> = either(
51
+ regex(url_re, 'Must be URL').transform((value) => new URL(value)),
52
+ instanceOf(URL),
53
+ );
54
+
55
+ /**
56
+ * Accepts strings that are valid URLs, but only HTTPS ones. Returns the value
57
+ * as a URL instance.
58
+ */
59
+ export const httpsUrl: Decoder<URL> = url.refine(
60
+ (value) => value.protocol === 'https:',
61
+ 'Must be an HTTPS URL',
62
+ );
63
+
64
+ /**
65
+ * Accepts strings that are valid
66
+ * [UUIDs](https://en.wikipedia.org/wiki/universally_unique_identifier)
67
+ * (universally unique identifier).
68
+ */
69
+ export const uuid: Decoder<string> = regex(
70
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
71
+ 'Must be uuid',
72
+ );
73
+
74
+ /**
75
+ * Like `uuid`, but only accepts
76
+ * [UUIDv1](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_%28date-time_and_MAC_address%29)
77
+ * strings.
78
+ */
79
+ export const uuidv1: Decoder<string> =
80
+ // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_(date-time_and_MAC_address)
81
+ uuid.refine((value) => value[14] === '1', 'Must be uuidv1');
82
+
83
+ /**
84
+ * Like `uuid`, but only accepts
85
+ * [UUIDv4](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_%28random%29)
86
+ * strings.
87
+ */
88
+ export const uuidv4: Decoder<string> =
89
+ // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)
90
+ uuid.refine((value) => value[14] === '4', 'Must be uuidv4');
@@ -0,0 +1,82 @@
1
+ import { define } from '../Decoder.mjs';
2
+ import { either } from './unions.mjs';
3
+ import { instanceOf } from './utilities.mjs';
4
+
5
+ /** Match groups in this regex:
6
+ * \1 - the scheme
7
+ * \2 - the username/password (optional)
8
+ * \3 - the host
9
+ * \4 - the port (optional)
10
+ * \5 - the path (optional)
11
+ */
12
+ var url_re = /^([A-Za-z]{3,9}(?:[+][A-Za-z]{3,9})?):\/\/(?:([-;:&=+$,\w]+)@)?(?:([A-Za-z0-9.-]+)(?::([0-9]{2,5}))?)(\/(?:[-+~%/.,\w]*)?(?:\?[-+=&;%@.,\w]*)?(?:#[.,!/\w]*)?)?$/;
13
+ /**
14
+ * Accepts and returns strings.
15
+ */
16
+
17
+ export var string = define(function (blob, ok, err) {
18
+ return typeof blob === 'string' ? ok(blob) : err('Must be string');
19
+ });
20
+ /**
21
+ * Like `string`, but will reject the empty string or strings containing only whitespace.
22
+ */
23
+
24
+ export var nonEmptyString = regex(/\S/, 'Must be non-empty string');
25
+ /**
26
+ * Accepts and returns strings that match the given regular expression.
27
+ */
28
+
29
+ export function regex(regex, msg) {
30
+ return string.refine(function (s) {
31
+ return regex.test(s);
32
+ }, msg);
33
+ }
34
+ /**
35
+ * Accepts and returns strings that are syntactically valid email addresses.
36
+ * (This will not mean that the email address actually exist.)
37
+ */
38
+
39
+ export var email = regex( // The almost perfect email regex, taken from https://emailregex.com/
40
+ /^(([^<>()[\]\\.,;:\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,}))$/, 'Must be email');
41
+ /**
42
+ * Accepts strings that are valid URLs, returns the value as a URL instance.
43
+ */
44
+
45
+ export var url = either(regex(url_re, 'Must be URL').transform(function (value) {
46
+ return new URL(value);
47
+ }), instanceOf(URL));
48
+ /**
49
+ * Accepts strings that are valid URLs, but only HTTPS ones. Returns the value
50
+ * as a URL instance.
51
+ */
52
+
53
+ export var httpsUrl = url.refine(function (value) {
54
+ return value.protocol === 'https:';
55
+ }, 'Must be an HTTPS URL');
56
+ /**
57
+ * Accepts strings that are valid
58
+ * [UUIDs](https://en.wikipedia.org/wiki/universally_unique_identifier)
59
+ * (universally unique identifier).
60
+ */
61
+
62
+ export var uuid = regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, 'Must be uuid');
63
+ /**
64
+ * Like `uuid`, but only accepts
65
+ * [UUIDv1](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_%28date-time_and_MAC_address%29)
66
+ * strings.
67
+ */
68
+
69
+ export var uuidv1 = // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_(date-time_and_MAC_address)
70
+ uuid.refine(function (value) {
71
+ return value[14] === '1';
72
+ }, 'Must be uuidv1');
73
+ /**
74
+ * Like `uuid`, but only accepts
75
+ * [UUIDv4](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_%28random%29)
76
+ * strings.
77
+ */
78
+
79
+ export var uuidv4 = // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)
80
+ uuid.refine(function (value) {
81
+ return value[14] === '4';
82
+ }, 'Must be uuidv4');
@@ -0,0 +1,55 @@
1
+ import { Decoder, DecoderType, Scalar } from '../Decoder';
2
+
3
+ export type Values<T extends object> = T[keyof T];
4
+
5
+ export type DecoderTypes<T> = T extends ReadonlyArray<Decoder<infer U>> ? U : never;
6
+
7
+ /**
8
+ * Accepts values accepted by any of the given decoders.
9
+ *
10
+ * The decoders are tried on the input one by one, in the given order. The
11
+ * first one that accepts the input "wins". If all decoders reject the input,
12
+ * the input gets rejected.
13
+ */
14
+ export function either<T extends ReadonlyArray<Decoder<any>>>(
15
+ ...args: T
16
+ ): Decoder<DecoderTypes<T>>;
17
+
18
+ /**
19
+ * Accepts any value that is strictly-equal (using `===`) to one of the
20
+ * specified values.
21
+ */
22
+ export function oneOf<T extends Scalar>(constants: readonly T[]): Decoder<T>;
23
+
24
+ /**
25
+ * If you are decoding tagged unions you may want to use the `taggedUnion()`
26
+ * decoder instead of the general purpose `either()` decoder to get better
27
+ * error messages and better performance.
28
+ *
29
+ * This decoder is optimized for [tagged
30
+ * unions](https://en.wikipedia.org/wiki/Tagged_union), i.e. a union of
31
+ * objects where one field is used as the discriminator.
32
+ *
33
+ * ```ts
34
+ * const A = object({ tag: constant('A'), foo: string });
35
+ * const B = object({ tag: constant('B'), bar: number });
36
+ *
37
+ * const AorB = taggedUnion('tag', { A, B });
38
+ * // ^^^
39
+ * ```
40
+ *
41
+ * Decoding now works in two steps:
42
+ *
43
+ * 1. Look at the `'tag'` field in the incoming object (this is the field
44
+ * that decides which decoder will be used)
45
+ * 2. If the value is `'A'`, then decoder `A` will be used. If it's `'B'`, then
46
+ * decoder `B` will be used. Otherwise, this will fail.
47
+ *
48
+ * This is effectively equivalent to `either(A, B)`, but will provide better
49
+ * error messages and is more performant at runtime because it doesn't have to
50
+ * try all decoders one by one.
51
+ */
52
+ export function taggedUnion<O extends { [key: string]: Decoder<any> }>(
53
+ field: string,
54
+ mapping: O,
55
+ ): Decoder<Values<{ [key in keyof O]: DecoderType<O[key]> }>>;
package/lib/unions.js ADDED
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.either = void 0;
5
+ exports.oneOf = oneOf;
6
+ exports.taggedUnion = taggedUnion;
7
+
8
+ var _Decoder = require("../Decoder");
9
+
10
+ var _utils = require("../_utils");
11
+
12
+ var _objects = require("./objects");
13
+
14
+ var _utilities = require("./utilities");
15
+
16
+ var EITHER_PREFIX = 'Either:\n';
17
+ /**
18
+ * Indents and adds a dash in front of this (potentially multiline) string.
19
+ */
20
+
21
+ function itemize(s) {
22
+ return '-' + (0, _utils.indent)(s).substring(1);
23
+ }
24
+ /**
25
+ * Nests another error as an item under a new-to-be-created "Either error". If
26
+ * the given subitem already is an "Either error" of itself, don't indent, but
27
+ * just "inject" its items at the same error level, for nicely flattened either
28
+ * expressions.
29
+ *
30
+ * Avoids:
31
+ *
32
+ * Either:
33
+ * - Either:
34
+ * - Must be P
35
+ * - Either:
36
+ * - Must be Q
37
+ * - Must be R
38
+ * - Must be S
39
+ *
40
+ * And "flattens" these to:
41
+ *
42
+ * Either:
43
+ * - Must be P
44
+ * - Must be Q
45
+ * - Must be R
46
+ * - Must be S
47
+ *
48
+ */
49
+
50
+
51
+ function nest(errText) {
52
+ return errText.startsWith(EITHER_PREFIX) ? errText.substr(EITHER_PREFIX.length) : itemize(errText);
53
+ } // prettier-ignore
54
+
55
+
56
+ function _either() {
57
+ for (var _len = arguments.length, decoders = new Array(_len), _key = 0; _key < _len; _key++) {
58
+ decoders[_key] = arguments[_key];
59
+ }
60
+
61
+ if (decoders.length === 0) {
62
+ throw new Error('Pass at least one decoder to either()');
63
+ }
64
+
65
+ return (0, _Decoder.define)(function (blob, _, err) {
66
+ // Collect errors here along the way
67
+ var errors = [];
68
+
69
+ for (var _i = 0; _i < decoders.length; _i++) {
70
+ var result = decoders[_i].decode(blob);
71
+
72
+ if (result.ok) {
73
+ return result;
74
+ } else {
75
+ errors.push(result.error);
76
+ }
77
+ } // Decoding all alternatives failed, return the combined error message
78
+
79
+
80
+ var text = EITHER_PREFIX + errors.map(function (err) {
81
+ return nest((0, _utils.summarize)(err).join('\n'));
82
+ }).join('\n');
83
+ return err(text);
84
+ });
85
+ }
86
+ /**
87
+ * Accepts values accepted by any of the given decoders.
88
+ *
89
+ * The decoders are tried on the input one by one, in the given order. The
90
+ * first one that accepts the input "wins". If all decoders reject the input,
91
+ * the input gets rejected.
92
+ */
93
+
94
+
95
+ var either = _either;
96
+ /**
97
+ * Accepts any value that is strictly-equal (using `===`) to one of the
98
+ * specified values.
99
+ */
100
+
101
+ exports.either = either;
102
+
103
+ function oneOf(constants) {
104
+ return (0, _Decoder.define)(function (blob, ok, err) {
105
+ var winner = constants.find(function (c) {
106
+ return c === blob;
107
+ });
108
+
109
+ if (winner !== undefined) {
110
+ return ok(winner);
111
+ }
112
+
113
+ return err("Must be one of " + constants.map(function (value) {
114
+ return JSON.stringify(value);
115
+ }).join(', '));
116
+ });
117
+ }
118
+ /**
119
+ * If you are decoding tagged unions you may want to use the `taggedUnion()`
120
+ * decoder instead of the general purpose `either()` decoder to get better
121
+ * error messages and better performance.
122
+ *
123
+ * This decoder is optimized for [tagged
124
+ * unions](https://en.wikipedia.org/wiki/Tagged_union), i.e. a union of
125
+ * objects where one field is used as the discriminator.
126
+ *
127
+ * ```ts
128
+ * const A = object({ tag: constant('A'), foo: string });
129
+ * const B = object({ tag: constant('B'), bar: number });
130
+ *
131
+ * const AorB = taggedUnion('tag', { A, B });
132
+ * // ^^^
133
+ * ```
134
+ *
135
+ * Decoding now works in two steps:
136
+ *
137
+ * 1. Look at the `'tag'` field in the incoming object (this is the field
138
+ * that decides which decoder will be used)
139
+ * 2. If the value is `'A'`, then decoder `A` will be used. If it's `'B'`, then
140
+ * decoder `B` will be used. Otherwise, this will fail.
141
+ *
142
+ * This is effectively equivalent to `either(A, B)`, but will provide better
143
+ * error messages and is more performant at runtime because it doesn't have to
144
+ * try all decoders one by one.
145
+ */
146
+
147
+
148
+ function taggedUnion(field, mapping) {
149
+ var _object;
150
+
151
+ var base = (0, _objects.object)((_object = {}, _object[field] = (0, _utilities.prep)(String, oneOf(Object.keys(mapping))), _object)).transform(function (o) {
152
+ return o[field];
153
+ });
154
+ return base.peek_UNSTABLE(function (_ref) {
155
+ var blob = _ref[0],
156
+ key = _ref[1];
157
+ var decoder = mapping[key];
158
+ return decoder.decode(blob);
159
+ });
160
+ }
@@ -1,10 +1,11 @@
1
1
  // @flow strict
2
2
 
3
- import { annotate } from '../annotate';
4
- import { err, ok } from '../result';
3
+ import { define } from '../Decoder';
5
4
  import { indent, summarize } from '../_utils';
5
+ import { object } from './objects';
6
+ import { prep } from './utilities';
6
7
  import type { _Any } from '../_utils';
7
- import type { Decoder, DecodeResult, Scalar } from '../_types';
8
+ import type { Decoder, DecodeResult, Scalar } from '../Decoder';
8
9
 
9
10
  const EITHER_PREFIX = 'Either:\n';
10
11
 
@@ -47,7 +48,7 @@ function nest(errText: string): string {
47
48
  }
48
49
 
49
50
  // prettier-ignore
50
- interface EitherDecoderSignatures {
51
+ interface EitherT {
51
52
  <A>(a: Decoder<A>): Decoder<A>;
52
53
  <A, B>(a: Decoder<A>, b: Decoder<B>): Decoder<A | B>;
53
54
  <A, B, C>(a: Decoder<A>, b: Decoder<B>, c: Decoder<C>): Decoder<A | B | C>;
@@ -64,12 +65,12 @@ function _either(...decoders: $ReadOnlyArray<Decoder<mixed>>): Decoder<mixed> {
64
65
  throw new Error('Pass at least one decoder to either()');
65
66
  }
66
67
 
67
- return (blob: mixed) => {
68
+ return define((blob, _, err) => {
68
69
  // Collect errors here along the way
69
70
  const errors = [];
70
71
 
71
72
  for (let i = 0; i < decoders.length; i++) {
72
- const result: DecodeResult<mixed> = decoders[i](blob);
73
+ const result: DecodeResult<mixed> = decoders[i].decode(blob);
73
74
  if (result.ok) {
74
75
  return result;
75
76
  } else {
@@ -81,25 +82,74 @@ function _either(...decoders: $ReadOnlyArray<Decoder<mixed>>): Decoder<mixed> {
81
82
  const text =
82
83
  EITHER_PREFIX +
83
84
  errors.map((err) => nest(summarize(err).join('\n'))).join('\n');
84
- return err(annotate(blob, text));
85
- };
85
+ return err(text);
86
+ });
86
87
  }
87
88
 
88
- export const either: EitherDecoderSignatures = (_either: _Any);
89
+ /**
90
+ * Accepts values accepted by any of the given decoders.
91
+ *
92
+ * The decoders are tried on the input one by one, in the given order. The
93
+ * first one that accepts the input "wins". If all decoders reject the input,
94
+ * the input gets rejected.
95
+ */
96
+ export const either: EitherT = (_either: _Any);
89
97
 
98
+ /**
99
+ * Accepts any value that is strictly-equal (using `===`) to one of the
100
+ * specified values.
101
+ */
90
102
  export function oneOf<T: Scalar>(constants: $ReadOnlyArray<T>): Decoder<T> {
91
- return (blob: mixed) => {
103
+ return define((blob, ok, err) => {
92
104
  const winner = constants.find((c) => c === blob);
93
105
  if (winner !== undefined) {
94
106
  return ok(winner);
95
107
  }
96
108
  return err(
97
- annotate(
98
- blob,
99
- `Must be one of ${constants
100
- .map((value) => JSON.stringify(value))
101
- .join(', ')}`,
102
- ),
109
+ `Must be one of ${constants
110
+ .map((value) => JSON.stringify(value))
111
+ .join(', ')}`,
103
112
  );
104
- };
113
+ });
114
+ }
115
+
116
+ /**
117
+ * If you are decoding tagged unions you may want to use the `taggedUnion()`
118
+ * decoder instead of the general purpose `either()` decoder to get better
119
+ * error messages and better performance.
120
+ *
121
+ * This decoder is optimized for [tagged
122
+ * unions](https://en.wikipedia.org/wiki/Tagged_union), i.e. a union of
123
+ * objects where one field is used as the discriminator.
124
+ *
125
+ * ```ts
126
+ * const A = object({ tag: constant('A'), foo: string });
127
+ * const B = object({ tag: constant('B'), bar: number });
128
+ *
129
+ * const AorB = taggedUnion('tag', { A, B });
130
+ * // ^^^
131
+ * ```
132
+ *
133
+ * Decoding now works in two steps:
134
+ *
135
+ * 1. Look at the `'tag'` field in the incoming object (this is the field
136
+ * that decides which decoder will be used)
137
+ * 2. If the value is `'A'`, then decoder `A` will be used. If it's `'B'`, then
138
+ * decoder `B` will be used. Otherwise, this will fail.
139
+ *
140
+ * This is effectively equivalent to `either(A, B)`, but will provide better
141
+ * error messages and is more performant at runtime because it doesn't have to
142
+ * try all decoders one by one.
143
+ */
144
+ export function taggedUnion<O: { +[field: string]: Decoder<_Any>, ... }>(
145
+ field: string,
146
+ mapping: O,
147
+ ): Decoder<$Values<$ObjMap<O, <T>(Decoder<T>) => T>>> {
148
+ const base: Decoder<string> = object({
149
+ [field]: prep(String, oneOf(Object.keys(mapping))),
150
+ }).transform((o) => o[field]);
151
+ return base.peek_UNSTABLE(([blob, key]) => {
152
+ const decoder = mapping[key];
153
+ return decoder.decode(blob);
154
+ });
105
155
  }