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,194 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.exact = exact;
5
- exports.inexact = inexact;
6
- exports.object = object;
7
- exports.pojo = void 0;
8
-
9
- var Result = _interopRequireWildcard(require("../result"));
10
-
11
- var _annotate = require("../annotate");
12
-
13
- var _composition = require("./composition");
14
-
15
- 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); }
16
-
17
- 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; }
18
-
19
- function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
20
-
21
- function isPojo(o) {
22
- return o !== null && o !== undefined && typeof o === 'object' && // This still seems to be the only reliable way to determine whether
23
- // something is a pojo... ¯\_(ツ)_/¯
24
- // $FlowFixMe[method-unbinding]
25
- Object.prototype.toString.call(o) === '[object Object]';
26
- }
27
-
28
- function subtract(xs, ys) {
29
- var result = new Set();
30
- xs.forEach(function (x) {
31
- if (!ys.has(x)) {
32
- result.add(x);
33
- }
34
- });
35
- return result;
36
- }
37
-
38
- var pojo = function pojo(blob) {
39
- return isPojo(blob) ? Result.ok( // NOTE:
40
- // Since Flow 0.98, typeof o === 'object' refines to
41
- // {| +[string]: mixed |}
42
- // instead of
43
- // {| [string]: mixed |}
44
- //
45
- // For rationale, see https://github.com/facebook/flow/issues/7685.
46
- // In this case, we don't want to output a read-only version of
47
- // the object because it's up to the user of decoders to
48
- // determine what they want to do with the decoded output. If they
49
- // want to write items into the array, that's fine! The fastest
50
- // way to turn a read-only Object to a writeable one in ES6 seems
51
- // to be to use object-spread. (Going off this benchmark:
52
- // https://thecodebarbarian.com/object-assign-vs-object-spread.html)
53
- _extends({}, blob)) : Result.err((0, _annotate.annotate)(blob, 'Must be an object'));
54
- };
55
- /**
56
- * Given a mapping of fields-to-decoders, builds a decoder for an object type.
57
- *
58
- * For example, given decoders for a number and a string, we can construct an
59
- * "object description" like so:
60
- *
61
- * { id: number, name: string }
62
- *
63
- * Which is of type:
64
- *
65
- * { id: Decoder<number>, name: Decoder<string> }
66
- *
67
- * Passing this to object() will produce the following return type:
68
- *
69
- * Decoder<{ id: number, name: string }>
70
- *
71
- * Put simply: it'll "peel off" all of the nested Decoders, puts them together
72
- * in an object, and wraps it in a Decoder<...>.
73
- */
74
-
75
-
76
- exports.pojo = pojo;
77
-
78
- function object(mapping) {
79
- var known = new Set(Object.keys(mapping));
80
- return (0, _composition.compose)(pojo, function (blob) {
81
- var actual = new Set(Object.keys(blob)); // At this point, "missing" will also include all fields that may
82
- // validly be optional. We'll let the underlying decoder decide and
83
- // remove the key from this missing set if the decoder accepts the
84
- // value.
85
-
86
- var missing = subtract(known, actual);
87
- var record = {};
88
- var errors = null;
89
- Object.keys(mapping).forEach(function (key) {
90
- var decoder = mapping[key];
91
- var rawValue = blob[key];
92
- var result = decoder(rawValue);
93
-
94
- if (result.type === 'ok') {
95
- var value = result.value;
96
-
97
- if (value !== undefined) {
98
- record[key] = value;
99
- } // If this succeeded, remove the key from the missing keys
100
- // tracker
101
-
102
-
103
- missing["delete"](key);
104
- } else {
105
- var ann = result.error; // Keep track of the annotation, but don't return just yet. We
106
- // want to collect more error information.
107
-
108
- if (rawValue === undefined) {
109
- // Explicitly add it to the missing set if the value is
110
- // undefined. This covers explicit undefineds to be
111
- // treated the same as implicit undefineds (aka missing
112
- // keys).
113
- missing.add(key);
114
- } else {
115
- if (errors === null) {
116
- errors = {};
117
- }
118
-
119
- errors[key] = ann;
120
- }
121
- }
122
- }); // Deal with errors now. There are two classes of errors we want to
123
- // report. First of all, we want to report any inline errors in this
124
- // object. Lastly, any fields that are missing should be annotated on
125
- // the outer object itself.
126
-
127
- if (errors || missing.size > 0) {
128
- var objAnn = (0, _annotate.annotateObject)(blob);
129
-
130
- if (errors) {
131
- objAnn = (0, _annotate.merge)(objAnn, errors);
132
- }
133
-
134
- if (missing.size > 0) {
135
- var errMsg = Array.from(missing).map(function (key) {
136
- return "\"" + key + "\"";
137
- }).join(', ');
138
- var pluralized = missing.size > 1 ? 'keys' : 'key';
139
- objAnn = (0, _annotate.updateText)(objAnn, "Missing " + pluralized + ": " + errMsg);
140
- }
141
-
142
- return Result.err(objAnn);
143
- }
144
-
145
- return Result.ok(record);
146
- });
147
- }
148
-
149
- function exact(mapping) {
150
- // Check the inputted object for any superfluous keys
151
- var allowed = new Set(Object.keys(mapping));
152
- var checked = (0, _composition.compose)(pojo, function (blob) {
153
- var actual = new Set(Object.keys(blob));
154
- var superfluous = subtract(actual, allowed);
155
-
156
- if (superfluous.size > 0) {
157
- return Result.err((0, _annotate.annotate)(blob, "Superfluous keys: " + Array.from(superfluous).join(', ')));
158
- }
159
-
160
- return Result.ok(blob);
161
- }); // Defer to the "object" decoder for doing the real decoding work. Since
162
- // we made sure there are no superfluous keys in this structure, it's now
163
- // safe to force-cast it to an $Exact<> type.
164
-
165
- var decoder = object(mapping);
166
- return (0, _composition.compose)(checked, decoder);
167
- }
168
-
169
- function inexact(mapping) {
170
- return (0, _composition.compose)(pojo, function (blob) {
171
- var allkeys = new Set(Object.keys(blob));
172
- var decoder = (0, _composition.map)(object(mapping), function (safepart) {
173
- var safekeys = new Set(Object.keys(mapping)); // To account for hard-coded keys that aren't part of the input
174
-
175
- safekeys.forEach(function (k) {
176
- return allkeys.add(k);
177
- });
178
- var rv = {};
179
- allkeys.forEach(function (k) {
180
- if (safekeys.has(k)) {
181
- var value = safepart[k];
182
-
183
- if (value !== undefined) {
184
- rv[k] = value;
185
- }
186
- } else {
187
- rv[k] = blob[k];
188
- }
189
- });
190
- return rv;
191
- });
192
- return decoder(blob);
193
- });
194
- }
@@ -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,54 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.maybe = maybe;
5
- exports.nullable = nullable;
6
- exports.optional = optional;
7
-
8
- var Result = _interopRequireWildcard(require("../result"));
9
-
10
- var _annotate = require("../annotate");
11
-
12
- var _either = require("./either");
13
-
14
- var _constants = require("./constants");
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
- /**
21
- * Builds a Decoder that returns Ok for either `undefined` or `T` values,
22
- * given a Decoder for `T`. Err otherwise.
23
- */
24
- function optional(decoder) {
25
- return (0, _either.either)(_constants.undefined_, decoder);
26
- }
27
- /**
28
- * Builds a Decoder that returns Ok for either `null` or `T` values,
29
- * given a Decoder for `T`. Err otherwise.
30
- */
31
-
32
-
33
- function nullable(decoder) {
34
- return (0, _either.either)(_constants.null_, decoder);
35
- }
36
- /**
37
- * Decoder that only returns Ok for `null` or `undefined` inputs.
38
- * This is effectively equivalent to either(null_, undefined_), but combines
39
- * their error message output into a single line for convenience.
40
- */
41
-
42
-
43
- var undefined_or_null = function undefined_or_null(blob) {
44
- return blob === undefined || blob === null ? Result.ok(blob) : // Combine error message into a single line
45
- Result.err((0, _annotate.annotate)(blob, 'Must be undefined or null'));
46
- };
47
- /**
48
- * Decoder that only returns Ok for `null` or `undefined` inputs.
49
- */
50
-
51
-
52
- function maybe(decoder) {
53
- return (0, _either.either)(undefined_or_null, decoder);
54
- }
@@ -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,98 +0,0 @@
1
- "use strict";
2
-
3
- exports.__esModule = true;
4
- exports.nonEmptyString = exports.email = void 0;
5
- exports.regex = regex;
6
- exports.url = exports.string = void 0;
7
-
8
- var Result = _interopRequireWildcard(require("../result"));
9
-
10
- var _annotate = require("../annotate");
11
-
12
- var _composition = require("./composition");
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
- /** Match groups in this regex:
19
- * \1 - the scheme
20
- * \2 - the username/password (optional)
21
- * \3 - the host
22
- * \4 - the port (optional)
23
- * \5 - the path (optional)
24
- */
25
- 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]*)?)?$/; // The URL schemes the url() decoder accepts by default
26
-
27
- var DEFAULT_SCHEMES = ['https'];
28
- /**
29
- * Decoder that only returns Ok for string inputs. Err otherwise.
30
- */
31
-
32
- var string = function string(blob) {
33
- return typeof blob === 'string' ? Result.ok(blob) : Result.err((0, _annotate.annotate)(blob, 'Must be string'));
34
- };
35
- /**
36
- * Decoder that only returns Ok for non-empty string inputs. Err otherwise.
37
- */
38
-
39
-
40
- exports.string = string;
41
- var nonEmptyString = regex(/\S/, 'Must be non-empty string');
42
- /**
43
- * Decoder that only returns Ok for string inputs that match the regular
44
- * expression. Err otherwise. Will always validate that the input is a string
45
- * before testing the regex.
46
- */
47
-
48
- exports.nonEmptyString = nonEmptyString;
49
-
50
- function regex(regex, msg) {
51
- return (0, _composition.compose)(string, (0, _composition.predicate)(function (s) {
52
- return regex.test(s);
53
- }, msg));
54
- }
55
- /**
56
- * Decoder that only returns Ok for string inputs that match the almost perfect
57
- * email regex, taken from http://emailregex.com. Err otherwise.
58
- */
59
-
60
-
61
- var email = regex(/^(([^<>()[\]\\.,;:\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');
62
- /**
63
- * Decoder that only returns Ok for string inputs that match URLs of the
64
- * expected scheme. Defaults to only accept HTTPS URLs. Err otherwise.
65
- *
66
- * Variants that can be used:
67
- *
68
- * - url() accepts only https:// URLs
69
- * - url([]) accepts any URL scheme
70
- * - url(['http']) accepts only HTTP
71
- * - url(['https', 'git+ssh']) accepts both https:// and git+ssh:// URLs
72
- */
73
-
74
- exports.email = email;
75
-
76
- var url = function url(schemes) {
77
- if (schemes === void 0) {
78
- schemes = DEFAULT_SCHEMES;
79
- }
80
-
81
- return (0, _composition.compose)(string, function (value) {
82
- var matches = value.match(url_re);
83
-
84
- if (!matches) {
85
- return Result.err((0, _annotate.annotate)(value, 'Must be URL'));
86
- } else {
87
- var scheme = matches[1];
88
-
89
- if (schemes.length === 0 || schemes.includes(scheme.toLowerCase())) {
90
- return Result.ok(value);
91
- } else {
92
- return Result.err((0, _annotate.annotate)(value, "URL scheme must be any of: " + schemes.join(', ')));
93
- }
94
- }
95
- });
96
- };
97
-
98
- exports.url = url;
@@ -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
- });