decoders 1.25.2 → 1.26.0-test1
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.
- package/CHANGELOG.md +16 -0
- package/{array.js → cjs/array.js} +0 -0
- package/{array.js.flow → cjs/array.js.flow} +0 -0
- package/{boolean.js → cjs/boolean.js} +1 -1
- package/{boolean.js.flow → cjs/boolean.js.flow} +0 -0
- package/{constants.js → cjs/constants.js} +1 -1
- package/{constants.js.flow → cjs/constants.js.flow} +2 -2
- package/{date.js → cjs/date.js} +0 -0
- package/{date.js.flow → cjs/date.js.flow} +0 -0
- package/{describe.js → cjs/describe.js} +0 -0
- package/{describe.js.flow → cjs/describe.js.flow} +0 -0
- package/{dispatch.js → cjs/dispatch.js} +0 -0
- package/{dispatch.js.flow → cjs/dispatch.js.flow} +0 -0
- package/{either.js → cjs/either.js} +0 -0
- package/{either.js.flow → cjs/either.js.flow} +1 -3
- package/{fail.js → cjs/fail.js} +0 -0
- package/{fail.js.flow → cjs/fail.js.flow} +0 -0
- package/{guard.js → cjs/guard.js} +0 -0
- package/{guard.js.flow → cjs/guard.js.flow} +0 -0
- package/{index.js → cjs/index.js} +110 -110
- package/{index.js.flow → cjs/index.js.flow} +0 -0
- package/{instanceOf.js → cjs/instanceOf.js} +0 -0
- package/{instanceOf.js.flow → cjs/instanceOf.js.flow} +0 -0
- package/{json.js → cjs/json.js} +1 -1
- package/{json.js.flow → cjs/json.js.flow} +0 -0
- package/{lazy.js → cjs/lazy.js} +0 -0
- package/{lazy.js.flow → cjs/lazy.js.flow} +0 -0
- package/{mapping.js → cjs/mapping.js} +1 -1
- package/{mapping.js.flow → cjs/mapping.js.flow} +0 -0
- package/{number.js → cjs/number.js} +1 -1
- package/{number.js.flow → cjs/number.js.flow} +0 -0
- package/{object.js → cjs/object.js} +1 -1
- package/{object.js.flow → cjs/object.js.flow} +0 -0
- package/{optional.js → cjs/optional.js} +2 -2
- package/{optional.js.flow → cjs/optional.js.flow} +0 -0
- package/{string.js → cjs/string.js} +2 -1
- package/{string.js.flow → cjs/string.js.flow} +0 -0
- package/{tuple.js → cjs/tuple.js} +0 -0
- package/{tuple.js.flow → cjs/tuple.js.flow} +0 -0
- package/{types.js → cjs/types.js} +0 -0
- package/{types.js.flow → cjs/types.js.flow} +2 -0
- package/{utils.js → cjs/utils.js} +2 -2
- package/{utils.js.flow → cjs/utils.js.flow} +0 -0
- package/es/index.js +1212 -0
- package/package.json +4 -3
- package/{array.d.ts → ts/array.d.ts} +1 -1
- package/{boolean.d.ts → ts/boolean.d.ts} +0 -0
- package/{constants.d.ts → ts/constants.d.ts} +1 -2
- package/{date.d.ts → ts/date.d.ts} +0 -0
- package/{describe.d.ts → ts/describe.d.ts} +0 -0
- package/{dispatch.d.ts → ts/dispatch.d.ts} +0 -0
- package/{either.d.ts → ts/either.d.ts} +1 -3
- package/{fail.d.ts → ts/fail.d.ts} +0 -0
- package/{guard.d.ts → ts/guard.d.ts} +0 -0
- package/ts/helpers.d.ts +79 -0
- package/{index.d.ts → ts/index.d.ts} +1 -1
- package/{instanceOf.d.ts → ts/instanceOf.d.ts} +0 -0
- package/{json.d.ts → ts/json.d.ts} +0 -0
- package/{lazy.d.ts → ts/lazy.d.ts} +0 -0
- package/{mapping.d.ts → ts/mapping.d.ts} +0 -0
- package/{number.d.ts → ts/number.d.ts} +0 -0
- package/{object.d.ts → ts/object.d.ts} +3 -3
- package/{optional.d.ts → ts/optional.d.ts} +0 -0
- package/{string.d.ts → ts/string.d.ts} +0 -0
- package/{tuple.d.ts → ts/tuple.d.ts} +0 -0
- package/{types.d.ts → ts/types.d.ts} +2 -0
- package/{utils.d.ts → ts/utils.d.ts} +0 -0
- package/helpers.d.ts +0 -62
package/es/index.js
ADDED
|
@@ -0,0 +1,1212 @@
|
|
|
1
|
+
import { summarize, serialize, annotate, indent, isAnnotation, annotateFields } from 'debrief';
|
|
2
|
+
import { Ok, Err } from 'lemons/Result';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Alternative for serialize() that does not echo back the input value.
|
|
6
|
+
*/
|
|
7
|
+
function serializeSimple(annotation) {
|
|
8
|
+
return summarize(annotation).join('\n');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function guard(decoder, options) {
|
|
12
|
+
var o = options || {};
|
|
13
|
+
var style = o.style || 'inline';
|
|
14
|
+
var serializer = style === 'inline' ? serialize // Normal serializer, which echoes back inputted value and inlines errors
|
|
15
|
+
: serializeSimple; // Only returns error messages, without echoing back input
|
|
16
|
+
|
|
17
|
+
return function (blob) {
|
|
18
|
+
return decoder(blob).mapError(function (annotation) {
|
|
19
|
+
var err = new Error('\n' + serializer(annotation));
|
|
20
|
+
err.name = 'Decoding error';
|
|
21
|
+
return err;
|
|
22
|
+
}).unwrap();
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* `x instanceof Date` checks are unreliable across stack frames (that information
|
|
28
|
+
* might get lost by the JS runtime), so we'll have to reside to more runtime
|
|
29
|
+
* inspection checks.
|
|
30
|
+
*
|
|
31
|
+
* Taken from https://stackoverflow.com/a/44198641
|
|
32
|
+
*/
|
|
33
|
+
var isDate = function isDate(value) {
|
|
34
|
+
return value !== undefined && value !== null && // $FlowFixMe[method-unbinding]
|
|
35
|
+
Object.prototype.toString.call(value) === '[object Date]' && !isNaN(value);
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Given a decoder T and a mapping function from T's to V's, returns a decoder
|
|
39
|
+
* for V's. This is useful to change the original input data.
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
function map(decoder, mapper) {
|
|
43
|
+
return compose(decoder, function (x) {
|
|
44
|
+
try {
|
|
45
|
+
return Ok(mapper(x));
|
|
46
|
+
} catch (e) {
|
|
47
|
+
return Err(annotate(x, e instanceof Error ? e.message : String(e)));
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Compose two decoders by passing the result of the first into the second.
|
|
53
|
+
* The second decoder may assume as its input type the output type of the first
|
|
54
|
+
* decoder (so it's not necessary to accept the typical "mixed"). This is
|
|
55
|
+
* useful for "narrowing down" the checks. For example, if you want to write
|
|
56
|
+
* a decoder for positive numbers, you can compose it from an existing decoder
|
|
57
|
+
* for any number, and a decoder that, assuming a number, checks if it's
|
|
58
|
+
* positive. Very often combined with the predicate() helper as the second
|
|
59
|
+
* argument.
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
function compose(decoder, next) {
|
|
63
|
+
return function (blob) {
|
|
64
|
+
return decoder(blob).andThen(next);
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Factory function returning a Decoder<T>, given a predicate function that
|
|
69
|
+
* accepts/rejects the input of type T.
|
|
70
|
+
*/
|
|
71
|
+
|
|
72
|
+
function predicate(predicate, msg) {
|
|
73
|
+
return function (value) {
|
|
74
|
+
return predicate(value) ? Ok(value) : Err(annotate(value, msg));
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function ownKeys(object, enumerableOnly) {
|
|
79
|
+
var keys = Object.keys(object);
|
|
80
|
+
|
|
81
|
+
if (Object.getOwnPropertySymbols) {
|
|
82
|
+
var symbols = Object.getOwnPropertySymbols(object);
|
|
83
|
+
|
|
84
|
+
if (enumerableOnly) {
|
|
85
|
+
symbols = symbols.filter(function (sym) {
|
|
86
|
+
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
keys.push.apply(keys, symbols);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return keys;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function _objectSpread2(target) {
|
|
97
|
+
for (var i = 1; i < arguments.length; i++) {
|
|
98
|
+
var source = arguments[i] != null ? arguments[i] : {};
|
|
99
|
+
|
|
100
|
+
if (i % 2) {
|
|
101
|
+
ownKeys(Object(source), true).forEach(function (key) {
|
|
102
|
+
_defineProperty(target, key, source[key]);
|
|
103
|
+
});
|
|
104
|
+
} else if (Object.getOwnPropertyDescriptors) {
|
|
105
|
+
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
|
|
106
|
+
} else {
|
|
107
|
+
ownKeys(Object(source)).forEach(function (key) {
|
|
108
|
+
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return target;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function _typeof(obj) {
|
|
117
|
+
"@babel/helpers - typeof";
|
|
118
|
+
|
|
119
|
+
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
|
|
120
|
+
_typeof = function (obj) {
|
|
121
|
+
return typeof obj;
|
|
122
|
+
};
|
|
123
|
+
} else {
|
|
124
|
+
_typeof = function (obj) {
|
|
125
|
+
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return _typeof(obj);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function _defineProperty(obj, key, value) {
|
|
133
|
+
if (key in obj) {
|
|
134
|
+
Object.defineProperty(obj, key, {
|
|
135
|
+
value: value,
|
|
136
|
+
enumerable: true,
|
|
137
|
+
configurable: true,
|
|
138
|
+
writable: true
|
|
139
|
+
});
|
|
140
|
+
} else {
|
|
141
|
+
obj[key] = value;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return obj;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function _slicedToArray(arr, i) {
|
|
148
|
+
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function _toConsumableArray(arr) {
|
|
152
|
+
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function _arrayWithoutHoles(arr) {
|
|
156
|
+
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function _arrayWithHoles(arr) {
|
|
160
|
+
if (Array.isArray(arr)) return arr;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function _iterableToArray(iter) {
|
|
164
|
+
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function _iterableToArrayLimit(arr, i) {
|
|
168
|
+
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
|
|
169
|
+
|
|
170
|
+
if (_i == null) return;
|
|
171
|
+
var _arr = [];
|
|
172
|
+
var _n = true;
|
|
173
|
+
var _d = false;
|
|
174
|
+
|
|
175
|
+
var _s, _e;
|
|
176
|
+
|
|
177
|
+
try {
|
|
178
|
+
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
|
|
179
|
+
_arr.push(_s.value);
|
|
180
|
+
|
|
181
|
+
if (i && _arr.length === i) break;
|
|
182
|
+
}
|
|
183
|
+
} catch (err) {
|
|
184
|
+
_d = true;
|
|
185
|
+
_e = err;
|
|
186
|
+
} finally {
|
|
187
|
+
try {
|
|
188
|
+
if (!_n && _i["return"] != null) _i["return"]();
|
|
189
|
+
} finally {
|
|
190
|
+
if (_d) throw _e;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return _arr;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function _unsupportedIterableToArray(o, minLen) {
|
|
198
|
+
if (!o) return;
|
|
199
|
+
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
|
|
200
|
+
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
201
|
+
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
202
|
+
if (n === "Map" || n === "Set") return Array.from(o);
|
|
203
|
+
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function _arrayLikeToArray(arr, len) {
|
|
207
|
+
if (len == null || len > arr.length) len = arr.length;
|
|
208
|
+
|
|
209
|
+
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
|
|
210
|
+
|
|
211
|
+
return arr2;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function _nonIterableSpread() {
|
|
215
|
+
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function _nonIterableRest() {
|
|
219
|
+
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function _createForOfIteratorHelper(o, allowArrayLike) {
|
|
223
|
+
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
|
|
224
|
+
|
|
225
|
+
if (!it) {
|
|
226
|
+
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
|
|
227
|
+
if (it) o = it;
|
|
228
|
+
var i = 0;
|
|
229
|
+
|
|
230
|
+
var F = function () {};
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
s: F,
|
|
234
|
+
n: function () {
|
|
235
|
+
if (i >= o.length) return {
|
|
236
|
+
done: true
|
|
237
|
+
};
|
|
238
|
+
return {
|
|
239
|
+
done: false,
|
|
240
|
+
value: o[i++]
|
|
241
|
+
};
|
|
242
|
+
},
|
|
243
|
+
e: function (e) {
|
|
244
|
+
throw e;
|
|
245
|
+
},
|
|
246
|
+
f: F
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
var normalCompletion = true,
|
|
254
|
+
didErr = false,
|
|
255
|
+
err;
|
|
256
|
+
return {
|
|
257
|
+
s: function () {
|
|
258
|
+
it = it.call(o);
|
|
259
|
+
},
|
|
260
|
+
n: function () {
|
|
261
|
+
var step = it.next();
|
|
262
|
+
normalCompletion = step.done;
|
|
263
|
+
return step;
|
|
264
|
+
},
|
|
265
|
+
e: function (e) {
|
|
266
|
+
didErr = true;
|
|
267
|
+
err = e;
|
|
268
|
+
},
|
|
269
|
+
f: function () {
|
|
270
|
+
try {
|
|
271
|
+
if (!normalCompletion && it.return != null) it.return();
|
|
272
|
+
} finally {
|
|
273
|
+
if (didErr) throw err;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Like a "Plain Old JavaScript Object", but for arrays: "Plain Old JavaScript
|
|
281
|
+
* Array" ^_^
|
|
282
|
+
*/
|
|
283
|
+
|
|
284
|
+
var poja = function poja(blob) {
|
|
285
|
+
if (!Array.isArray(blob)) {
|
|
286
|
+
return Err(annotate(blob, 'Must be an array'));
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
return Ok( // NOTE: Since Flow 0.98, Array.isArray() returns $ReadOnlyArray<mixed>
|
|
290
|
+
// instead of Array<mixed>. For rationale, see
|
|
291
|
+
// https://github.com/facebook/flow/issues/7684. In this case, we
|
|
292
|
+
// don't want to output read-only types because it's up to the user of
|
|
293
|
+
// decoders to determine what they want to do with the decoded output.
|
|
294
|
+
// If they want to write items into the array, that's fine!
|
|
295
|
+
// The fastest way to turn a read-only array into a normal array in
|
|
296
|
+
// Javascript is to use .slice() on it, see this benchmark:
|
|
297
|
+
// http://jsben.ch/lO6C5
|
|
298
|
+
blob.slice());
|
|
299
|
+
};
|
|
300
|
+
/**
|
|
301
|
+
* Given an iterable of Result instances, exhaust them all and return:
|
|
302
|
+
* - An [index, err] tuple, indicating the (index of the) first Err instance
|
|
303
|
+
* encountered; or
|
|
304
|
+
* - a new Ok with an array of all unwrapped Ok'ed values
|
|
305
|
+
*/
|
|
306
|
+
|
|
307
|
+
function all(iterable, blobs) {
|
|
308
|
+
var results = [];
|
|
309
|
+
var index = 0;
|
|
310
|
+
|
|
311
|
+
var _iterator = _createForOfIteratorHelper(iterable),
|
|
312
|
+
_step;
|
|
313
|
+
|
|
314
|
+
try {
|
|
315
|
+
for (_iterator.s(); !(_step = _iterator.n()).done;) {
|
|
316
|
+
var result = _step.value;
|
|
317
|
+
|
|
318
|
+
try {
|
|
319
|
+
var value = result.unwrap();
|
|
320
|
+
results.push(value);
|
|
321
|
+
} catch (ann) {
|
|
322
|
+
// Rewrite the annotation to include the index information, and inject it into the original blob
|
|
323
|
+
var clone = _toConsumableArray(blobs);
|
|
324
|
+
|
|
325
|
+
clone.splice(index, 1, annotate(ann, ann.annotation !== undefined ? "".concat(ann.annotation, " (at index ").concat(index, ")") : "index ".concat(index))); // const errValue = [];
|
|
326
|
+
// if (index > 0) {
|
|
327
|
+
// errValue.push('...'); // TODO: make special mark, not string!
|
|
328
|
+
// }
|
|
329
|
+
// errValue.push(
|
|
330
|
+
// );
|
|
331
|
+
// if (index < iterable.length - 1) {
|
|
332
|
+
// errValue.push('...'); // TODO: make special mark, not string!
|
|
333
|
+
// }
|
|
334
|
+
|
|
335
|
+
return Err(annotate(clone));
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
index++;
|
|
339
|
+
}
|
|
340
|
+
} catch (err) {
|
|
341
|
+
_iterator.e(err);
|
|
342
|
+
} finally {
|
|
343
|
+
_iterator.f();
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
return Ok(results);
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Given a T, builds a decoder that assumes an array input and returns an
|
|
350
|
+
* Array<T>.
|
|
351
|
+
*/
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
function members(decoder) {
|
|
355
|
+
return function (blobs) {
|
|
356
|
+
var results = blobs.map(decoder);
|
|
357
|
+
var result = all(results, blobs);
|
|
358
|
+
return result;
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Builds a Decoder that returns Ok for values of `Array<T>`, given a Decoder
|
|
363
|
+
* for `T`. Err otherwise.
|
|
364
|
+
*/
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
function array(decoder) {
|
|
368
|
+
return compose(poja, members(decoder));
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Builds a Decoder that returns Ok for values of `Array<T>`, but will reject
|
|
372
|
+
* empty arrays.
|
|
373
|
+
*/
|
|
374
|
+
|
|
375
|
+
function nonEmptyArray(decoder) {
|
|
376
|
+
return compose(array(decoder), predicate(function (arr) {
|
|
377
|
+
return arr.length > 0;
|
|
378
|
+
}, 'Must be non-empty array'));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
var anyNumber = function anyNumber(blob) {
|
|
382
|
+
return typeof blob === 'number' && !Number.isNaN(blob) ? Ok(blob) : Err(annotate(blob, 'Must be number'));
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
var isInteger = function isInteger(n) {
|
|
386
|
+
return Number.isInteger(n);
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
var isFinite = function isFinite(n) {
|
|
390
|
+
return Number.isFinite(n);
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
var number = compose(anyNumber, predicate(isFinite, 'Number must be finite'));
|
|
394
|
+
var positiveNumber = compose(number, predicate(function (n) {
|
|
395
|
+
return n >= 0;
|
|
396
|
+
}, 'Number must be positive')); // Integers
|
|
397
|
+
|
|
398
|
+
var integer = compose(number, predicate(isInteger, 'Number must be an integer'));
|
|
399
|
+
var positiveInteger = compose(integer, predicate(function (n) {
|
|
400
|
+
return n >= 0;
|
|
401
|
+
}, 'Number must be positive'));
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Decoder that only returns Ok for boolean inputs. Err otherwise.
|
|
405
|
+
*/
|
|
406
|
+
|
|
407
|
+
var _boolean = function _boolean(blob) {
|
|
408
|
+
return typeof blob === 'boolean' ? Ok(blob) : Err(annotate(blob, 'Must be boolean'));
|
|
409
|
+
};
|
|
410
|
+
var truthy = function truthy(blob) {
|
|
411
|
+
return Ok(!!blob);
|
|
412
|
+
};
|
|
413
|
+
/**
|
|
414
|
+
* Decoder that only returns Ok for numeric input values representing booleans.
|
|
415
|
+
* Returns their boolean representation. Err otherwise.
|
|
416
|
+
*/
|
|
417
|
+
|
|
418
|
+
var numericBoolean = map(number, function (n) {
|
|
419
|
+
return !!n;
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Decoder that only returns Ok for `null` inputs. Err otherwise.
|
|
424
|
+
*/
|
|
425
|
+
var null_ = function null_(blob) {
|
|
426
|
+
return blob === null ? Ok(blob) : Err(annotate(blob, 'Must be null'));
|
|
427
|
+
};
|
|
428
|
+
/**
|
|
429
|
+
* Decoder that only returns Ok for `undefined` inputs. Err otherwise.
|
|
430
|
+
*/
|
|
431
|
+
|
|
432
|
+
var undefined_ = function undefined_(blob) {
|
|
433
|
+
return blob === undefined ? Ok(blob) : Err(annotate(blob, 'Must be undefined'));
|
|
434
|
+
};
|
|
435
|
+
/**
|
|
436
|
+
* Decoder that only returns Ok for the given value constant. Err otherwise.
|
|
437
|
+
*/
|
|
438
|
+
|
|
439
|
+
function constant(value) {
|
|
440
|
+
return function (blob) {
|
|
441
|
+
return blob === value ? Ok(value) : Err(annotate(blob, "Must be constant ".concat(String(value))));
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Decoder that always returns Ok for the given hardcoded value, no matter what the input.
|
|
446
|
+
*/
|
|
447
|
+
|
|
448
|
+
function hardcoded(value) {
|
|
449
|
+
return function (_) {
|
|
450
|
+
return Ok(value);
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Decoder that always returns Ok for the given hardcoded value, no matter what the input.
|
|
455
|
+
*/
|
|
456
|
+
|
|
457
|
+
var mixed = function mixed(blob) {
|
|
458
|
+
return Ok(blob);
|
|
459
|
+
};
|
|
460
|
+
/**
|
|
461
|
+
* Alias of mixed.
|
|
462
|
+
*/
|
|
463
|
+
|
|
464
|
+
var unknown = mixed;
|
|
465
|
+
|
|
466
|
+
/** Match groups in this regex:
|
|
467
|
+
* \1 - the scheme
|
|
468
|
+
* \2 - the username/password (optional)
|
|
469
|
+
* \3 - the host
|
|
470
|
+
* \4 - the port (optional)
|
|
471
|
+
* \5 - the path (optional)
|
|
472
|
+
*/
|
|
473
|
+
|
|
474
|
+
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
|
|
475
|
+
|
|
476
|
+
var DEFAULT_SCHEMES = ['https'];
|
|
477
|
+
/**
|
|
478
|
+
* Decoder that only returns Ok for string inputs. Err otherwise.
|
|
479
|
+
*/
|
|
480
|
+
|
|
481
|
+
var string = function string(blob) {
|
|
482
|
+
return typeof blob === 'string' ? Ok(blob) : Err(annotate(blob, 'Must be string'));
|
|
483
|
+
};
|
|
484
|
+
/**
|
|
485
|
+
* Decoder that only returns Ok for non-empty string inputs. Err otherwise.
|
|
486
|
+
*/
|
|
487
|
+
|
|
488
|
+
var nonEmptyString = regex(/\S/, 'Must be non-empty string');
|
|
489
|
+
/**
|
|
490
|
+
* Decoder that only returns Ok for string inputs that match the regular
|
|
491
|
+
* expression. Err otherwise. Will always validate that the input is a string
|
|
492
|
+
* before testing the regex.
|
|
493
|
+
*/
|
|
494
|
+
|
|
495
|
+
function regex(regex, msg) {
|
|
496
|
+
return compose(string, predicate(function (s) {
|
|
497
|
+
return regex.test(s);
|
|
498
|
+
}, msg));
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Decoder that only returns Ok for string inputs that match the almost perfect
|
|
502
|
+
* email regex, taken from http://emailregex.com. Err otherwise.
|
|
503
|
+
*/
|
|
504
|
+
|
|
505
|
+
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');
|
|
506
|
+
/**
|
|
507
|
+
* Decoder that only returns Ok for string inputs that match URLs of the
|
|
508
|
+
* expected scheme. Defaults to only accept HTTPS URLs. Err otherwise.
|
|
509
|
+
*
|
|
510
|
+
* Variants that can be used:
|
|
511
|
+
*
|
|
512
|
+
* - url() accepts only https:// URLs
|
|
513
|
+
* - url([]) accepts any URL scheme
|
|
514
|
+
* - url(['http']) accepts only HTTP
|
|
515
|
+
* - url(['https', 'git+ssh']) accepts both https:// and git+ssh:// URLs
|
|
516
|
+
*/
|
|
517
|
+
|
|
518
|
+
var url = function url() {
|
|
519
|
+
var schemes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_SCHEMES;
|
|
520
|
+
return compose(string, function (value) {
|
|
521
|
+
var matches = value.match(url_re);
|
|
522
|
+
|
|
523
|
+
if (!matches) {
|
|
524
|
+
return Err(annotate(value, 'Must be URL'));
|
|
525
|
+
} else {
|
|
526
|
+
var scheme = matches[1];
|
|
527
|
+
|
|
528
|
+
if (schemes.length === 0 || schemes.includes(scheme.toLowerCase())) {
|
|
529
|
+
return Ok(value);
|
|
530
|
+
} else {
|
|
531
|
+
return Err(annotate(value, "URL scheme must be any of: ".concat(schemes.join(', '))));
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
});
|
|
535
|
+
};
|
|
536
|
+
|
|
537
|
+
// Only matches the shape. This "over-matches" some values that still aren't
|
|
538
|
+
// valid dates (like 9999-99-99), but those will be caught by JS Date's
|
|
539
|
+
// internal validations
|
|
540
|
+
var iso8601_re = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.]\d+)?(?:Z|[+-]\d{2}:?\d{2})$/;
|
|
541
|
+
var date = function date(value) {
|
|
542
|
+
return isDate(value) ? Ok(value) : Err(annotate(value, 'Must be a Date'));
|
|
543
|
+
};
|
|
544
|
+
/**
|
|
545
|
+
* Decoder that only returns Ok for strings that are valid ISO8601 date
|
|
546
|
+
* strings. Err otherwise.
|
|
547
|
+
*/
|
|
548
|
+
|
|
549
|
+
var iso8601 = map( // Input itself needs to match the ISO8601 regex...
|
|
550
|
+
regex(iso8601_re, 'Must be ISO8601 format'), // Make sure it is a _valid_ date
|
|
551
|
+
function (value) {
|
|
552
|
+
var date = new Date(value);
|
|
553
|
+
|
|
554
|
+
if (isNaN(date.getTime())) {
|
|
555
|
+
throw new Error('Must be valid date/time value');
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
return date;
|
|
559
|
+
});
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* Wrap another decoder, and override the error message in case it fails. This
|
|
563
|
+
* is useful to "simplify" otherwise potentially complex error messages, or to
|
|
564
|
+
* use language in those error messages that can be relayed to end users (for
|
|
565
|
+
* example to show in form errors).
|
|
566
|
+
*/
|
|
567
|
+
function describe(decoder, message) {
|
|
568
|
+
return function (blob) {
|
|
569
|
+
return decoder(blob).mapError(function (err) {
|
|
570
|
+
return annotate(err, message);
|
|
571
|
+
});
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Indents and adds a dash in front of this (potentially multiline) string.
|
|
577
|
+
*/
|
|
578
|
+
// istanbul ignore next
|
|
579
|
+
function itemize() {
|
|
580
|
+
var s = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
|
|
581
|
+
return '-' + indent(s).substring(1);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function either(d1, d2) {
|
|
585
|
+
return function (blob) {
|
|
586
|
+
return d1(blob).dispatch(function (value1) {
|
|
587
|
+
return Ok(value1);
|
|
588
|
+
}, function (err1) {
|
|
589
|
+
return d2(blob).dispatch(function (value2) {
|
|
590
|
+
return Ok(value2);
|
|
591
|
+
}, function (err2) {
|
|
592
|
+
return Err(annotate(blob, ['Either:', itemize(summarize(err1).join('\n')), itemize(summarize(err2).join('\n'))].join('\n')));
|
|
593
|
+
});
|
|
594
|
+
});
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
function either3(d1, d2, d3) {
|
|
598
|
+
return either(d1, either(d2, d3));
|
|
599
|
+
}
|
|
600
|
+
function either4(d1, d2, d3, d4) {
|
|
601
|
+
return either(d1, either3(d2, d3, d4));
|
|
602
|
+
}
|
|
603
|
+
function either5(d1, d2, d3, d4, d5) {
|
|
604
|
+
return either(d1, either4(d2, d3, d4, d5));
|
|
605
|
+
}
|
|
606
|
+
function either6(d1, d2, d3, d4, d5, d6) {
|
|
607
|
+
return either(d1, either5(d2, d3, d4, d5, d6));
|
|
608
|
+
}
|
|
609
|
+
function either7(d1, d2, d3, d4, d5, d6, d7) {
|
|
610
|
+
return either(d1, either6(d2, d3, d4, d5, d6, d7));
|
|
611
|
+
}
|
|
612
|
+
function either8(d1, d2, d3, d4, d5, d6, d7, d8) {
|
|
613
|
+
return either(d1, either7(d2, d3, d4, d5, d6, d7, d8));
|
|
614
|
+
}
|
|
615
|
+
function either9(d1, d2, d3, d4, d5, d6, d7, d8, d9) {
|
|
616
|
+
return either(d1, either8(d2, d3, d4, d5, d6, d7, d8, d9));
|
|
617
|
+
}
|
|
618
|
+
function oneOf(constants) {
|
|
619
|
+
return function (blob) {
|
|
620
|
+
var winner = constants.find(function (c) {
|
|
621
|
+
return c === blob;
|
|
622
|
+
});
|
|
623
|
+
|
|
624
|
+
if (winner !== undefined) {
|
|
625
|
+
return Ok(winner);
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
return Err(annotate(blob, "Must be one of ".concat(constants.map(function (value) {
|
|
629
|
+
return JSON.stringify(value);
|
|
630
|
+
}).join(', '))));
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function isPojo(o) {
|
|
635
|
+
return o !== null && o !== undefined && _typeof(o) === 'object' && // This still seems to be the only reliable way to determine whether
|
|
636
|
+
// something is a pojo... ¯\_(ツ)_/¯
|
|
637
|
+
// $FlowFixMe[method-unbinding]
|
|
638
|
+
Object.prototype.toString.call(o) === '[object Object]';
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function subtract(xs, ys) {
|
|
642
|
+
var result = new Set();
|
|
643
|
+
|
|
644
|
+
var _iterator = _createForOfIteratorHelper(xs),
|
|
645
|
+
_step;
|
|
646
|
+
|
|
647
|
+
try {
|
|
648
|
+
for (_iterator.s(); !(_step = _iterator.n()).done;) {
|
|
649
|
+
var x = _step.value;
|
|
650
|
+
|
|
651
|
+
if (!ys.has(x)) {
|
|
652
|
+
result.add(x);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
} catch (err) {
|
|
656
|
+
_iterator.e(err);
|
|
657
|
+
} finally {
|
|
658
|
+
_iterator.f();
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
return result;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
var pojo = function pojo(blob) {
|
|
665
|
+
return isPojo(blob) ? Ok( // NOTE:
|
|
666
|
+
// Since Flow 0.98, typeof o === 'object' refines to
|
|
667
|
+
// {| +[string]: mixed |}
|
|
668
|
+
// instead of
|
|
669
|
+
// {| [string]: mixed |}
|
|
670
|
+
//
|
|
671
|
+
// For rationale, see https://github.com/facebook/flow/issues/7685.
|
|
672
|
+
// In this case, we don't want to output a read-only version of
|
|
673
|
+
// the object because it's up to the user of decoders to
|
|
674
|
+
// determine what they want to do with the decoded output. If they
|
|
675
|
+
// want to write items into the array, that's fine! The fastest
|
|
676
|
+
// way to turn a read-only Object to a writeable one in ES6 seems
|
|
677
|
+
// to be to use object-spread. (Going off this benchmark:
|
|
678
|
+
// https://thecodebarbarian.com/object-assign-vs-object-spread.html)
|
|
679
|
+
_objectSpread2({}, blob)) : Err(annotate(blob, 'Must be an object'));
|
|
680
|
+
};
|
|
681
|
+
/**
|
|
682
|
+
* Given a mapping of fields-to-decoders, builds a decoder for an object type.
|
|
683
|
+
*
|
|
684
|
+
* For example, given decoders for a number and a string, we can construct an
|
|
685
|
+
* "object description" like so:
|
|
686
|
+
*
|
|
687
|
+
* { id: number, name: string }
|
|
688
|
+
*
|
|
689
|
+
* Which is of type:
|
|
690
|
+
*
|
|
691
|
+
* { id: Decoder<number>, name: Decoder<string> }
|
|
692
|
+
*
|
|
693
|
+
* Passing this to object() will produce the following return type:
|
|
694
|
+
*
|
|
695
|
+
* Decoder<{ id: number, name: string }>
|
|
696
|
+
*
|
|
697
|
+
* Put simply: it'll "peel off" all of the nested Decoders, puts them together
|
|
698
|
+
* in an object, and wraps it in a Decoder<...>.
|
|
699
|
+
*/
|
|
700
|
+
|
|
701
|
+
function object(mapping) {
|
|
702
|
+
var known = new Set(Object.keys(mapping));
|
|
703
|
+
return compose(pojo, function (blob) {
|
|
704
|
+
var actual = new Set(Object.keys(blob)); // At this point, "missing" will also include all fields that may
|
|
705
|
+
// validly be optional. We'll let the underlying decoder decide and
|
|
706
|
+
// remove the key from this missing set if the decoder accepts the
|
|
707
|
+
// value.
|
|
708
|
+
|
|
709
|
+
var missing = subtract(known, actual);
|
|
710
|
+
var record = {};
|
|
711
|
+
|
|
712
|
+
var fieldErrors = _objectSpread2({}, null); // NOTE: We're using .keys() here over .entries(), since .entries()
|
|
713
|
+
// will type the value part as "mixed"
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
for (var _i = 0, _Object$keys = Object.keys(mapping); _i < _Object$keys.length; _i++) {
|
|
717
|
+
var _key = _Object$keys[_i];
|
|
718
|
+
var decoder = mapping[_key];
|
|
719
|
+
var rawValue = blob[_key];
|
|
720
|
+
var result = decoder(rawValue);
|
|
721
|
+
|
|
722
|
+
try {
|
|
723
|
+
var value = result.unwrap();
|
|
724
|
+
|
|
725
|
+
if (value !== undefined) {
|
|
726
|
+
record[_key] = value;
|
|
727
|
+
} // If this succeeded, remove the key from the missing keys
|
|
728
|
+
// tracker
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
missing["delete"](_key);
|
|
732
|
+
} catch (ann) {
|
|
733
|
+
/* istanbul ignore next */
|
|
734
|
+
if (!isAnnotation(ann)) {
|
|
735
|
+
throw ann;
|
|
736
|
+
} // Keep track of the annotation, but don't return just yet. We
|
|
737
|
+
// want to collect more error information.
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
if (rawValue === undefined) {
|
|
741
|
+
// Explicitly add it to the missing set if the value is
|
|
742
|
+
// undefined. This covers explicit undefineds to be
|
|
743
|
+
// treated the same as implicit undefineds (aka missing
|
|
744
|
+
// keys).
|
|
745
|
+
missing.add(_key);
|
|
746
|
+
} else {
|
|
747
|
+
fieldErrors[_key] = ann;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
} // Deal with errors now. There are two classes of errors we want to
|
|
751
|
+
// report. First of all, we want to report any inline errors in this
|
|
752
|
+
// object. Lastly, any fields that are missing should be annotated on
|
|
753
|
+
// the outer object itself.
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
var fieldsWithErrors = Object.keys(fieldErrors);
|
|
757
|
+
|
|
758
|
+
if (fieldsWithErrors.length > 0 || missing.size > 0) {
|
|
759
|
+
var err;
|
|
760
|
+
|
|
761
|
+
if (fieldsWithErrors.length > 0) {
|
|
762
|
+
var errorlist = fieldsWithErrors.map(function (k) {
|
|
763
|
+
return [k, fieldErrors[k]];
|
|
764
|
+
});
|
|
765
|
+
err = annotateFields(blob, errorlist);
|
|
766
|
+
} else {
|
|
767
|
+
err = annotate(blob);
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
if (missing.size > 0) {
|
|
771
|
+
var errMsg = Array.from(missing).map(function (key) {
|
|
772
|
+
return "\"".concat(key, "\"");
|
|
773
|
+
}).join(', ');
|
|
774
|
+
var pluralized = missing.size > 1 ? 'keys' : 'key';
|
|
775
|
+
err = annotate(err, "Missing ".concat(pluralized, ": ").concat(errMsg));
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
return Err(err);
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
return Ok(record);
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
function exact(mapping) {
|
|
785
|
+
// Check the inputted object for any superfluous keys
|
|
786
|
+
var allowed = new Set(Object.keys(mapping));
|
|
787
|
+
var checked = compose(pojo, function (blob) {
|
|
788
|
+
var actual = new Set(Object.keys(blob));
|
|
789
|
+
var superfluous = subtract(actual, allowed);
|
|
790
|
+
|
|
791
|
+
if (superfluous.size > 0) {
|
|
792
|
+
return Err(annotate(blob, "Superfluous keys: ".concat(Array.from(superfluous).join(', '))));
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
return Ok(blob);
|
|
796
|
+
}); // Defer to the "object" decoder for doing the real decoding work. Since
|
|
797
|
+
// we made sure there are no superfluous keys in this structure, it's now
|
|
798
|
+
// safe to force-cast it to an $Exact<> type.
|
|
799
|
+
|
|
800
|
+
var decoder = object(mapping);
|
|
801
|
+
return compose(checked, decoder);
|
|
802
|
+
}
|
|
803
|
+
function inexact(mapping) {
|
|
804
|
+
return compose(pojo, function (blob) {
|
|
805
|
+
var allkeys = new Set(Object.keys(blob));
|
|
806
|
+
var decoder = map(object(mapping), function (safepart) {
|
|
807
|
+
var safekeys = new Set(Object.keys(mapping)); // To account for hard-coded keys that aren't part of the input
|
|
808
|
+
|
|
809
|
+
var _iterator2 = _createForOfIteratorHelper(safekeys),
|
|
810
|
+
_step2;
|
|
811
|
+
|
|
812
|
+
try {
|
|
813
|
+
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
|
|
814
|
+
var k = _step2.value;
|
|
815
|
+
allkeys.add(k);
|
|
816
|
+
}
|
|
817
|
+
} catch (err) {
|
|
818
|
+
_iterator2.e(err);
|
|
819
|
+
} finally {
|
|
820
|
+
_iterator2.f();
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
var rv = {};
|
|
824
|
+
|
|
825
|
+
var _iterator3 = _createForOfIteratorHelper(allkeys),
|
|
826
|
+
_step3;
|
|
827
|
+
|
|
828
|
+
try {
|
|
829
|
+
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
|
|
830
|
+
var _k = _step3.value;
|
|
831
|
+
|
|
832
|
+
if (safekeys.has(_k)) {
|
|
833
|
+
var value = safepart[_k];
|
|
834
|
+
|
|
835
|
+
if (value !== undefined) {
|
|
836
|
+
rv[_k] = value;
|
|
837
|
+
}
|
|
838
|
+
} else {
|
|
839
|
+
rv[_k] = blob[_k];
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
} catch (err) {
|
|
843
|
+
_iterator3.e(err);
|
|
844
|
+
} finally {
|
|
845
|
+
_iterator3.f();
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
return rv;
|
|
849
|
+
});
|
|
850
|
+
return decoder(blob);
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* Dispatches to one of several given decoders, based on the value found at
|
|
856
|
+
* runtime in the given field. For example, suppose you have these decoders:
|
|
857
|
+
*
|
|
858
|
+
* const rectangle = object({
|
|
859
|
+
* type: constant('rect'),
|
|
860
|
+
* x: number,
|
|
861
|
+
* y: number,
|
|
862
|
+
* width: number,
|
|
863
|
+
* height: number,
|
|
864
|
+
* });
|
|
865
|
+
*
|
|
866
|
+
* const circle = object({
|
|
867
|
+
* type: constant('circle'),
|
|
868
|
+
* cx: number,
|
|
869
|
+
* cy: number,
|
|
870
|
+
* r: number,
|
|
871
|
+
* });
|
|
872
|
+
*
|
|
873
|
+
* Then these two decoders are equivalent:
|
|
874
|
+
*
|
|
875
|
+
* const shape = either(rectangle, circle)
|
|
876
|
+
* const shape = dispatch('type', { rectangle, circle })
|
|
877
|
+
*
|
|
878
|
+
* Will be of type Decoder<Rectangle | Circle>.
|
|
879
|
+
*
|
|
880
|
+
* But the dispatch version will typically be more runtime-efficient. The
|
|
881
|
+
* reason is that it will first do minimal work to "look ahead" into the `type`
|
|
882
|
+
* field here, and based on that value, pick the decoder to invoke.
|
|
883
|
+
*
|
|
884
|
+
* The `either` version will simply try to invoke each decoder, until it finds
|
|
885
|
+
* one that matches.
|
|
886
|
+
*
|
|
887
|
+
* Also, the error messages will be less ambiguous using `dispatch()`.
|
|
888
|
+
*/
|
|
889
|
+
function dispatch(field, mapping) {
|
|
890
|
+
var base = object(_defineProperty({}, field, oneOf(Object.keys(mapping))));
|
|
891
|
+
return function (blob) {
|
|
892
|
+
return base(blob).andThen(function (baseObj) {
|
|
893
|
+
var decoderName = baseObj[field];
|
|
894
|
+
var decoder = mapping[decoderName];
|
|
895
|
+
return decoder(blob);
|
|
896
|
+
});
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/**
|
|
901
|
+
* Decoder that always fails with the given error message, no matter what the input.
|
|
902
|
+
*/
|
|
903
|
+
function fail(msg) {
|
|
904
|
+
return function (blob) {
|
|
905
|
+
return Err(annotate(blob, msg));
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
function instanceOf(klass) {
|
|
910
|
+
return function (blob) {
|
|
911
|
+
return blob instanceof klass ? Ok(blob) : Err(annotate(blob, "Must be ".concat( // $FlowFixMe[incompatible-use] - klass.name is fine?
|
|
912
|
+
klass.name, " instance")));
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* Given an function returning a Decoder, will use that decoder to decode the
|
|
918
|
+
* value. This is typically used to build decoders for recursive or
|
|
919
|
+
* self-referential types.
|
|
920
|
+
*/
|
|
921
|
+
function lazy(decoderFn) {
|
|
922
|
+
return function (blob) {
|
|
923
|
+
var decoder = decoderFn();
|
|
924
|
+
return decoder(blob);
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* Given an object, will decode a Map of string keys to whatever values.
|
|
930
|
+
*
|
|
931
|
+
* For example, given a decoder for a Person, we can verify a Person lookup
|
|
932
|
+
* table structure (of type Map<string, Person>) like so:
|
|
933
|
+
*
|
|
934
|
+
* mapping(person)
|
|
935
|
+
*
|
|
936
|
+
*/
|
|
937
|
+
|
|
938
|
+
function mapping(decoder) {
|
|
939
|
+
return compose(pojo, // $FlowFixMe[unclear-type] (not really an issue) - deliberate use of Object here
|
|
940
|
+
function (blob) {
|
|
941
|
+
var tuples = [];
|
|
942
|
+
var errors = [];
|
|
943
|
+
Object.keys(blob).forEach(function (key) {
|
|
944
|
+
var value = blob[key];
|
|
945
|
+
var result = decoder(value);
|
|
946
|
+
|
|
947
|
+
try {
|
|
948
|
+
var okValue = result.unwrap();
|
|
949
|
+
|
|
950
|
+
if (errors.length === 0) {
|
|
951
|
+
tuples.push([key, okValue]);
|
|
952
|
+
}
|
|
953
|
+
} catch (e) {
|
|
954
|
+
/* istanbul ignore else */
|
|
955
|
+
if (isAnnotation(e)) {
|
|
956
|
+
tuples.length = 0; // Clear the tuples array
|
|
957
|
+
|
|
958
|
+
errors.push([key, e]);
|
|
959
|
+
} else {
|
|
960
|
+
// Otherwise, simply rethrow it
|
|
961
|
+
|
|
962
|
+
/* istanbul ignore next */
|
|
963
|
+
throw e;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
});
|
|
967
|
+
|
|
968
|
+
if (errors.length > 0) {
|
|
969
|
+
return Err(annotateFields(blob, errors));
|
|
970
|
+
} else {
|
|
971
|
+
return Ok(new Map(tuples));
|
|
972
|
+
}
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
function mapToObject(mapping) {
|
|
977
|
+
var result = _objectSpread2({}, null);
|
|
978
|
+
|
|
979
|
+
var _iterator = _createForOfIteratorHelper(mapping.entries()),
|
|
980
|
+
_step;
|
|
981
|
+
|
|
982
|
+
try {
|
|
983
|
+
for (_iterator.s(); !(_step = _iterator.n()).done;) {
|
|
984
|
+
var _step$value = _slicedToArray(_step.value, 2),
|
|
985
|
+
k = _step$value[0],
|
|
986
|
+
v = _step$value[1];
|
|
987
|
+
|
|
988
|
+
result[k] = v;
|
|
989
|
+
}
|
|
990
|
+
} catch (err) {
|
|
991
|
+
_iterator.e(err);
|
|
992
|
+
} finally {
|
|
993
|
+
_iterator.f();
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
return result;
|
|
997
|
+
}
|
|
998
|
+
/**
|
|
999
|
+
* Like mapping(), but returns an object rather than a Map instance.
|
|
1000
|
+
*/
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
function dict(decoder) {
|
|
1004
|
+
return map(mapping(decoder), mapToObject);
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
var jsonObject = lazy(function () {
|
|
1008
|
+
return dict(json);
|
|
1009
|
+
});
|
|
1010
|
+
var jsonArray = lazy(function () {
|
|
1011
|
+
return array(json);
|
|
1012
|
+
});
|
|
1013
|
+
var json = either6(null_, string, number, _boolean, jsonObject, jsonArray);
|
|
1014
|
+
|
|
1015
|
+
/**
|
|
1016
|
+
* Builds a Decoder that returns Ok for either `undefined` or `T` values,
|
|
1017
|
+
* given a Decoder for `T`. Err otherwise.
|
|
1018
|
+
*/
|
|
1019
|
+
function optional(decoder) {
|
|
1020
|
+
return either(undefined_, decoder);
|
|
1021
|
+
}
|
|
1022
|
+
/**
|
|
1023
|
+
* Builds a Decoder that returns Ok for either `null` or `T` values,
|
|
1024
|
+
* given a Decoder for `T`. Err otherwise.
|
|
1025
|
+
*/
|
|
1026
|
+
|
|
1027
|
+
function nullable(decoder) {
|
|
1028
|
+
return either(null_, decoder);
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* Decoder that only returns Ok for `null` or `undefined` inputs.
|
|
1032
|
+
* This is effectively equivalent to either(null_, undefined_), but combines
|
|
1033
|
+
* their error message output into a single line for convenience.
|
|
1034
|
+
*/
|
|
1035
|
+
|
|
1036
|
+
var undefined_or_null = function undefined_or_null(blob) {
|
|
1037
|
+
return blob === undefined || blob === null ? Ok(blob) : // Combine error message into a single line
|
|
1038
|
+
Err(annotate(blob, 'Must be undefined or null'));
|
|
1039
|
+
};
|
|
1040
|
+
/**
|
|
1041
|
+
* Decoder that only returns Ok for `null` or `undefined` inputs.
|
|
1042
|
+
*/
|
|
1043
|
+
|
|
1044
|
+
|
|
1045
|
+
function maybe(decoder) {
|
|
1046
|
+
return either(undefined_or_null, decoder);
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
var ntuple = function ntuple(n) {
|
|
1050
|
+
return compose(poja, predicate(function (arr) {
|
|
1051
|
+
return arr.length === n;
|
|
1052
|
+
}, "Must be a ".concat(n, "-tuple")));
|
|
1053
|
+
};
|
|
1054
|
+
/**
|
|
1055
|
+
* Builds a Decoder that returns Ok for 1-tuple of [T], given a Decoder for T.
|
|
1056
|
+
* Err otherwise.
|
|
1057
|
+
*/
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
function tuple1(decoder1) {
|
|
1061
|
+
return compose(ntuple(1), function (blobs) {
|
|
1062
|
+
var _blobs = _slicedToArray(blobs, 1),
|
|
1063
|
+
blob1 = _blobs[0];
|
|
1064
|
+
|
|
1065
|
+
var result1 = decoder1(blob1);
|
|
1066
|
+
|
|
1067
|
+
try {
|
|
1068
|
+
return Ok([result1.unwrap()]);
|
|
1069
|
+
} catch (e) {
|
|
1070
|
+
// If a decoder error has happened while unwrapping all the
|
|
1071
|
+
// results, try to construct a good error message
|
|
1072
|
+
return Err(annotate(result1.errValue()));
|
|
1073
|
+
}
|
|
1074
|
+
});
|
|
1075
|
+
}
|
|
1076
|
+
/**
|
|
1077
|
+
* Builds a Decoder that returns Ok for 2-tuples of [T1, T2], given Decoders
|
|
1078
|
+
* for T1 and T2. Err otherwise.
|
|
1079
|
+
*/
|
|
1080
|
+
|
|
1081
|
+
function tuple2(decoder1, decoder2) {
|
|
1082
|
+
return compose(ntuple(2), function (blobs) {
|
|
1083
|
+
var _blobs2 = _slicedToArray(blobs, 2),
|
|
1084
|
+
blob1 = _blobs2[0],
|
|
1085
|
+
blob2 = _blobs2[1];
|
|
1086
|
+
|
|
1087
|
+
var result1 = decoder1(blob1);
|
|
1088
|
+
var result2 = decoder2(blob2);
|
|
1089
|
+
|
|
1090
|
+
try {
|
|
1091
|
+
return Ok([result1.unwrap(), result2.unwrap()]);
|
|
1092
|
+
} catch (e) {
|
|
1093
|
+
// If a decoder error has happened while unwrapping all the
|
|
1094
|
+
// results, try to construct a good error message
|
|
1095
|
+
return Err(annotate([result1.isErr() ? result1.errValue() : result1.value(), result2.isErr() ? result2.errValue() : result2.value()]));
|
|
1096
|
+
}
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* Builds a Decoder that returns Ok for 3-tuples of [T1, T2, T3], given
|
|
1101
|
+
* Decoders for T1, T2, and T3. Err otherwise.
|
|
1102
|
+
*/
|
|
1103
|
+
|
|
1104
|
+
function tuple3(decoder1, decoder2, decoder3) {
|
|
1105
|
+
return compose(ntuple(3), function (blobs) {
|
|
1106
|
+
var _blobs3 = _slicedToArray(blobs, 3),
|
|
1107
|
+
blob1 = _blobs3[0],
|
|
1108
|
+
blob2 = _blobs3[1],
|
|
1109
|
+
blob3 = _blobs3[2];
|
|
1110
|
+
|
|
1111
|
+
var result1 = decoder1(blob1);
|
|
1112
|
+
var result2 = decoder2(blob2);
|
|
1113
|
+
var result3 = decoder3(blob3);
|
|
1114
|
+
|
|
1115
|
+
try {
|
|
1116
|
+
return Ok([result1.unwrap(), result2.unwrap(), result3.unwrap()]);
|
|
1117
|
+
} catch (e) {
|
|
1118
|
+
// If a decoder error has happened while unwrapping all the
|
|
1119
|
+
// results, try to construct a good error message
|
|
1120
|
+
return Err(annotate([result1.isErr() ? result1.errValue() : result1.value(), result2.isErr() ? result2.errValue() : result2.value(), result3.isErr() ? result3.errValue() : result3.value()]));
|
|
1121
|
+
}
|
|
1122
|
+
});
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* Builds a Decoder that returns Ok for 4-tuples of [T1, T2, T3, T4], given
|
|
1126
|
+
* Decoders for T1, T2, T3, and T4. Err otherwise.
|
|
1127
|
+
*/
|
|
1128
|
+
|
|
1129
|
+
function tuple4(decoder1, decoder2, decoder3, decoder4) {
|
|
1130
|
+
return compose(ntuple(4), function (blobs) {
|
|
1131
|
+
var _blobs4 = _slicedToArray(blobs, 4),
|
|
1132
|
+
blob1 = _blobs4[0],
|
|
1133
|
+
blob2 = _blobs4[1],
|
|
1134
|
+
blob3 = _blobs4[2],
|
|
1135
|
+
blob4 = _blobs4[3];
|
|
1136
|
+
|
|
1137
|
+
var result1 = decoder1(blob1);
|
|
1138
|
+
var result2 = decoder2(blob2);
|
|
1139
|
+
var result3 = decoder3(blob3);
|
|
1140
|
+
var result4 = decoder4(blob4);
|
|
1141
|
+
|
|
1142
|
+
try {
|
|
1143
|
+
return Ok([result1.unwrap(), result2.unwrap(), result3.unwrap(), result4.unwrap()]);
|
|
1144
|
+
} catch (e) {
|
|
1145
|
+
// If a decoder error has happened while unwrapping all the
|
|
1146
|
+
// results, try to construct a good error message
|
|
1147
|
+
return Err(annotate([result1.isErr() ? result1.errValue() : result1.value(), result2.isErr() ? result2.errValue() : result2.value(), result3.isErr() ? result3.errValue() : result3.value(), result4.isErr() ? result4.errValue() : result4.value()]));
|
|
1148
|
+
}
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Builds a Decoder that returns Ok for 5-tuples of [T1, T2, T3, T4, T5], given
|
|
1153
|
+
* Decoders for T1, T2, T3, T4, and T5. Err otherwise.
|
|
1154
|
+
*/
|
|
1155
|
+
|
|
1156
|
+
function tuple5(decoder1, decoder2, decoder3, decoder4, decoder5) {
|
|
1157
|
+
return compose(ntuple(5), function (blobs) {
|
|
1158
|
+
var _blobs5 = _slicedToArray(blobs, 5),
|
|
1159
|
+
blob1 = _blobs5[0],
|
|
1160
|
+
blob2 = _blobs5[1],
|
|
1161
|
+
blob3 = _blobs5[2],
|
|
1162
|
+
blob4 = _blobs5[3],
|
|
1163
|
+
blob5 = _blobs5[4];
|
|
1164
|
+
|
|
1165
|
+
var result1 = decoder1(blob1);
|
|
1166
|
+
var result2 = decoder2(blob2);
|
|
1167
|
+
var result3 = decoder3(blob3);
|
|
1168
|
+
var result4 = decoder4(blob4);
|
|
1169
|
+
var result5 = decoder5(blob5);
|
|
1170
|
+
|
|
1171
|
+
try {
|
|
1172
|
+
return Ok([result1.unwrap(), result2.unwrap(), result3.unwrap(), result4.unwrap(), result5.unwrap()]);
|
|
1173
|
+
} catch (e) {
|
|
1174
|
+
// If a decoder error has happened while unwrapping all the
|
|
1175
|
+
// results, try to construct a good error message
|
|
1176
|
+
return Err(annotate([result1.isErr() ? result1.errValue() : result1.value(), result2.isErr() ? result2.errValue() : result2.value(), result3.isErr() ? result3.errValue() : result3.value(), result4.isErr() ? result4.errValue() : result4.value(), result5.isErr() ? result5.errValue() : result5.value()]));
|
|
1177
|
+
}
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
/**
|
|
1181
|
+
* Builds a Decoder that returns Ok for 5-tuples of [T1, T2, T3, T4, T5], given
|
|
1182
|
+
* Decoders for T1, T2, T3, T4, T5, and T6. Err otherwise.
|
|
1183
|
+
*/
|
|
1184
|
+
|
|
1185
|
+
function tuple6(decoder1, decoder2, decoder3, decoder4, decoder5, decoder6) {
|
|
1186
|
+
return compose(ntuple(6), function (blobs) {
|
|
1187
|
+
var _blobs6 = _slicedToArray(blobs, 6),
|
|
1188
|
+
blob1 = _blobs6[0],
|
|
1189
|
+
blob2 = _blobs6[1],
|
|
1190
|
+
blob3 = _blobs6[2],
|
|
1191
|
+
blob4 = _blobs6[3],
|
|
1192
|
+
blob5 = _blobs6[4],
|
|
1193
|
+
blob6 = _blobs6[5];
|
|
1194
|
+
|
|
1195
|
+
var result1 = decoder1(blob1);
|
|
1196
|
+
var result2 = decoder2(blob2);
|
|
1197
|
+
var result3 = decoder3(blob3);
|
|
1198
|
+
var result4 = decoder4(blob4);
|
|
1199
|
+
var result5 = decoder5(blob5);
|
|
1200
|
+
var result6 = decoder6(blob6);
|
|
1201
|
+
|
|
1202
|
+
try {
|
|
1203
|
+
return Ok([result1.unwrap(), result2.unwrap(), result3.unwrap(), result4.unwrap(), result5.unwrap(), result6.unwrap()]);
|
|
1204
|
+
} catch (e) {
|
|
1205
|
+
// If a decoder error has happened while unwrapping all the
|
|
1206
|
+
// results, try to construct a good error message
|
|
1207
|
+
return Err(annotate([result1.isErr() ? result1.errValue() : result1.value(), result2.isErr() ? result2.errValue() : result2.value(), result3.isErr() ? result3.errValue() : result3.value(), result4.isErr() ? result4.errValue() : result4.value(), result5.isErr() ? result5.errValue() : result5.value(), result6.isErr() ? result6.errValue() : result6.value()]));
|
|
1208
|
+
}
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
export { array, _boolean as boolean, compose, constant, date, describe, dict, dispatch, either, either3, either4, either5, either6, either7, either8, either9, email, exact, fail, guard, hardcoded, inexact, instanceOf, integer, iso8601, json, jsonArray, jsonObject, lazy, map, mapping, maybe, mixed, nonEmptyArray, nonEmptyString, null_, nullable, number, numericBoolean, object, oneOf, optional, poja, pojo, positiveInteger, positiveNumber, predicate, regex, string, truthy, tuple1, tuple2, tuple3, tuple4, tuple5, tuple6, undefined_, unknown, url };
|