decoders 1.25.4 → 2.0.0-beta1

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 (132) hide show
  1. package/CHANGELOG.md +30 -3
  2. package/cjs/_guard.js +26 -0
  3. package/cjs/_guard.js.flow +20 -0
  4. package/cjs/_types.js +1 -0
  5. package/cjs/_types.js.flow +20 -0
  6. package/cjs/_utils.js +108 -0
  7. package/cjs/_utils.js.flow +97 -0
  8. package/cjs/annotate.js +161 -0
  9. package/cjs/annotate.js.flow +218 -0
  10. package/cjs/format/index.js +12 -0
  11. package/cjs/format/index.js.flow +4 -0
  12. package/cjs/format/inline.js +146 -0
  13. package/cjs/format/inline.js.flow +122 -0
  14. package/cjs/format/short.js +10 -0
  15. package/cjs/format/short.js.flow +8 -0
  16. package/cjs/index.js +120 -0
  17. package/{index.js.flow → cjs/index.js.flow} +31 -24
  18. package/cjs/result.js +172 -0
  19. package/cjs/result.js.flow +166 -0
  20. package/cjs/stdlib/array.js +108 -0
  21. package/{array.js.flow → cjs/stdlib/array.js.flow} +22 -25
  22. package/cjs/stdlib/boolean.js +44 -0
  23. package/{boolean.js.flow → cjs/stdlib/boolean.js.flow} +8 -7
  24. package/cjs/stdlib/composition.js +56 -0
  25. package/{utils.js.flow → cjs/stdlib/composition.js.flow} +7 -22
  26. package/cjs/stdlib/constants.js +69 -0
  27. package/{constants.js.flow → cjs/stdlib/constants.js.flow} +13 -12
  28. package/cjs/stdlib/date.js +46 -0
  29. package/{date.js.flow → cjs/stdlib/date.js.flow} +9 -7
  30. package/cjs/stdlib/describe.js +26 -0
  31. package/{describe.js.flow → cjs/stdlib/describe.js.flow} +4 -4
  32. package/cjs/stdlib/dispatch.js +62 -0
  33. package/{dispatch.js.flow → cjs/stdlib/dispatch.js.flow} +6 -5
  34. package/cjs/stdlib/either.js +117 -0
  35. package/{either.js.flow → cjs/stdlib/either.js.flow} +55 -35
  36. package/cjs/stdlib/fail.js +21 -0
  37. package/cjs/stdlib/fail.js.flow +12 -0
  38. package/cjs/stdlib/instanceOf.js +19 -0
  39. package/{instanceOf.js.flow → cjs/stdlib/instanceOf.js.flow} +7 -8
  40. package/{json.js → cjs/stdlib/json.js} +3 -5
  41. package/{json.js.flow → cjs/stdlib/json.js.flow} +4 -4
  42. package/{lazy.js → cjs/stdlib/lazy.js} +1 -3
  43. package/{lazy.js.flow → cjs/stdlib/lazy.js.flow} +1 -1
  44. package/cjs/stdlib/mapping.js +67 -0
  45. package/cjs/stdlib/mapping.js.flow +54 -0
  46. package/cjs/stdlib/number.js +40 -0
  47. package/{number.js.flow → cjs/stdlib/number.js.flow} +10 -11
  48. package/cjs/stdlib/object.js +194 -0
  49. package/{object.js.flow → cjs/stdlib/object.js.flow} +44 -52
  50. package/cjs/stdlib/optional.js +54 -0
  51. package/{optional.js.flow → cjs/stdlib/optional.js.flow} +6 -7
  52. package/cjs/stdlib/string.js +98 -0
  53. package/{string.js.flow → cjs/stdlib/string.js.flow} +13 -12
  54. package/cjs/stdlib/tuple.js +173 -0
  55. package/{tuple.js.flow → cjs/stdlib/tuple.js.flow} +62 -63
  56. package/es/_guard.js +15 -0
  57. package/es/_types.js +0 -0
  58. package/es/_utils.js +93 -0
  59. package/es/annotate.js +144 -0
  60. package/es/format/index.js +2 -0
  61. package/es/format/inline.js +137 -0
  62. package/es/format/short.js +4 -0
  63. package/es/index.js +37 -0
  64. package/es/result.js +139 -0
  65. package/es/stdlib/array.js +91 -0
  66. package/es/stdlib/boolean.js +28 -0
  67. package/es/stdlib/composition.js +42 -0
  68. package/es/stdlib/constants.js +46 -0
  69. package/es/stdlib/date.js +28 -0
  70. package/{describe.js → es/stdlib/describe.js} +5 -11
  71. package/{dispatch.js → es/stdlib/dispatch.js} +8 -15
  72. package/es/stdlib/either.js +90 -0
  73. package/es/stdlib/fail.js +11 -0
  74. package/es/stdlib/instanceOf.js +8 -0
  75. package/es/stdlib/json.js +15 -0
  76. package/es/stdlib/lazy.js +11 -0
  77. package/es/stdlib/mapping.js +54 -0
  78. package/es/stdlib/number.js +25 -0
  79. package/es/stdlib/object.js +175 -0
  80. package/es/stdlib/optional.js +38 -0
  81. package/{string.js → es/stdlib/string.js} +18 -35
  82. package/es/stdlib/tuple.js +155 -0
  83. package/package.json +12 -7
  84. package/ts/_guard.d.ts +7 -0
  85. package/ts/_helpers.d.ts +79 -0
  86. package/{types.d.ts → ts/_types.d.ts} +3 -5
  87. package/{utils.d.ts → ts/_utils.d.ts} +3 -3
  88. package/ts/annotate.d.ts +58 -0
  89. package/{array.d.ts → ts/array.d.ts} +1 -1
  90. package/{boolean.d.ts → ts/boolean.d.ts} +1 -1
  91. package/{constants.d.ts → ts/constants.d.ts} +1 -1
  92. package/{date.d.ts → ts/date.d.ts} +1 -1
  93. package/{describe.d.ts → ts/describe.d.ts} +1 -1
  94. package/{dispatch.d.ts → ts/dispatch.d.ts} +3 -3
  95. package/{either.d.ts → ts/either.d.ts} +8 -8
  96. package/{fail.d.ts → ts/fail.d.ts} +1 -1
  97. package/ts/index.d.ts +42 -0
  98. package/ts/inline.d.ts +3 -0
  99. package/{instanceOf.d.ts → ts/instanceOf.d.ts} +1 -1
  100. package/{json.d.ts → ts/json.d.ts} +1 -1
  101. package/{lazy.d.ts → ts/lazy.d.ts} +1 -1
  102. package/{mapping.d.ts → ts/mapping.d.ts} +1 -1
  103. package/{number.d.ts → ts/number.d.ts} +1 -1
  104. package/{object.d.ts → ts/object.d.ts} +8 -8
  105. package/{optional.d.ts → ts/optional.d.ts} +1 -1
  106. package/ts/result.d.ts +39 -0
  107. package/ts/short.d.ts +3 -0
  108. package/{string.d.ts → ts/string.d.ts} +1 -1
  109. package/{tuple.d.ts → ts/tuple.d.ts} +5 -5
  110. package/array.js +0 -133
  111. package/boolean.js +0 -42
  112. package/constants.js +0 -67
  113. package/date.js +0 -42
  114. package/either.js +0 -85
  115. package/fail.js +0 -19
  116. package/fail.js.flow +0 -13
  117. package/guard.d.ts +0 -7
  118. package/guard.js +0 -30
  119. package/guard.js.flow +0 -36
  120. package/helpers.d.ts +0 -62
  121. package/index.d.ts +0 -38
  122. package/index.js +0 -397
  123. package/instanceOf.js +0 -17
  124. package/mapping.js +0 -113
  125. package/mapping.js.flow +0 -71
  126. package/number.js +0 -38
  127. package/object.js +0 -254
  128. package/optional.js +0 -52
  129. package/tuple.js +0 -199
  130. package/types.js +0 -5
  131. package/types.js.flow +0 -26
  132. package/utils.js +0 -70
@@ -1,11 +1,10 @@
1
1
  // @flow strict
2
2
 
3
- import { annotate, annotateFields, isAnnotation } from 'debrief';
4
- import type { Annotation } from 'debrief';
5
- import { Err, Ok } from 'lemons/Result';
6
-
7
- import type { $DecoderType, Decoder } from './types';
8
- import { compose, map } from './utils';
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';
9
8
 
10
9
  // $FlowFixMe[unclear-type] (not really an issue) - deliberate use of `any` - not sure how we should get rid of this
11
10
  type AnyDecoder = any;
@@ -27,17 +26,17 @@ function isPojo(o: mixed): boolean %checks {
27
26
 
28
27
  function subtract(xs: Set<string>, ys: Set<string>): Set<string> {
29
28
  const result = new Set();
30
- for (const x of xs) {
29
+ xs.forEach((x) => {
31
30
  if (!ys.has(x)) {
32
31
  result.add(x);
33
32
  }
34
- }
33
+ });
35
34
  return result;
36
35
  }
37
36
 
38
37
  export const pojo: Decoder<{| [string]: mixed |}> = (blob: mixed) => {
39
38
  return isPojo(blob)
40
- ? Ok(
39
+ ? Result.ok(
41
40
  // NOTE:
42
41
  // Since Flow 0.98, typeof o === 'object' refines to
43
42
  // {| +[string]: mixed |}
@@ -52,9 +51,9 @@ export const pojo: Decoder<{| [string]: mixed |}> = (blob: mixed) => {
52
51
  // way to turn a read-only Object to a writeable one in ES6 seems
53
52
  // to be to use object-spread. (Going off this benchmark:
54
53
  // https://thecodebarbarian.com/object-assign-vs-object-spread.html)
55
- { ...blob }
54
+ { ...blob },
56
55
  )
57
- : Err(annotate(blob, 'Must be an object'));
56
+ : Result.err(annotate(blob, 'Must be an object'));
58
57
  };
59
58
 
60
59
  /**
@@ -77,10 +76,10 @@ export const pojo: Decoder<{| [string]: mixed |}> = (blob: mixed) => {
77
76
  * in an object, and wraps it in a Decoder<...>.
78
77
  */
79
78
  export function object<O: { +[field: string]: AnyDecoder, ... }>(
80
- mapping: O
81
- ): Decoder<$ObjMap<O, $DecoderType>> {
79
+ mapping: O,
80
+ ): Decoder<$ObjMap<O, DecoderType>> {
82
81
  const known = new Set(Object.keys(mapping));
83
- return compose(pojo, (blob: {| [string]: mixed |}) => {
82
+ return compose(pojo, (blob: { +[string]: mixed }) => {
84
83
  const actual = new Set(Object.keys(blob));
85
84
 
86
85
  // At this point, "missing" will also include all fields that may
@@ -90,16 +89,15 @@ export function object<O: { +[field: string]: AnyDecoder, ... }>(
90
89
  const missing = subtract(known, actual);
91
90
 
92
91
  let record = {};
93
- const fieldErrors: { [key: string]: Annotation } = { ...null };
92
+ let errors: { [key: string]: Annotation } | null = null;
94
93
 
95
- // NOTE: We're using .keys() here over .entries(), since .entries()
96
- // will type the value part as "mixed"
97
- for (const key of Object.keys(mapping)) {
94
+ Object.keys(mapping).forEach((key) => {
98
95
  const decoder = mapping[key];
99
96
  const rawValue = blob[key];
100
97
  const result = decoder(rawValue);
101
- try {
102
- const value = result.unwrap();
98
+
99
+ if (result.type === 'ok') {
100
+ const value = result.value;
103
101
  if (value !== undefined) {
104
102
  record[key] = value;
105
103
  }
@@ -107,11 +105,8 @@ export function object<O: { +[field: string]: AnyDecoder, ... }>(
107
105
  // If this succeeded, remove the key from the missing keys
108
106
  // tracker
109
107
  missing.delete(key);
110
- } catch (ann) {
111
- /* istanbul ignore next */
112
- if (!isAnnotation(ann)) {
113
- throw ann;
114
- }
108
+ } else {
109
+ const ann = result.error;
115
110
 
116
111
  // Keep track of the annotation, but don't return just yet. We
117
112
  // want to collect more error information.
@@ -122,24 +117,23 @@ export function object<O: { +[field: string]: AnyDecoder, ... }>(
122
117
  // keys).
123
118
  missing.add(key);
124
119
  } else {
125
- fieldErrors[key] = ann;
120
+ if (errors === null) {
121
+ errors = {};
122
+ }
123
+ errors[key] = ann;
126
124
  }
127
125
  }
128
- }
126
+ });
129
127
 
130
128
  // Deal with errors now. There are two classes of errors we want to
131
129
  // report. First of all, we want to report any inline errors in this
132
130
  // object. Lastly, any fields that are missing should be annotated on
133
131
  // the outer object itself.
134
- const fieldsWithErrors = Object.keys(fieldErrors);
135
- if (fieldsWithErrors.length > 0 || missing.size > 0) {
136
- let err;
132
+ if (errors || missing.size > 0) {
133
+ let objAnn = annotateObject(blob);
137
134
 
138
- if (fieldsWithErrors.length > 0) {
139
- const errorlist = fieldsWithErrors.map((k) => [k, fieldErrors[k]]);
140
- err = annotateFields(blob, errorlist);
141
- } else {
142
- err = annotate(blob);
135
+ if (errors) {
136
+ objAnn = merge(objAnn, errors);
143
137
  }
144
138
 
145
139
  if (missing.size > 0) {
@@ -147,54 +141,52 @@ export function object<O: { +[field: string]: AnyDecoder, ... }>(
147
141
  .map((key) => `"${key}"`)
148
142
  .join(', ');
149
143
  const pluralized = missing.size > 1 ? 'keys' : 'key';
150
- err = annotate(err, `Missing ${pluralized}: ${errMsg}`);
144
+ objAnn = updateText(objAnn, `Missing ${pluralized}: ${errMsg}`);
151
145
  }
152
146
 
153
- return Err(err);
147
+ return Result.err(objAnn);
154
148
  }
155
149
 
156
- return Ok(record);
150
+ return Result.ok(record);
157
151
  });
158
152
  }
159
153
 
160
154
  export function exact<O: { +[field: string]: AnyDecoder, ... }>(
161
- mapping: O
162
- ): Decoder<$ObjMap<$Exact<O>, $DecoderType>> {
155
+ mapping: O,
156
+ ): Decoder<$ObjMap<$Exact<O>, DecoderType>> {
163
157
  // Check the inputted object for any superfluous keys
164
158
  const allowed = new Set(Object.keys(mapping));
165
159
  const checked = compose(pojo, (blob: {| [string]: mixed |}) => {
166
160
  const actual = new Set(Object.keys(blob));
167
161
  const superfluous = subtract(actual, allowed);
168
162
  if (superfluous.size > 0) {
169
- return Err(
170
- annotate(blob, `Superfluous keys: ${Array.from(superfluous).join(', ')}`)
163
+ return Result.err(
164
+ annotate(blob, `Superfluous keys: ${Array.from(superfluous).join(', ')}`),
171
165
  );
172
166
  }
173
- return Ok(blob);
167
+ return Result.ok(blob);
174
168
  });
175
169
 
176
170
  // Defer to the "object" decoder for doing the real decoding work. Since
177
171
  // we made sure there are no superfluous keys in this structure, it's now
178
172
  // safe to force-cast it to an $Exact<> type.
179
- const decoder = ((object(mapping): cast): Decoder<$ObjMap<$Exact<O>, $DecoderType>>);
173
+ const decoder = ((object(mapping): cast): Decoder<$ObjMap<$Exact<O>, DecoderType>>);
180
174
  return compose(checked, decoder);
181
175
  }
182
176
 
183
177
  export function inexact<O: { +[field: string]: AnyDecoder }>(
184
- mapping: O
185
- ): Decoder<$ObjMap<O, $DecoderType> & { +[string]: mixed }> {
178
+ mapping: O,
179
+ ): Decoder<$ObjMap<O, DecoderType> & { +[string]: mixed }> {
186
180
  return compose(pojo, (blob: {| [string]: mixed |}) => {
187
181
  const allkeys = new Set(Object.keys(blob));
188
- const decoder = map(object(mapping), (safepart: $ObjMap<O, $DecoderType>) => {
182
+ const decoder = map(object(mapping), (safepart: $ObjMap<O, DecoderType>) => {
189
183
  const safekeys = new Set(Object.keys(mapping));
190
184
 
191
185
  // To account for hard-coded keys that aren't part of the input
192
- for (const k of safekeys) {
193
- allkeys.add(k);
194
- }
186
+ safekeys.forEach((k) => allkeys.add(k));
195
187
 
196
188
  const rv = {};
197
- for (const k of allkeys) {
189
+ allkeys.forEach((k) => {
198
190
  if (safekeys.has(k)) {
199
191
  const value = safepart[k];
200
192
  if (value !== undefined) {
@@ -203,7 +195,7 @@ export function inexact<O: { +[field: string]: AnyDecoder }>(
203
195
  } else {
204
196
  rv[k] = blob[k];
205
197
  }
206
- }
198
+ });
207
199
  return rv;
208
200
  });
209
201
  return decoder(blob);
@@ -0,0 +1,54 @@
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,11 +1,10 @@
1
1
  // @flow strict
2
2
 
3
- import { annotate } from 'debrief';
4
- import { Err, Ok } from 'lemons/Result';
5
-
6
- import { null_, undefined_ } from './constants';
3
+ import * as Result from '../result';
4
+ import { annotate } from '../annotate';
7
5
  import { either } from './either';
8
- import type { Decoder } from './types';
6
+ import { null_, undefined_ } from './constants';
7
+ import type { Decoder } from '../_types';
9
8
 
10
9
  /**
11
10
  * Builds a Decoder that returns Ok for either `undefined` or `T` values,
@@ -30,9 +29,9 @@ export function nullable<T>(decoder: Decoder<T>): Decoder<null | T> {
30
29
  */
31
30
  const undefined_or_null: Decoder<null | void> = (blob: mixed) =>
32
31
  blob === undefined || blob === null
33
- ? Ok(blob)
32
+ ? Result.ok(blob)
34
33
  : // Combine error message into a single line
35
- Err(annotate(blob, 'Must be undefined or null'));
34
+ Result.err(annotate(blob, 'Must be undefined or null'));
36
35
 
37
36
  /**
38
37
  * Decoder that only returns Ok for `null` or `undefined` inputs.
@@ -0,0 +1,98 @@
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,10 +1,9 @@
1
1
  // @flow strict
2
2
 
3
- import { annotate } from 'debrief';
4
- import { Err, Ok } from 'lemons/Result';
5
-
6
- import type { Decoder } from './types';
7
- import { compose, predicate } from './utils';
3
+ import * as Result from '../result';
4
+ import { annotate } from '../annotate';
5
+ import { compose, predicate } from './composition';
6
+ import type { Decoder } from '../_types';
8
7
 
9
8
  /** Match groups in this regex:
10
9
  * \1 - the scheme
@@ -23,7 +22,9 @@ const DEFAULT_SCHEMES = ['https'];
23
22
  * Decoder that only returns Ok for string inputs. Err otherwise.
24
23
  */
25
24
  export const string: Decoder<string> = (blob: mixed) => {
26
- return typeof blob === 'string' ? Ok(blob) : Err(annotate(blob, 'Must be string'));
25
+ return typeof blob === 'string'
26
+ ? Result.ok(blob)
27
+ : Result.err(annotate(blob, 'Must be string'));
27
28
  };
28
29
 
29
30
  /**
@@ -39,7 +40,7 @@ export const nonEmptyString: Decoder<string> = regex(/\S/, 'Must be non-empty st
39
40
  export function regex(regex: RegExp, msg: string): Decoder<string> {
40
41
  return compose(
41
42
  string,
42
- predicate((s) => regex.test(s), msg)
43
+ predicate((s) => regex.test(s), msg),
43
44
  );
44
45
  }
45
46
 
@@ -49,7 +50,7 @@ export function regex(regex: RegExp, msg: string): Decoder<string> {
49
50
  */
50
51
  export const email: Decoder<string> = regex(
51
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,}))$/,
52
- 'Must be email'
53
+ 'Must be email',
53
54
  );
54
55
 
55
56
  /**
@@ -67,14 +68,14 @@ export const url = (schemes: $ReadOnlyArray<string> = DEFAULT_SCHEMES): Decoder<
67
68
  compose(string, (value: string) => {
68
69
  const matches = value.match(url_re);
69
70
  if (!matches) {
70
- return Err(annotate(value, 'Must be URL'));
71
+ return Result.err(annotate(value, 'Must be URL'));
71
72
  } else {
72
73
  const scheme = matches[1];
73
74
  if (schemes.length === 0 || schemes.includes(scheme.toLowerCase())) {
74
- return Ok(value);
75
+ return Result.ok(value);
75
76
  } else {
76
- return Err(
77
- annotate(value, `URL scheme must be any of: ${schemes.join(', ')}`)
77
+ return Result.err(
78
+ annotate(value, `URL scheme must be any of: ${schemes.join(', ')}`),
78
79
  );
79
80
  }
80
81
  }
@@ -0,0 +1,173 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.tuple1 = tuple1;
5
+ exports.tuple2 = tuple2;
6
+ exports.tuple3 = tuple3;
7
+ exports.tuple4 = tuple4;
8
+ exports.tuple5 = tuple5;
9
+ exports.tuple6 = tuple6;
10
+
11
+ var _annotate = require("../annotate");
12
+
13
+ var _composition = require("./composition");
14
+
15
+ var _result = require("../result");
16
+
17
+ var _array = require("./array");
18
+
19
+ var ntuple = function ntuple(n) {
20
+ return (0, _composition.compose)(_array.poja, (0, _composition.predicate)(function (arr) {
21
+ return arr.length === n;
22
+ }, "Must be a " + n + "-tuple"));
23
+ };
24
+ /**
25
+ * Builds a Decoder that returns Ok for 1-tuple of [T], given a Decoder for T.
26
+ * Err otherwise.
27
+ */
28
+
29
+
30
+ function tuple1(decoder1) {
31
+ return (0, _composition.compose)(ntuple(1), function (blobs) {
32
+ var blob1 = blobs[0];
33
+ var result1 = decoder1(blob1);
34
+
35
+ try {
36
+ return (0, _result.ok)([(0, _result.unwrap)(result1)]);
37
+ } catch (e) {
38
+ // If a decoder error has happened while unwrapping all the
39
+ // results, try to construct a good error message
40
+ return (0, _result.err)((0, _annotate.annotate)((0, _result.errValue)(result1)));
41
+ }
42
+ });
43
+ }
44
+ /**
45
+ * Builds a Decoder that returns Ok for 2-tuples of [T1, T2], given Decoders
46
+ * for T1 and T2. Err otherwise.
47
+ */
48
+
49
+
50
+ function tuple2(decoder1, decoder2) {
51
+ return (0, _composition.compose)(ntuple(2), function (blobs) {
52
+ var blob1 = blobs[0],
53
+ blob2 = blobs[1];
54
+ var result1 = decoder1(blob1);
55
+ var result2 = decoder2(blob2);
56
+
57
+ try {
58
+ return (0, _result.ok)([(0, _result.unwrap)(result1), (0, _result.unwrap)(result2)]);
59
+ } catch (e) {
60
+ // If a decoder error has happened while unwrapping all the
61
+ // results, try to construct a good error message
62
+ return (0, _result.err)((0, _annotate.annotate)([(0, _result.isErr)(result1) ? (0, _result.errValue)(result1) : (0, _result.value)(result1), (0, _result.isErr)(result2) ? (0, _result.errValue)(result2) : (0, _result.value)(result2)]));
63
+ }
64
+ });
65
+ }
66
+ /**
67
+ * Builds a Decoder that returns Ok for 3-tuples of [T1, T2, T3], given
68
+ * Decoders for T1, T2, and T3. Err otherwise.
69
+ */
70
+
71
+
72
+ function tuple3(decoder1, decoder2, decoder3) {
73
+ return (0, _composition.compose)(ntuple(3), function (blobs) {
74
+ var blob1 = blobs[0],
75
+ blob2 = blobs[1],
76
+ blob3 = blobs[2];
77
+ var result1 = decoder1(blob1);
78
+ var result2 = decoder2(blob2);
79
+ var result3 = decoder3(blob3);
80
+
81
+ try {
82
+ return (0, _result.ok)([(0, _result.unwrap)(result1), (0, _result.unwrap)(result2), (0, _result.unwrap)(result3)]);
83
+ } catch (e) {
84
+ // If a decoder error has happened while unwrapping all the
85
+ // results, try to construct a good error message
86
+ return (0, _result.err)((0, _annotate.annotate)([(0, _result.isErr)(result1) ? (0, _result.errValue)(result1) : (0, _result.value)(result1), (0, _result.isErr)(result2) ? (0, _result.errValue)(result2) : (0, _result.value)(result2), (0, _result.isErr)(result3) ? (0, _result.errValue)(result3) : (0, _result.value)(result3)]));
87
+ }
88
+ });
89
+ }
90
+ /**
91
+ * Builds a Decoder that returns Ok for 4-tuples of [T1, T2, T3, T4], given
92
+ * Decoders for T1, T2, T3, and T4. Err otherwise.
93
+ */
94
+
95
+
96
+ function tuple4(decoder1, decoder2, decoder3, decoder4) {
97
+ return (0, _composition.compose)(ntuple(4), function (blobs) {
98
+ var blob1 = blobs[0],
99
+ blob2 = blobs[1],
100
+ blob3 = blobs[2],
101
+ blob4 = blobs[3];
102
+ var result1 = decoder1(blob1);
103
+ var result2 = decoder2(blob2);
104
+ var result3 = decoder3(blob3);
105
+ var result4 = decoder4(blob4);
106
+
107
+ try {
108
+ return (0, _result.ok)([(0, _result.unwrap)(result1), (0, _result.unwrap)(result2), (0, _result.unwrap)(result3), (0, _result.unwrap)(result4)]);
109
+ } catch (e) {
110
+ // If a decoder error has happened while unwrapping all the
111
+ // results, try to construct a good error message
112
+ return (0, _result.err)((0, _annotate.annotate)([(0, _result.isErr)(result1) ? (0, _result.errValue)(result1) : (0, _result.value)(result1), (0, _result.isErr)(result2) ? (0, _result.errValue)(result2) : (0, _result.value)(result2), (0, _result.isErr)(result3) ? (0, _result.errValue)(result3) : (0, _result.value)(result3), (0, _result.isErr)(result4) ? (0, _result.errValue)(result4) : (0, _result.value)(result4)]));
113
+ }
114
+ });
115
+ }
116
+ /**
117
+ * Builds a Decoder that returns Ok for 5-tuples of [T1, T2, T3, T4, T5], given
118
+ * Decoders for T1, T2, T3, T4, and T5. Err otherwise.
119
+ */
120
+
121
+
122
+ function tuple5(decoder1, decoder2, decoder3, decoder4, decoder5) {
123
+ return (0, _composition.compose)(ntuple(5), function (blobs) {
124
+ var blob1 = blobs[0],
125
+ blob2 = blobs[1],
126
+ blob3 = blobs[2],
127
+ blob4 = blobs[3],
128
+ blob5 = blobs[4];
129
+ var result1 = decoder1(blob1);
130
+ var result2 = decoder2(blob2);
131
+ var result3 = decoder3(blob3);
132
+ var result4 = decoder4(blob4);
133
+ var result5 = decoder5(blob5);
134
+
135
+ try {
136
+ return (0, _result.ok)([(0, _result.unwrap)(result1), (0, _result.unwrap)(result2), (0, _result.unwrap)(result3), (0, _result.unwrap)(result4), (0, _result.unwrap)(result5)]);
137
+ } catch (e) {
138
+ // If a decoder error has happened while unwrapping all the
139
+ // results, try to construct a good error message
140
+ return (0, _result.err)((0, _annotate.annotate)([(0, _result.isErr)(result1) ? (0, _result.errValue)(result1) : (0, _result.value)(result1), (0, _result.isErr)(result2) ? (0, _result.errValue)(result2) : (0, _result.value)(result2), (0, _result.isErr)(result3) ? (0, _result.errValue)(result3) : (0, _result.value)(result3), (0, _result.isErr)(result4) ? (0, _result.errValue)(result4) : (0, _result.value)(result4), (0, _result.isErr)(result5) ? (0, _result.errValue)(result5) : (0, _result.value)(result5)]));
141
+ }
142
+ });
143
+ }
144
+ /**
145
+ * Builds a Decoder that returns Ok for 5-tuples of [T1, T2, T3, T4, T5], given
146
+ * Decoders for T1, T2, T3, T4, T5, and T6. Err otherwise.
147
+ */
148
+
149
+
150
+ function tuple6(decoder1, decoder2, decoder3, decoder4, decoder5, decoder6) {
151
+ return (0, _composition.compose)(ntuple(6), function (blobs) {
152
+ var blob1 = blobs[0],
153
+ blob2 = blobs[1],
154
+ blob3 = blobs[2],
155
+ blob4 = blobs[3],
156
+ blob5 = blobs[4],
157
+ blob6 = blobs[5];
158
+ var result1 = decoder1(blob1);
159
+ var result2 = decoder2(blob2);
160
+ var result3 = decoder3(blob3);
161
+ var result4 = decoder4(blob4);
162
+ var result5 = decoder5(blob5);
163
+ var result6 = decoder6(blob6);
164
+
165
+ try {
166
+ return (0, _result.ok)([(0, _result.unwrap)(result1), (0, _result.unwrap)(result2), (0, _result.unwrap)(result3), (0, _result.unwrap)(result4), (0, _result.unwrap)(result5), (0, _result.unwrap)(result6)]);
167
+ } catch (e) {
168
+ // If a decoder error has happened while unwrapping all the
169
+ // results, try to construct a good error message
170
+ return (0, _result.err)((0, _annotate.annotate)([(0, _result.isErr)(result1) ? (0, _result.errValue)(result1) : (0, _result.value)(result1), (0, _result.isErr)(result2) ? (0, _result.errValue)(result2) : (0, _result.value)(result2), (0, _result.isErr)(result3) ? (0, _result.errValue)(result3) : (0, _result.value)(result3), (0, _result.isErr)(result4) ? (0, _result.errValue)(result4) : (0, _result.value)(result4), (0, _result.isErr)(result5) ? (0, _result.errValue)(result5) : (0, _result.value)(result5), (0, _result.isErr)(result6) ? (0, _result.errValue)(result6) : (0, _result.value)(result6)]));
171
+ }
172
+ });
173
+ }