decoders 2.0.0-beta1 → 2.0.0-beta13

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 (165) hide show
  1. package/CHANGELOG.md +53 -5
  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/NotSupportedTSVersion.d.ts +1 -0
  7. package/README.md +124 -961
  8. package/_utils.d.ts +9 -0
  9. package/{cjs/_utils.js → _utils.js} +12 -18
  10. package/{cjs/_utils.js.flow → _utils.js.flow} +15 -19
  11. package/{es/_utils.js → _utils.mjs} +11 -15
  12. package/{ts/annotate.d.ts → annotate.d.ts} +25 -21
  13. package/{cjs/annotate.js → annotate.js} +0 -0
  14. package/{cjs/annotate.js.flow → annotate.js.flow} +0 -0
  15. package/{es/annotate.js → annotate.mjs} +0 -0
  16. package/format.d.ts +6 -0
  17. package/{cjs/format/inline.js → format.js} +7 -2
  18. package/{cjs/format/inline.js.flow → format.js.flow} +9 -3
  19. package/{es/format/inline.js → format.mjs} +5 -2
  20. package/index.d.ts +40 -0
  21. package/index.js +89 -0
  22. package/index.js.flow +44 -0
  23. package/index.mjs +11 -0
  24. package/{ts → lib}/_helpers.d.ts +0 -0
  25. package/lib/arrays.d.ts +59 -0
  26. package/lib/arrays.js +139 -0
  27. package/lib/arrays.js.flow +138 -0
  28. package/lib/arrays.mjs +124 -0
  29. package/lib/basics.d.ts +93 -0
  30. package/lib/basics.js +144 -0
  31. package/lib/basics.js.flow +124 -0
  32. package/lib/basics.mjs +120 -0
  33. package/lib/booleans.d.ts +16 -0
  34. package/lib/booleans.js +35 -0
  35. package/lib/booleans.js.flow +22 -0
  36. package/lib/booleans.mjs +25 -0
  37. package/lib/dates.d.ts +15 -0
  38. package/lib/dates.js +44 -0
  39. package/lib/dates.js.flow +40 -0
  40. package/lib/dates.mjs +34 -0
  41. package/lib/json.d.ts +35 -0
  42. package/lib/json.js +55 -0
  43. package/lib/json.js.flow +50 -0
  44. package/lib/json.mjs +40 -0
  45. package/lib/numbers.d.ts +31 -0
  46. package/lib/numbers.js +51 -0
  47. package/lib/numbers.js.flow +48 -0
  48. package/lib/numbers.mjs +41 -0
  49. package/lib/objects.d.ts +75 -0
  50. package/lib/objects.js +240 -0
  51. package/lib/objects.js.flow +246 -0
  52. package/lib/objects.mjs +223 -0
  53. package/lib/strings.d.ts +56 -0
  54. package/lib/strings.js +101 -0
  55. package/lib/strings.js.flow +90 -0
  56. package/lib/strings.mjs +82 -0
  57. package/lib/unions.d.ts +55 -0
  58. package/lib/unions.js +160 -0
  59. package/lib/unions.js.flow +155 -0
  60. package/lib/unions.mjs +146 -0
  61. package/lib/utilities.d.ts +34 -0
  62. package/lib/utilities.js +75 -0
  63. package/lib/utilities.js.flow +65 -0
  64. package/lib/utilities.mjs +60 -0
  65. package/package.json +79 -29
  66. package/result.d.ts +16 -0
  67. package/result.js +34 -0
  68. package/result.js.flow +26 -0
  69. package/result.mjs +27 -0
  70. package/cjs/_guard.js +0 -26
  71. package/cjs/_guard.js.flow +0 -20
  72. package/cjs/_types.js +0 -1
  73. package/cjs/_types.js.flow +0 -20
  74. package/cjs/format/index.js +0 -12
  75. package/cjs/format/index.js.flow +0 -4
  76. package/cjs/format/short.js +0 -10
  77. package/cjs/format/short.js.flow +0 -8
  78. package/cjs/index.js +0 -120
  79. package/cjs/index.js.flow +0 -63
  80. package/cjs/result.js +0 -172
  81. package/cjs/result.js.flow +0 -166
  82. package/cjs/stdlib/array.js +0 -108
  83. package/cjs/stdlib/array.js.flow +0 -103
  84. package/cjs/stdlib/boolean.js +0 -44
  85. package/cjs/stdlib/boolean.js.flow +0 -29
  86. package/cjs/stdlib/composition.js +0 -56
  87. package/cjs/stdlib/composition.js.flow +0 -43
  88. package/cjs/stdlib/constants.js +0 -69
  89. package/cjs/stdlib/constants.js.flow +0 -46
  90. package/cjs/stdlib/date.js +0 -46
  91. package/cjs/stdlib/date.js.flow +0 -40
  92. package/cjs/stdlib/describe.js +0 -26
  93. package/cjs/stdlib/describe.js.flow +0 -17
  94. package/cjs/stdlib/dispatch.js +0 -62
  95. package/cjs/stdlib/dispatch.js.flow +0 -58
  96. package/cjs/stdlib/either.js +0 -117
  97. package/cjs/stdlib/either.js.flow +0 -151
  98. package/cjs/stdlib/fail.js +0 -21
  99. package/cjs/stdlib/fail.js.flow +0 -12
  100. package/cjs/stdlib/instanceOf.js +0 -19
  101. package/cjs/stdlib/instanceOf.js.flow +0 -20
  102. package/cjs/stdlib/json.js +0 -31
  103. package/cjs/stdlib/json.js.flow +0 -28
  104. package/cjs/stdlib/lazy.js +0 -16
  105. package/cjs/stdlib/lazy.js.flow +0 -15
  106. package/cjs/stdlib/mapping.js +0 -67
  107. package/cjs/stdlib/mapping.js.flow +0 -54
  108. package/cjs/stdlib/number.js +0 -40
  109. package/cjs/stdlib/number.js.flow +0 -34
  110. package/cjs/stdlib/object.js +0 -194
  111. package/cjs/stdlib/object.js.flow +0 -203
  112. package/cjs/stdlib/optional.js +0 -54
  113. package/cjs/stdlib/optional.js.flow +0 -41
  114. package/cjs/stdlib/string.js +0 -98
  115. package/cjs/stdlib/string.js.flow +0 -82
  116. package/cjs/stdlib/tuple.js +0 -173
  117. package/cjs/stdlib/tuple.js.flow +0 -220
  118. package/es/_guard.js +0 -15
  119. package/es/_types.js +0 -0
  120. package/es/format/index.js +0 -2
  121. package/es/format/short.js +0 -4
  122. package/es/index.js +0 -37
  123. package/es/result.js +0 -139
  124. package/es/stdlib/array.js +0 -91
  125. package/es/stdlib/boolean.js +0 -28
  126. package/es/stdlib/composition.js +0 -42
  127. package/es/stdlib/constants.js +0 -46
  128. package/es/stdlib/date.js +0 -28
  129. package/es/stdlib/describe.js +0 -16
  130. package/es/stdlib/dispatch.js +0 -51
  131. package/es/stdlib/either.js +0 -90
  132. package/es/stdlib/fail.js +0 -11
  133. package/es/stdlib/instanceOf.js +0 -8
  134. package/es/stdlib/json.js +0 -15
  135. package/es/stdlib/lazy.js +0 -11
  136. package/es/stdlib/mapping.js +0 -54
  137. package/es/stdlib/number.js +0 -25
  138. package/es/stdlib/object.js +0 -175
  139. package/es/stdlib/optional.js +0 -38
  140. package/es/stdlib/string.js +0 -76
  141. package/es/stdlib/tuple.js +0 -155
  142. package/ts/_guard.d.ts +0 -7
  143. package/ts/_types.d.ts +0 -16
  144. package/ts/_utils.d.ts +0 -13
  145. package/ts/array.d.ts +0 -5
  146. package/ts/boolean.d.ts +0 -5
  147. package/ts/constants.d.ts +0 -11
  148. package/ts/date.d.ts +0 -4
  149. package/ts/describe.d.ts +0 -3
  150. package/ts/dispatch.d.ts +0 -8
  151. package/ts/either.d.ts +0 -61
  152. package/ts/fail.d.ts +0 -3
  153. package/ts/index.d.ts +0 -42
  154. package/ts/inline.d.ts +0 -3
  155. package/ts/instanceOf.d.ts +0 -3
  156. package/ts/json.d.ts +0 -11
  157. package/ts/lazy.d.ts +0 -3
  158. package/ts/mapping.d.ts +0 -4
  159. package/ts/number.d.ts +0 -6
  160. package/ts/object.d.ts +0 -33
  161. package/ts/optional.d.ts +0 -5
  162. package/ts/result.d.ts +0 -39
  163. package/ts/short.d.ts +0 -3
  164. package/ts/string.d.ts +0 -7
  165. package/ts/tuple.d.ts +0 -30
@@ -1,103 +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, 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
- }
@@ -1,44 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.truthy = exports.numericBoolean = exports["boolean"] = void 0;
5
-
6
- var Result = _interopRequireWildcard(require("../result"));
7
-
8
- var _annotate = require("../annotate");
9
-
10
- var _composition = require("./composition");
11
-
12
- var _number = require("./number");
13
-
14
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
15
-
16
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
17
-
18
- /**
19
- * Decoder that only returns Ok for boolean inputs. Err otherwise.
20
- */
21
- var _boolean = function _boolean(blob) {
22
- return typeof blob === 'boolean' ? Result.ok(blob) : Result.err((0, _annotate.annotate)(blob, 'Must be boolean'));
23
- };
24
- /**
25
- * Decoder that returns true for all truthy values, and false otherwise. Never fails.
26
- */
27
-
28
-
29
- exports["boolean"] = _boolean;
30
-
31
- var truthy = function truthy(blob) {
32
- return Result.ok(!!blob);
33
- };
34
- /**
35
- * Decoder that only returns Ok for numeric input values representing booleans.
36
- * Returns their boolean representation. Err otherwise.
37
- */
38
-
39
-
40
- exports.truthy = truthy;
41
- var numericBoolean = (0, _composition.map)(_number.number, function (n) {
42
- return !!n;
43
- });
44
- exports.numericBoolean = numericBoolean;
@@ -1,29 +0,0 @@
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);
@@ -1,56 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.compose = compose;
5
- exports.map = map;
6
- exports.predicate = predicate;
7
-
8
- var Result = _interopRequireWildcard(require("../result"));
9
-
10
- var _annotate = require("../annotate");
11
-
12
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
13
-
14
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
15
-
16
- /**
17
- * Given a decoder T and a mapping function from T's to V's, returns a decoder
18
- * for V's. This is useful to change the original input data.
19
- */
20
- function map(decoder, mapper) {
21
- return compose(decoder, function (x) {
22
- try {
23
- return Result.ok(mapper(x));
24
- } catch (e) {
25
- return Result.err((0, _annotate.annotate)(x, e instanceof Error ? e.message : String(e)));
26
- }
27
- });
28
- }
29
- /**
30
- * Compose two decoders by passing the result of the first into the second.
31
- * The second decoder may assume as its input type the output type of the first
32
- * decoder (so it's not necessary to accept the typical "mixed"). This is
33
- * useful for "narrowing down" the checks. For example, if you want to write
34
- * a decoder for positive numbers, you can compose it from an existing decoder
35
- * for any number, and a decoder that, assuming a number, checks if it's
36
- * positive. Very often combined with the predicate() helper as the second
37
- * argument.
38
- */
39
-
40
-
41
- function compose(decoder, next) {
42
- return function (blob) {
43
- return Result.andThen(decoder(blob), next);
44
- };
45
- }
46
- /**
47
- * Factory function returning a Decoder<T>, given a predicate function that
48
- * accepts/rejects the input of type T.
49
- */
50
-
51
-
52
- function predicate(predicate, msg) {
53
- return function (value) {
54
- return predicate(value) ? Result.ok(value) : Result.err((0, _annotate.annotate)(value, msg));
55
- };
56
- }
@@ -1,43 +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
- * 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
- }
@@ -1,69 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.constant = constant;
5
- exports.hardcoded = hardcoded;
6
- exports.unknown = exports.undefined_ = exports.null_ = exports.mixed = void 0;
7
-
8
- var Result = _interopRequireWildcard(require("../result"));
9
-
10
- var _annotate = require("../annotate");
11
-
12
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
13
-
14
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
15
-
16
- /**
17
- * Decoder that only returns Ok for `null` inputs. Err otherwise.
18
- */
19
- var null_ = function null_(blob) {
20
- return blob === null ? Result.ok(blob) : Result.err((0, _annotate.annotate)(blob, 'Must be null'));
21
- };
22
- /**
23
- * Decoder that only returns Ok for `undefined` inputs. Err otherwise.
24
- */
25
-
26
-
27
- exports.null_ = null_;
28
-
29
- var undefined_ = function undefined_(blob) {
30
- return blob === undefined ? Result.ok(blob) : Result.err((0, _annotate.annotate)(blob, 'Must be undefined'));
31
- };
32
- /**
33
- * Decoder that only returns Ok for the given value constant. Err otherwise.
34
- */
35
-
36
-
37
- exports.undefined_ = undefined_;
38
-
39
- function constant(value) {
40
- return function (blob) {
41
- return blob === value ? Result.ok(value) : Result.err((0, _annotate.annotate)(blob, "Must be constant " + String(value)));
42
- };
43
- }
44
- /**
45
- * Decoder that always returns Ok for the given hardcoded value, no matter what the input.
46
- */
47
-
48
-
49
- function hardcoded(value) {
50
- return function () {
51
- return Result.ok(value);
52
- };
53
- }
54
- /**
55
- * Decoder that always returns Ok for the given hardcoded value, no matter what the input.
56
- */
57
-
58
-
59
- var unknown = function unknown(blob) {
60
- return Result.ok(blob);
61
- };
62
- /**
63
- * Alias of unknown.
64
- */
65
-
66
-
67
- exports.unknown = unknown;
68
- var mixed = unknown;
69
- exports.mixed = mixed;
@@ -1,46 +0,0 @@
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;
@@ -1,46 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.iso8601 = exports.date = void 0;
5
-
6
- var Result = _interopRequireWildcard(require("../result"));
7
-
8
- var _annotate = require("../annotate");
9
-
10
- var _utils = require("../_utils");
11
-
12
- var _composition = require("./composition");
13
-
14
- var _string = require("./string");
15
-
16
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
17
-
18
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
19
-
20
- // Only matches the shape. This "over-matches" some values that still aren't
21
- // valid dates (like 9999-99-99), but those will be caught by JS Date's
22
- // internal validations
23
- var iso8601_re = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.]\d+)?(?:Z|[+-]\d{2}:?\d{2})$/;
24
-
25
- var date = function date(value) {
26
- return (0, _utils.isDate)(value) ? Result.ok(value) : Result.err((0, _annotate.annotate)(value, 'Must be a Date'));
27
- };
28
- /**
29
- * Decoder that only returns Ok for strings that are valid ISO8601 date
30
- * strings. Err otherwise.
31
- */
32
-
33
-
34
- exports.date = date;
35
- var iso8601 = (0, _composition.map)( // Input itself needs to match the ISO8601 regex...
36
- (0, _string.regex)(iso8601_re, 'Must be ISO8601 format'), // Make sure it is a _valid_ date
37
- function (value) {
38
- var date = new Date(value);
39
-
40
- if (isNaN(date.getTime())) {
41
- throw new Error('Must be valid date/time value');
42
- }
43
-
44
- return date;
45
- });
46
- exports.iso8601 = iso8601;
@@ -1,40 +0,0 @@
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
- );
@@ -1,26 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.describe = describe;
5
-
6
- var Result = _interopRequireWildcard(require("../result"));
7
-
8
- var _annotate = require("../annotate");
9
-
10
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
11
-
12
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
13
-
14
- /**
15
- * Wrap another decoder, and override the error message in case it fails. This
16
- * is useful to "simplify" otherwise potentially complex error messages, or to
17
- * use language in those error messages that can be relayed to end users (for
18
- * example to show in form errors).
19
- */
20
- function describe(decoder, message) {
21
- return function (blob) {
22
- return Result.mapError(decoder(blob), function (err) {
23
- return (0, _annotate.annotate)(err, message);
24
- });
25
- };
26
- }
@@ -1,17 +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
- * 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
- }
@@ -1,62 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.dispatch = dispatch;
5
-
6
- var Result = _interopRequireWildcard(require("../result"));
7
-
8
- var _object2 = require("./object");
9
-
10
- var _either = require("./either");
11
-
12
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
13
-
14
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
15
-
16
- /**
17
- * Dispatches to one of several given decoders, based on the value found at
18
- * runtime in the given field. For example, suppose you have these decoders:
19
- *
20
- * const rectangle = object({
21
- * type: constant('rect'),
22
- * x: number,
23
- * y: number,
24
- * width: number,
25
- * height: number,
26
- * });
27
- *
28
- * const circle = object({
29
- * type: constant('circle'),
30
- * cx: number,
31
- * cy: number,
32
- * r: number,
33
- * });
34
- *
35
- * Then these two decoders are equivalent:
36
- *
37
- * const shape = either(rectangle, circle)
38
- * const shape = dispatch('type', { rectangle, circle })
39
- *
40
- * Will be of type Decoder<Rectangle | Circle>.
41
- *
42
- * But the dispatch version will typically be more runtime-efficient. The
43
- * reason is that it will first do minimal work to "look ahead" into the `type`
44
- * field here, and based on that value, pick the decoder to invoke.
45
- *
46
- * The `either` version will simply try to invoke each decoder, until it finds
47
- * one that matches.
48
- *
49
- * Also, the error messages will be less ambiguous using `dispatch()`.
50
- */
51
- function dispatch(field, mapping) {
52
- var _object;
53
-
54
- var base = (0, _object2.object)((_object = {}, _object[field] = (0, _either.oneOf)(Object.keys(mapping)), _object));
55
- return function (blob) {
56
- return Result.andThen(base(blob), function (baseObj) {
57
- var decoderName = baseObj[field];
58
- var decoder = mapping[decoderName];
59
- return decoder(blob);
60
- });
61
- };
62
- }
@@ -1,58 +0,0 @@
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
- }