decoders 2.0.0-beta8 → 2.0.1

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 (146) hide show
  1. package/CHANGELOG.md +67 -20
  2. package/Decoder.d.ts +94 -0
  3. package/Decoder.js +115 -0
  4. package/Decoder.js.flow +286 -0
  5. package/Decoder.mjs +108 -0
  6. package/README.md +122 -1345
  7. package/_utils.d.ts +0 -1
  8. package/_utils.js +51 -68
  9. package/_utils.js.flow +30 -20
  10. package/_utils.mjs +39 -54
  11. package/annotate.js +79 -72
  12. package/annotate.mjs +62 -58
  13. package/format.d.ts +4 -2
  14. package/format.js +64 -74
  15. package/format.js.flow +14 -12
  16. package/format.mjs +58 -68
  17. package/index.d.ts +38 -41
  18. package/index.js +66 -98
  19. package/index.js.flow +39 -58
  20. package/index.mjs +11 -37
  21. package/{core → lib}/_helpers.d.ts +0 -0
  22. package/lib/arrays.d.ts +59 -0
  23. package/lib/arrays.js +97 -0
  24. package/lib/arrays.js.flow +138 -0
  25. package/lib/arrays.mjs +84 -0
  26. package/lib/basics.d.ts +93 -0
  27. package/lib/basics.js +94 -0
  28. package/lib/basics.js.flow +124 -0
  29. package/lib/basics.mjs +75 -0
  30. package/lib/booleans.d.ts +16 -0
  31. package/lib/booleans.js +25 -0
  32. package/lib/booleans.js.flow +22 -0
  33. package/lib/booleans.mjs +15 -0
  34. package/lib/dates.d.ts +15 -0
  35. package/lib/dates.js +28 -0
  36. package/lib/dates.js.flow +40 -0
  37. package/lib/dates.mjs +19 -0
  38. package/lib/json.d.ts +35 -0
  39. package/lib/json.js +33 -0
  40. package/lib/json.js.flow +50 -0
  41. package/lib/json.mjs +18 -0
  42. package/lib/numbers.d.ts +31 -0
  43. package/lib/numbers.js +31 -0
  44. package/lib/numbers.js.flow +48 -0
  45. package/lib/numbers.mjs +21 -0
  46. package/lib/objects.d.ts +76 -0
  47. package/lib/objects.js +161 -0
  48. package/lib/objects.js.flow +238 -0
  49. package/lib/objects.mjs +147 -0
  50. package/lib/strings.d.ts +56 -0
  51. package/lib/strings.js +58 -0
  52. package/lib/strings.js.flow +90 -0
  53. package/lib/strings.mjs +40 -0
  54. package/lib/unions.d.ts +55 -0
  55. package/lib/unions.js +96 -0
  56. package/lib/unions.js.flow +155 -0
  57. package/lib/unions.mjs +83 -0
  58. package/lib/utilities.d.ts +40 -0
  59. package/lib/utilities.js +48 -0
  60. package/lib/utilities.js.flow +65 -0
  61. package/lib/utilities.mjs +37 -0
  62. package/package.json +64 -17
  63. package/result.d.ts +2 -25
  64. package/result.js +9 -90
  65. package/result.js.flow +4 -76
  66. package/result.mjs +5 -71
  67. package/_guard.d.ts +0 -7
  68. package/_guard.js +0 -22
  69. package/_guard.js.flow +0 -20
  70. package/_guard.mjs +0 -15
  71. package/_types.d.ts +0 -13
  72. package/_types.js +0 -1
  73. package/_types.js.flow +0 -20
  74. package/_types.mjs +0 -0
  75. package/core/array.d.ts +0 -5
  76. package/core/array.js +0 -104
  77. package/core/array.js.flow +0 -100
  78. package/core/array.mjs +0 -91
  79. package/core/boolean.d.ts +0 -5
  80. package/core/boolean.js +0 -40
  81. package/core/boolean.js.flow +0 -27
  82. package/core/boolean.mjs +0 -28
  83. package/core/composition.d.ts +0 -14
  84. package/core/composition.js +0 -54
  85. package/core/composition.js.flow +0 -48
  86. package/core/composition.mjs +0 -44
  87. package/core/constants.d.ts +0 -11
  88. package/core/constants.js +0 -65
  89. package/core/constants.js.flow +0 -44
  90. package/core/constants.mjs +0 -46
  91. package/core/date.d.ts +0 -4
  92. package/core/date.js +0 -42
  93. package/core/date.js.flow +0 -38
  94. package/core/date.mjs +0 -28
  95. package/core/describe.d.ts +0 -3
  96. package/core/describe.js +0 -22
  97. package/core/describe.js.flow +0 -17
  98. package/core/describe.mjs +0 -16
  99. package/core/dispatch.d.ts +0 -8
  100. package/core/dispatch.js +0 -58
  101. package/core/dispatch.js.flow +0 -58
  102. package/core/dispatch.mjs +0 -51
  103. package/core/either.d.ts +0 -61
  104. package/core/either.js +0 -113
  105. package/core/either.js.flow +0 -151
  106. package/core/either.mjs +0 -90
  107. package/core/fail.d.ts +0 -3
  108. package/core/fail.js +0 -17
  109. package/core/fail.js.flow +0 -12
  110. package/core/fail.mjs +0 -11
  111. package/core/instanceOf.d.ts +0 -3
  112. package/core/instanceOf.js +0 -15
  113. package/core/instanceOf.js.flow +0 -20
  114. package/core/instanceOf.mjs +0 -8
  115. package/core/json.d.ts +0 -11
  116. package/core/json.js +0 -31
  117. package/core/json.js.flow +0 -28
  118. package/core/json.mjs +0 -15
  119. package/core/lazy.d.ts +0 -3
  120. package/core/lazy.js +0 -16
  121. package/core/lazy.js.flow +0 -15
  122. package/core/lazy.mjs +0 -11
  123. package/core/mapping.d.ts +0 -6
  124. package/core/mapping.js +0 -67
  125. package/core/mapping.js.flow +0 -62
  126. package/core/mapping.mjs +0 -58
  127. package/core/number.d.ts +0 -6
  128. package/core/number.js +0 -36
  129. package/core/number.js.flow +0 -40
  130. package/core/number.mjs +0 -25
  131. package/core/object.d.ts +0 -33
  132. package/core/object.js +0 -190
  133. package/core/object.js.flow +0 -203
  134. package/core/object.mjs +0 -175
  135. package/core/optional.d.ts +0 -5
  136. package/core/optional.js +0 -50
  137. package/core/optional.js.flow +0 -41
  138. package/core/optional.mjs +0 -38
  139. package/core/string.d.ts +0 -10
  140. package/core/string.js +0 -68
  141. package/core/string.js.flow +0 -59
  142. package/core/string.mjs +0 -49
  143. package/core/tuple.d.ts +0 -30
  144. package/core/tuple.js +0 -177
  145. package/core/tuple.js.flow +0 -211
  146. package/core/tuple.mjs +0 -159
package/CHANGELOG.md CHANGED
@@ -1,31 +1,78 @@
1
- ## v2.0.0-beta
1
+ ## v2.0.1
2
2
 
3
- Upgrading to v2 _can_, but doesn't _have_ to be a breaking change for you. If upgrading
4
- causes errors for you, please see the [migration guide](./MIGRATING-v2.md) for
5
- instructions.
3
+ - ![](./docs/assets/tiny-ts-logo.png) **TypeScript-only:** Fix definition of JSONObject
4
+ to reflect that its values might always be `undefined` as well.
6
5
 
7
- Potentially breaking changes:
6
+ - ![](./docs/assets/tiny-ts-logo.png) **TypeScript-only:** Changed return types of
7
+ `{ [key: string]: T }` to `Record<string, T>`.
8
+
9
+ - ![](./docs/assets/tiny-ts-logo.png) **TypeScript-only:** Fine-tune the type of
10
+ [`instanceOf()`](https://decoders.cc/api.html#instanceOf).
11
+
12
+ ## v2.0.0
13
+
14
+ This is a breaking change, which brings numerous benefits:
15
+
16
+ - A **simpler API** 😇
17
+ - Smaller **bundle size** (67% reduction 😱)
18
+ - **Tree-shaking** support 🍃
19
+ - Runtime **speed** 🏎️
20
+ - Better documentation 📚
21
+ - Better support for writing your own decoders 🛠️
22
+
23
+ <img alt="Bundle size comparison between v1 and v2" src="./docs/assets/size-comparison@2x.png" style="width: 100%; max-width: 829px" width="829" />
24
+
25
+ Please see the [migration guide](./MIGRATING-v2.md) for precise instructions on how to
26
+ adjust your v1 code.
27
+
28
+ The main change is the brand new `Decoder<T>` API! The **tl;dr** is:
29
+
30
+ | Replace this v1 pattern... | | ...with this v2 API | Notes |
31
+ | :----------------------------------- | --- | :----------------------------------------- | :--------------------------------------------------------------------------- |
32
+ | `mydecoder(input)` | → | `mydecoder.decode(input)` | [migration instructions](./MIGRATING-v2.md#stop-calling-decoders) |
33
+ | `guard(mydecoder)(input)` | → | `mydecoder.verify(input)` | [migration instructions](./MIGRATING-v2.md#guards-are-no-longer-a-thing) |
34
+ | `map(mydecoder, ...)` | → | `mydecoder.transform(...)` | [migration instructions](./MIGRATING-v2.md#map-is-now-transform) |
35
+ | `compose(mydecoder, predicate(...))` | → | `mydecoder.refine(...)` | [migration instructions](./MIGRATING-v2.md#compose--predicate-is-now-refine) |
36
+ | `describe(mydecoder, ...)` | → | `mydecoder.describe(...)` | |
37
+ | `mydecoder(input).value()` | → | `mydecoder.value(input)` | |
38
+ | `either`, `either3`, ..., `either9` | → | `either` | [migration instructions](./MIGRATING-v2.md#eitherN-is-now-simply-either) |
39
+ | `tuple1`, `tuple2`, ... `tuple6` | → | `tuple` | [migration instructions](./MIGRATING-v2.md#tupleN-is-now-simply-tuple) |
40
+ | `dispatch` | → | `taggedUnion` | [migration instructions](./MIGRATING-v2.md#dispatch-is-now-taggedUnion) |
41
+ | `url(...)` | → | `httpsUrl` / `url` (signature has changed) | [migration instructions](./MIGRATING-v2.md#signature-of-url-has-changed) |
42
+
43
+ The full documentation is available on [**decoders.cc**](https://decoders.cc).
44
+
45
+ Other features:
46
+
47
+ - Include ES modules in published NPM builds (yay tree-shaking! 🍃)
48
+ - Much smaller total bundle size (**67% smaller** compared to v1 😱)
49
+
50
+ Other potentially breaking changes:
8
51
 
9
52
  - Drop support for all Node versions below 12.x
10
- - Drop support for Flow versions below 0.142.0
11
53
  - Drop support for TypeScript versions below 4.1.0
54
+ - Drop support for Flow versions below 0.142.0
12
55
  - Drop all package dependencies
13
- - Decoders that have changed:
14
- - `dispatch` has been renamed to `disjointUnion` - see
15
- [migration instructions](./MIGRATING-v2.md#dispatch-is-now-disjointUnion)
16
- - API of `guard` has changed (but only if you used its undocumented second argument
17
- 😉) - see [migration instructions](./MIGRATING-v2.md#changes-to-the-guard-api)
18
- - API of `predicate` has changed - see
19
- [migration instructions](./MIGRATING-v2.md#predicate-is-now-a-first-class-citizen)
20
- - API of `url` decoder has changed - see
21
- [migration instructions](./MIGRATING-v2.md#url-decoder-has-changed)
22
-
23
- New features:
56
+ - Direct reliance on `lemons` has been removed
24
57
 
25
- - Include ES modules in published NPM builds (yay tree-shaking! 🍃)
26
- - Much smaller total bundle size
58
+ New decoders:
59
+
60
+ - [`always`](https://decoders.cc/api.html#always)
61
+ - [`anyNumber`](https://decoders.cc/api.html#anyNumber)
62
+ - [`never`](https://decoders.cc/api.html#never)
63
+ - [`prep()`](https://decoders.cc/api.html#prep)
64
+ - [`set()`](https://decoders.cc/api.html#set)
65
+ - [`uuid`](https://decoders.cc/api.html#uuid)
66
+ - [`uuidv1`](https://decoders.cc/api.html#uuidv1)
67
+ - [`uuidv4`](https://decoders.cc/api.html#uuidv4)
68
+
69
+ Other improvements:
70
+
71
+ - [`optional()`](https://decoders.cc/api.html#optional),
72
+ [`nullable()`](https://decoders.cc/api.html#nullable), and
73
+ [`maybe()`](https://decoders.cc/api.html#maybe) now each take an optional 2nd param to
74
+ specify a default value
27
75
  - Better error messages for nested `either`s
28
- - Guard API now has a simpler way to specify formatters
29
76
 
30
77
  Implementation changes:
31
78
 
package/Decoder.d.ts ADDED
@@ -0,0 +1,94 @@
1
+ import { Annotation } from './annotate';
2
+ import { Result } from './result';
3
+
4
+ export type Scalar = string | number | boolean | symbol | undefined | null;
5
+
6
+ export type DecodeResult<T> = Result<T, Annotation>;
7
+
8
+ export type AcceptanceFn<T, InputT = unknown> = (
9
+ blob: InputT,
10
+ ok: (value: T) => DecodeResult<T>,
11
+ err: (msg: string | Annotation) => DecodeResult<T>,
12
+ ) => DecodeResult<T>;
13
+
14
+ export interface Decoder<T> {
15
+ /**
16
+ * Verifies untrusted input. Either returns a value, or throws a decoding
17
+ * error.
18
+ */
19
+ verify(blob: unknown, formatterFn?: (ann: Annotation) => string | Error): T;
20
+
21
+ /**
22
+ * Verifies untrusted input. Either returns a value, or returns undefined.
23
+ */
24
+ value(blob: unknown): T | undefined;
25
+
26
+ /**
27
+ * Verifies untrusted input. Always returns a DecodeResult, which is either
28
+ * an "ok" value or an "error" annotation.
29
+ */
30
+ decode(blob: unknown): DecodeResult<T>;
31
+
32
+ /**
33
+ * Build a new decoder from the the current one, with an extra acceptance
34
+ * criterium.
35
+ */
36
+ refine<N extends T>(predicate: (value: T) => value is N, msg: string): Decoder<N>;
37
+ refine(predicate: (value: T) => boolean, msg: string): Decoder<T>;
38
+
39
+ /**
40
+ * Build a new decoder from the current one, with an extra rejection
41
+ * criterium.
42
+ */
43
+ reject(rejectFn: (value: T) => string | Annotation | null): Decoder<T>;
44
+
45
+ /**
46
+ * Build a new decoder from the current one, modifying its outputted value.
47
+ */
48
+ transform<V>(transformFn: (value: T) => V): Decoder<V>;
49
+
50
+ /**
51
+ * Build a new decoder from the current one, with a mutated error message
52
+ * in case of a rejection.
53
+ */
54
+ describe(message: string): Decoder<T>;
55
+
56
+ /**
57
+ * Chain together the current decoder with another acceptance function.
58
+ */
59
+ then<V>(next: AcceptanceFn<V, T>): Decoder<V>;
60
+
61
+ // Experimental APIs (please don't rely on these yet)
62
+ peek_UNSTABLE<V>(next: AcceptanceFn<V, [unknown, T]>): Decoder<V>;
63
+ }
64
+
65
+ /**
66
+ * Helper type to return the "type" of a Decoder.
67
+ *
68
+ * You can use it on types:
69
+ *
70
+ * DecoderType<Decoder<string>> // string
71
+ * DecoderType<Decoder<number[]>> // number[]
72
+ *
73
+ * Or on "values", by using the `typeof` keyword:
74
+ *
75
+ * DecoderType<typeof string> // string
76
+ * DecoderType<typeof truthy> // boolean
77
+ *
78
+ */
79
+ export type DecoderType<T> = T extends Decoder<infer V> ? V : never;
80
+
81
+ /**
82
+ * Defines a new `Decoder<T>`, by implementing a custom acceptance function.
83
+ * The function receives three arguments:
84
+ *
85
+ * 1. `blob` - the raw/unknown input (aka your external data)
86
+ * 2. `ok` - Call `ok(value)` to accept the input and return ``value``
87
+ * 3. `err` - Call `err(message)` to reject the input with error ``message``
88
+ *
89
+ * The expected return value should be a `DecodeResult<T>`, which can be
90
+ * obtained by returning the result of calling the provided `ok` or `err`
91
+ * helper functions. Please note that `ok()` and `err()` don't perform side
92
+ * effects! You'll need to _return_ those values.
93
+ */
94
+ export function define<T>(fn: AcceptanceFn<T>): Decoder<T>;
package/Decoder.js ADDED
@@ -0,0 +1,115 @@
1
+ 'use strict'
2
+
3
+ exports.__esModule = true
4
+ exports.define = define
5
+
6
+ var _annotate = require('./annotate')
7
+
8
+ var _format = require('./format')
9
+
10
+ var _result = require('./result')
11
+
12
+ function noThrow(fn) {
13
+ return function (t) {
14
+ try {
15
+ var v = fn(t)
16
+ return (0, _result.ok)(v)
17
+ } catch (e) {
18
+ return (0, _result.err)((0, _annotate.annotate)(t, e instanceof Error ? e.message : String(e)))
19
+ }
20
+ }
21
+ }
22
+
23
+ function format(err, formatter) {
24
+ var formatted = formatter(err)
25
+
26
+ if (typeof formatted === 'string') {
27
+ var _err = new Error('\n' + formatted)
28
+
29
+ _err.name = 'Decoding error'
30
+ return _err
31
+ } else {
32
+ return formatted
33
+ }
34
+ }
35
+
36
+ function define(fn) {
37
+ function decode(blob) {
38
+ return fn(blob, _result.ok, function (msg) {
39
+ return (0, _result.err)(typeof msg === 'string' ? (0, _annotate.annotate)(blob, msg) : msg)
40
+ })
41
+ }
42
+
43
+ function verify(blob, formatter) {
44
+ if (formatter === void 0) {
45
+ formatter = _format.formatInline
46
+ }
47
+
48
+ var result = decode(blob)
49
+
50
+ if (result.ok) {
51
+ return result.value
52
+ } else {
53
+ throw format(result.error, formatter)
54
+ }
55
+ }
56
+
57
+ function value(blob) {
58
+ return decode(blob).value
59
+ }
60
+
61
+ function transform(transformFn) {
62
+ return then(noThrow(transformFn))
63
+ }
64
+
65
+ function refine(predicateFn, errmsg) {
66
+ return reject(function (value) {
67
+ return predicateFn(value) ? null : errmsg
68
+ })
69
+ }
70
+
71
+ function then(next) {
72
+ return define(function (blob, ok, err) {
73
+ var result = decode(blob)
74
+ return result.ok ? next(result.value, ok, err) : result
75
+ })
76
+ }
77
+
78
+ function reject(rejectFn) {
79
+ return then(function (value, ok, err) {
80
+ var errmsg = rejectFn(value)
81
+ return errmsg === null ? ok(value) : err(typeof errmsg === 'string' ? (0, _annotate.annotate)(value, errmsg) : errmsg)
82
+ })
83
+ }
84
+
85
+ function describe(message) {
86
+ return define(function (blob, _, err) {
87
+ var result = decode(blob)
88
+
89
+ if (result.ok) {
90
+ return result
91
+ } else {
92
+ return err((0, _annotate.annotate)(result.error, message))
93
+ }
94
+ })
95
+ }
96
+
97
+ function peek_UNSTABLE(next) {
98
+ return define(function (blob, ok, err) {
99
+ var result = decode(blob)
100
+ return result.ok ? next([blob, result.value], ok, err) : result
101
+ })
102
+ }
103
+
104
+ return Object.freeze({
105
+ verify: verify,
106
+ value: value,
107
+ decode: decode,
108
+ transform: transform,
109
+ refine: refine,
110
+ reject: reject,
111
+ describe: describe,
112
+ then: then,
113
+ peek_UNSTABLE: peek_UNSTABLE,
114
+ })
115
+ }
@@ -0,0 +1,286 @@
1
+ // @flow strict
2
+
3
+ import { annotate } from './annotate';
4
+ import { formatInline } from './format';
5
+ import { err as makeErr, ok as makeOk } from './result';
6
+ import type { Annotation } from './annotate';
7
+ import type { Formatter } from './format';
8
+ import type { Result } from './result';
9
+
10
+ export type Scalar = string | number | boolean | symbol | void | null;
11
+
12
+ export type DecodeResult<T> = Result<T, Annotation>;
13
+
14
+ export type AcceptanceFn<T, InputT = mixed> = (
15
+ blob: InputT,
16
+ ok: (value: T) => DecodeResult<T>,
17
+ err: (msg: string | Annotation) => DecodeResult<T>,
18
+ ) => DecodeResult<T>;
19
+
20
+ export type Decoder<T> = {|
21
+ /**
22
+ * Verifies untrusted input. Either returns a value, or throws a decoding
23
+ * error.
24
+ */
25
+ verify(blob: mixed, formatter?: Formatter): T,
26
+
27
+ /**
28
+ * Verifies untrusted input. Either returns a value, or returns undefined.
29
+ */
30
+ value(blob: mixed): T | void,
31
+
32
+ /**
33
+ * Verifies untrusted input. Always returns a DecodeResult, which is either
34
+ * an "ok" value or an "error" annotation.
35
+ */
36
+ decode(blob: mixed): DecodeResult<T>,
37
+
38
+ /**
39
+ * Build a new decoder from the the current one, with an extra acceptance
40
+ * criterium.
41
+ */
42
+ refine(predicateFn: (value: T) => boolean, errmsg: string): Decoder<T>,
43
+
44
+ /**
45
+ * Build a new decoder from the current one, with an extra rejection
46
+ * criterium.
47
+ */
48
+ reject(rejectFn: (value: T) => string | Annotation | null): Decoder<T>,
49
+
50
+ /**
51
+ * Build a new decoder from the current one, modifying its outputted value.
52
+ */
53
+ transform<V>(transformFn: (value: T) => V): Decoder<V>,
54
+
55
+ /**
56
+ * Build a new decoder from the current one, with a mutated error message
57
+ * in case of a rejection.
58
+ */
59
+ describe(message: string): Decoder<T>,
60
+
61
+ /**
62
+ * Chain together the current decoder with another acceptance function.
63
+ */
64
+ then<V>(next: AcceptanceFn<V, T>): Decoder<V>,
65
+
66
+ // Experimental APIs (please don't rely on these yet)
67
+ peek_UNSTABLE<V>(next: AcceptanceFn<V, [mixed, T]>): Decoder<V>,
68
+ |};
69
+
70
+ /**
71
+ * Helper type to return the "type" of a Decoder.
72
+ *
73
+ * You can use it on types:
74
+ *
75
+ * DecoderType<Decoder<string>> // string
76
+ * DecoderType<Decoder<number[]>> // number[]
77
+ *
78
+ * Or on "values", by using the `typeof` keyword:
79
+ *
80
+ * DecoderType<typeof string> // string
81
+ * DecoderType<typeof truthy> // boolean
82
+ *
83
+ */
84
+ export type DecoderType<D> = $Call<<T>(Decoder<T>) => T, D>;
85
+
86
+ function noThrow<T, V>(fn: (value: T) => V): (T) => DecodeResult<V> {
87
+ return (t) => {
88
+ try {
89
+ const v = fn(t);
90
+ return makeOk(v);
91
+ } catch (e) {
92
+ return makeErr(annotate(t, e instanceof Error ? e.message : String(e)));
93
+ }
94
+ };
95
+ }
96
+
97
+ function format(err: Annotation, formatter: Formatter): Error {
98
+ const formatted = formatter(err);
99
+
100
+ // Formatter functions may return a string or an error for convenience of
101
+ // writing them. If it already returns an Error, return it unmodified. If
102
+ // it returns a string, wrap it in a "Decoding error" instance.
103
+ if (typeof formatted === 'string') {
104
+ const err = new Error(`\n${formatted}`);
105
+ err.name = 'Decoding error';
106
+ return err;
107
+ } else {
108
+ return formatted;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Defines a new `Decoder<T>`, by implementing a custom acceptance function.
114
+ * The function receives three arguments:
115
+ *
116
+ * 1. `blob` - the raw/unknown input (aka your external data)
117
+ * 2. `ok` - Call `ok(value)` to accept the input and return ``value``
118
+ * 3. `err` - Call `err(message)` to reject the input with error ``message``
119
+ *
120
+ * The expected return value should be a `DecodeResult<T>`, which can be
121
+ * obtained by returning the result of calling the provided `ok` or `err`
122
+ * helper functions. Please note that `ok()` and `err()` don't perform side
123
+ * effects! You'll need to _return_ those values.
124
+ */
125
+ export function define<T>(fn: AcceptanceFn<T>): Decoder<T> {
126
+ /**
127
+ * Verifies the untrusted/unknown input and either accepts or rejects it.
128
+ *
129
+ * Contrasted with `.verify()`, calls to `.decode()` will never fail and
130
+ * instead return a result type.
131
+ */
132
+ function decode(blob: mixed): DecodeResult<T> {
133
+ return fn(blob, makeOk, (msg: Annotation | string) =>
134
+ makeErr(typeof msg === 'string' ? annotate(blob, msg) : msg),
135
+ );
136
+ }
137
+
138
+ /**
139
+ * Verifies the untrusted/unknown input and either accepts or rejects it.
140
+ * When accepted, returns a value of type `T`. Otherwise fail with
141
+ * a runtime error.
142
+ */
143
+ function verify(blob: mixed, formatter: Formatter = formatInline): T {
144
+ const result = decode(blob);
145
+ if (result.ok) {
146
+ return result.value;
147
+ } else {
148
+ throw format(result.error, formatter);
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Verifies the untrusted/unknown input and either accepts or rejects it.
154
+ * When accepted, returns the decoded `T` value directly. Otherwise returns
155
+ * `undefined`.
156
+ *
157
+ * Use this when you're not interested in programmatically handling the
158
+ * error message.
159
+ */
160
+ function value(blob: mixed): T | void {
161
+ return decode(blob).value;
162
+ }
163
+
164
+ /**
165
+ * Accepts any value the given decoder accepts, and on success, will call
166
+ * the given function **on the decoded result**. If the transformation
167
+ * function throws an error, the whole decoder will fail using the error
168
+ * message as the failure reason.
169
+ */
170
+ function transform<V>(transformFn: (T) => V): Decoder<V> {
171
+ return then(noThrow(transformFn));
172
+ }
173
+
174
+ /**
175
+ * Adds an extra predicate to a decoder. The new decoder is like the
176
+ * original decoder, but only accepts values that also meet the
177
+ * predicate.
178
+ */
179
+ function refine(predicateFn: (value: T) => boolean, errmsg: string): Decoder<T> {
180
+ return reject((value) =>
181
+ predicateFn(value)
182
+ ? // Don't reject
183
+ null
184
+ : // Reject with the given error message
185
+ errmsg,
186
+ );
187
+ }
188
+
189
+ /**
190
+ * Chain together the current decoder with another.
191
+ *
192
+ * > _**NOTE:** This is an advanced, low-level, API. It's not recommended
193
+ * > to reach for this construct unless there is no other way. Most cases can
194
+ * > be covered more elegantly by `.transform()` or `.refine()` instead._
195
+ *
196
+ * If the current decoder accepts an input, the resulting ``T`` value will
197
+ * get passed into the given ``next`` acceptance function to further decide
198
+ * whether or not the value should get accepted or rejected.
199
+ *
200
+ * This works similar to how you would `define()` a new decoder, except
201
+ * that the ``blob`` param will now be ``T`` (a known type), rather than
202
+ * ``unknown``. This will allow the function to make a stronger assumption
203
+ * about its input and avoid re-refining inputs.
204
+ *
205
+ * If it helps, you can think of `define(...)` as equivalent to
206
+ * `unknown.then(...)`.
207
+ */
208
+ function then<V>(next: AcceptanceFn<V, T>): Decoder<V> {
209
+ return define((blob, ok, err) => {
210
+ const result = decode(blob);
211
+ return result.ok ? next(result.value, ok, err) : result;
212
+ });
213
+ }
214
+
215
+ /**
216
+ * Adds an extra predicate to a decoder. The new decoder is like the
217
+ * original decoder, but only accepts values that aren't rejected by the
218
+ * given function.
219
+ *
220
+ * The given function can return `null` to accept the decoded value, or
221
+ * return a specific error message to reject.
222
+ *
223
+ * Unlike `.refine()`, you can use this function to return a dynamic error
224
+ * message.
225
+ */
226
+ function reject(rejectFn: (value: T) => string | Annotation | null): Decoder<T> {
227
+ return then((value, ok, err) => {
228
+ const errmsg = rejectFn(value);
229
+ return errmsg === null
230
+ ? ok(value)
231
+ : err(typeof errmsg === 'string' ? annotate(value, errmsg) : errmsg);
232
+ });
233
+ }
234
+
235
+ /**
236
+ * Uses the given decoder, but will use an alternative error message in
237
+ * case it rejects. This can be used to simplify or shorten otherwise
238
+ * long or low-level/technical errors.
239
+ */
240
+ function describe(message: string): Decoder<T> {
241
+ return define((blob, _, err) => {
242
+ // Decode using the given decoder...
243
+ const result = decode(blob);
244
+ if (result.ok) {
245
+ return result;
246
+ } else {
247
+ // ...but in case of error, annotate this with the custom given
248
+ // message instead
249
+ return err(annotate(result.error, message));
250
+ }
251
+ });
252
+ }
253
+
254
+ /**
255
+ * WARNING: This is an EXPERIMENTAL API that will likely change in the
256
+ * future. Please DO NOT rely on it.
257
+ *
258
+ * Chain together the current decoder with another, but also pass along
259
+ * the original input.
260
+ *
261
+ * This is like `.then()`, but instead of this function receiving just
262
+ * the decoded result ``T``, it also receives the original input.
263
+ *
264
+ * This is an advanced, low-level, decoder.
265
+ */
266
+ function peek_UNSTABLE<V>(next: AcceptanceFn<V, [mixed, T]>): Decoder<V> {
267
+ return define((blob, ok, err) => {
268
+ const result = decode(blob);
269
+ return result.ok ? next([blob, result.value], ok, err) : result;
270
+ });
271
+ }
272
+
273
+ return Object.freeze({
274
+ verify,
275
+ value,
276
+ decode,
277
+ transform,
278
+ refine,
279
+ reject,
280
+ describe,
281
+ then,
282
+
283
+ // EXPERIMENTAL - please DO NOT rely on this method
284
+ peek_UNSTABLE,
285
+ });
286
+ }
package/Decoder.mjs ADDED
@@ -0,0 +1,108 @@
1
+ import { annotate } from './annotate.mjs'
2
+ import { formatInline } from './format.mjs'
3
+ import { err as makeErr, ok as makeOk } from './result.mjs'
4
+
5
+ function noThrow(fn) {
6
+ return function (t) {
7
+ try {
8
+ var v = fn(t)
9
+ return makeOk(v)
10
+ } catch (e) {
11
+ return makeErr(annotate(t, e instanceof Error ? e.message : String(e)))
12
+ }
13
+ }
14
+ }
15
+
16
+ function format(err, formatter) {
17
+ var formatted = formatter(err)
18
+
19
+ if (typeof formatted === 'string') {
20
+ var _err = new Error('\n' + formatted)
21
+
22
+ _err.name = 'Decoding error'
23
+ return _err
24
+ } else {
25
+ return formatted
26
+ }
27
+ }
28
+
29
+ export function define(fn) {
30
+ function decode(blob) {
31
+ return fn(blob, makeOk, function (msg) {
32
+ return makeErr(typeof msg === 'string' ? annotate(blob, msg) : msg)
33
+ })
34
+ }
35
+
36
+ function verify(blob, formatter) {
37
+ if (formatter === void 0) {
38
+ formatter = formatInline
39
+ }
40
+
41
+ var result = decode(blob)
42
+
43
+ if (result.ok) {
44
+ return result.value
45
+ } else {
46
+ throw format(result.error, formatter)
47
+ }
48
+ }
49
+
50
+ function value(blob) {
51
+ return decode(blob).value
52
+ }
53
+
54
+ function transform(transformFn) {
55
+ return then(noThrow(transformFn))
56
+ }
57
+
58
+ function refine(predicateFn, errmsg) {
59
+ return reject(function (value) {
60
+ return predicateFn(value) ? null : errmsg
61
+ })
62
+ }
63
+
64
+ function then(next) {
65
+ return define(function (blob, ok, err) {
66
+ var result = decode(blob)
67
+ return result.ok ? next(result.value, ok, err) : result
68
+ })
69
+ }
70
+
71
+ function reject(rejectFn) {
72
+ return then(function (value, ok, err) {
73
+ var errmsg = rejectFn(value)
74
+ return errmsg === null ? ok(value) : err(typeof errmsg === 'string' ? annotate(value, errmsg) : errmsg)
75
+ })
76
+ }
77
+
78
+ function describe(message) {
79
+ return define(function (blob, _, err) {
80
+ var result = decode(blob)
81
+
82
+ if (result.ok) {
83
+ return result
84
+ } else {
85
+ return err(annotate(result.error, message))
86
+ }
87
+ })
88
+ }
89
+
90
+ function peek_UNSTABLE(next) {
91
+ return define(function (blob, ok, err) {
92
+ var result = decode(blob)
93
+ return result.ok ? next([blob, result.value], ok, err) : result
94
+ })
95
+ }
96
+
97
+ return Object.freeze({
98
+ verify: verify,
99
+ value: value,
100
+ decode: decode,
101
+ transform: transform,
102
+ refine: refine,
103
+ reject: reject,
104
+ describe: describe,
105
+ then: then,
106
+ peek_UNSTABLE: peek_UNSTABLE,
107
+ })
108
+ }