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
package/CHANGELOG.md CHANGED
@@ -1,3 +1,30 @@
1
+ ## v2.0.0-beta
2
+
3
+ Potentially breaking changes:
4
+
5
+ - Drop support for all Node versions below 12.x
6
+ - Drop support for Flow versions below 0.142.0
7
+ - Drop all package dependencies
8
+
9
+ New features:
10
+
11
+ - Include ES modules in published NPM builds (yay tree-shaking! 🍃)
12
+ - Much smaller total bundle size
13
+ - Better error messages for nested `either`s
14
+ - Guard API now has a simpler way to specify formatters
15
+
16
+ Implementation changes:
17
+
18
+ - Major reorganization of internal module structure
19
+ - Various simplification of internals
20
+
21
+ ## v1.25.5
22
+
23
+ - Fix compatibility issue with TypeScript projects configured with
24
+ `strictNullChecks: false` (or `strict: false`) (Thanks, @stevekrouse and @djlauk!)
25
+
26
+ - Officially support Node 16.x
27
+
1
28
  ## v1.25.4
2
29
 
3
30
  - Expose `nonEmptyArray` function in TypeScript (Thanks, @mszczepanczyk!)
@@ -315,7 +342,7 @@ to upgrade:
315
342
  ```javascript
316
343
  const mydecoder: Decoder<string> = predicate(
317
344
  (s) => s.startsWith('x'),
318
- 'Must start with "x"'
345
+ 'Must start with "x"',
319
346
  );
320
347
  ```
321
348
 
@@ -325,7 +352,7 @@ to upgrade:
325
352
  const mydecoder: Decoder<string, string> = predicate(
326
353
  // ^^^^^^ Provide the input type to predicate() decoders
327
354
  (s) => s.startsWith('x'),
328
- 'Must start with "x"'
355
+ 'Must start with "x"',
329
356
  );
330
357
  ```
331
358
 
@@ -549,6 +576,6 @@ to upgrade:
549
576
  object({
550
577
  name: string,
551
578
  age: number,
552
- })
579
+ }),
553
580
  );
554
581
  ```
package/cjs/_guard.js ADDED
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.guard = guard;
5
+
6
+ var Result = _interopRequireWildcard(require("./result"));
7
+
8
+ var _format = require("./format");
9
+
10
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
11
+
12
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
13
+
14
+ function guard(decoder, formatter) {
15
+ if (formatter === void 0) {
16
+ formatter = _format.formatInline;
17
+ }
18
+
19
+ return function (blob) {
20
+ return Result.unwrap(Result.mapError(decoder(blob), function (annotation) {
21
+ var err = new Error('\n' + formatter(annotation));
22
+ err.name = 'Decoding error';
23
+ return err;
24
+ }));
25
+ };
26
+ }
@@ -0,0 +1,20 @@
1
+ // @flow strict
2
+
3
+ import * as Result from './result';
4
+ import { formatInline } from './format';
5
+ import type { Annotation } from './annotate';
6
+ import type { Decoder, Guard } from './_types';
7
+
8
+ export function guard<T>(
9
+ decoder: Decoder<T>,
10
+ formatter: (Annotation) => string = formatInline,
11
+ ): Guard<T> {
12
+ return (blob: mixed) =>
13
+ Result.unwrap(
14
+ Result.mapError(decoder(blob), (annotation) => {
15
+ const err = new Error('\n' + formatter(annotation));
16
+ err.name = 'Decoding error';
17
+ return err;
18
+ }),
19
+ );
20
+ }
package/cjs/_types.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,20 @@
1
+ // @flow strict
2
+
3
+ import type { Annotation } from './annotate';
4
+ import type { Result } from './result';
5
+
6
+ export type Scalar = string | number | boolean | symbol | void | null;
7
+
8
+ export type Predicate<T> = (T) => boolean;
9
+ export type DecodeResult<T> = Result<T, Annotation>;
10
+
11
+ export type Decoder<T, F = mixed> = (F) => DecodeResult<T>;
12
+ export type Guard<T> = (mixed) => T;
13
+
14
+ /**
15
+ * A "type function" which informs Flow about how a type will be modified at runtime.
16
+ * Read this as "given a Guard of type T, I can produce a value of type T". This
17
+ * definition helps construct $ObjMap types.
18
+ */
19
+ export type DecoderType = <T>(Decoder<T>) => T;
20
+ export type GuardType = <T>(Guard<T>) => T;
package/cjs/_utils.js ADDED
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.INDENT = void 0;
5
+ exports.asDate = asDate;
6
+ exports.indent = indent;
7
+ exports.isDate = isDate;
8
+ exports.isMultiline = isMultiline;
9
+ exports.summarize = summarize;
10
+ // $FlowFixMe[unclear-type] - deliberate casting
11
+ // Two spaces of indentation
12
+ var INDENT = ' ';
13
+ /**
14
+ * `x instanceof Date` checks are unreliable across stack frames (that information
15
+ * might get lost by the JS runtime), so we'll have to reside to more runtime
16
+ * inspection checks.
17
+ *
18
+ * Taken from https://stackoverflow.com/a/44198641
19
+ */
20
+
21
+ exports.INDENT = INDENT;
22
+
23
+ function isDate(value) {
24
+ return !!value && // $FlowFixMe[method-unbinding]
25
+ Object.prototype.toString.call(value) === '[object Date]' && !isNaN(value);
26
+ }
27
+ /**
28
+ * Is value is a valid Date instance, then return that. If not, then return
29
+ * null.
30
+ */
31
+
32
+
33
+ function asDate(value) {
34
+ return isDate(value) ? value : null;
35
+ }
36
+
37
+ function isMultiline(s) {
38
+ return s.indexOf('\n') >= 0;
39
+ }
40
+
41
+ function indent(s, prefix) {
42
+ if (prefix === void 0) {
43
+ prefix = INDENT;
44
+ }
45
+
46
+ if (isMultiline(s)) {
47
+ return s.split('\n').map(function (line) {
48
+ return prefix + line;
49
+ }).join('\n');
50
+ } else {
51
+ return prefix + s;
52
+ }
53
+ }
54
+ /**
55
+ * Walks the annotation tree and emits the annotation's key path within the
56
+ * object tree, and the message as a series of messages (array of strings).
57
+ */
58
+
59
+
60
+ function summarize(ann, keypath) {
61
+ if (keypath === void 0) {
62
+ keypath = [];
63
+ }
64
+
65
+ var result = [];
66
+
67
+ if (ann.type === 'array') {
68
+ var items = ann.items;
69
+ var index = 0;
70
+ items.forEach(function (ann) {
71
+ summarize(ann, [].concat(keypath, [index++])).forEach(function (item) {
72
+ return (// Collect to results
73
+ result.push(item)
74
+ );
75
+ });
76
+ });
77
+ } else if (ann.type === 'object') {
78
+ var fields = ann.fields;
79
+ Object.keys(fields).forEach(function (key) {
80
+ var value = fields[key];
81
+ summarize(value, [].concat(keypath, [key])).forEach(function (item) {
82
+ return (// Collect to results
83
+ result.push(item)
84
+ );
85
+ });
86
+ });
87
+ }
88
+
89
+ var text = ann.text;
90
+
91
+ if (!text) {
92
+ return result;
93
+ }
94
+
95
+ var prefix;
96
+
97
+ if (keypath.length === 0) {
98
+ prefix = '';
99
+ } else if (keypath.length === 1) {
100
+ prefix = typeof keypath[0] === 'number' ? "Value at index " + keypath[0] + ": " : "Value at key " + JSON.stringify(keypath[0]) + ": ";
101
+ } else {
102
+ prefix = "Value at keypath " + keypath.map(function (x) {
103
+ return x.toString();
104
+ }).join('.') + ": ";
105
+ }
106
+
107
+ return [].concat(result, [prefix + text]);
108
+ }
@@ -0,0 +1,97 @@
1
+ // @flow strict
2
+
3
+ import type { Annotation } from './annotate';
4
+
5
+ // $FlowFixMe[unclear-type] - deliberate casting
6
+ type cast = any;
7
+
8
+ // Two spaces of indentation
9
+ export const INDENT = ' ';
10
+
11
+ /**
12
+ * `x instanceof Date` checks are unreliable across stack frames (that information
13
+ * might get lost by the JS runtime), so we'll have to reside to more runtime
14
+ * inspection checks.
15
+ *
16
+ * Taken from https://stackoverflow.com/a/44198641
17
+ */
18
+ export function isDate(value: mixed): boolean {
19
+ return (
20
+ !!value &&
21
+ // $FlowFixMe[method-unbinding]
22
+ Object.prototype.toString.call(value) === '[object Date]' &&
23
+ !isNaN(value)
24
+ );
25
+ }
26
+
27
+ /**
28
+ * Is value is a valid Date instance, then return that. If not, then return
29
+ * null.
30
+ */
31
+ export function asDate(value: mixed): Date | null {
32
+ return isDate(value) ? ((value: cast): Date) : null;
33
+ }
34
+
35
+ export function isMultiline(s: string): boolean {
36
+ return s.indexOf('\n') >= 0;
37
+ }
38
+
39
+ export function indent(s: string, prefix: string = INDENT): string {
40
+ if (isMultiline(s)) {
41
+ return s
42
+ .split('\n')
43
+ .map((line) => prefix + line)
44
+ .join('\n');
45
+ } else {
46
+ return prefix + s;
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Walks the annotation tree and emits the annotation's key path within the
52
+ * object tree, and the message as a series of messages (array of strings).
53
+ */
54
+ export function summarize(
55
+ ann: Annotation,
56
+ keypath: $ReadOnlyArray<number | string> = [],
57
+ ): Array<string> {
58
+ const result: Array<string> = [];
59
+
60
+ if (ann.type === 'array') {
61
+ const items = ann.items;
62
+ let index = 0;
63
+ items.forEach((ann) => {
64
+ summarize(ann, [...keypath, index++]).forEach((item) =>
65
+ // Collect to results
66
+ result.push(item),
67
+ );
68
+ });
69
+ } else if (ann.type === 'object') {
70
+ const fields = ann.fields;
71
+ Object.keys(fields).forEach((key) => {
72
+ const value = fields[key];
73
+ summarize(value, [...keypath, key]).forEach((item) =>
74
+ // Collect to results
75
+ result.push(item),
76
+ );
77
+ });
78
+ }
79
+
80
+ const text = ann.text;
81
+ if (!text) {
82
+ return result;
83
+ }
84
+
85
+ let prefix: string;
86
+ if (keypath.length === 0) {
87
+ prefix = '';
88
+ } else if (keypath.length === 1) {
89
+ prefix =
90
+ typeof keypath[0] === 'number'
91
+ ? `Value at index ${keypath[0]}: `
92
+ : `Value at key ${JSON.stringify(keypath[0])}: `;
93
+ } else {
94
+ prefix = `Value at keypath ${keypath.map((x) => x.toString()).join('.')}: `;
95
+ }
96
+ return [...result, prefix + text];
97
+ }
@@ -0,0 +1,161 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.__private_annotate = annotate;
5
+ exports.annotate = public_annotate;
6
+ exports.annotateObject = public_annotateObject;
7
+ exports.array = array;
8
+ exports.asAnnotation = asAnnotation;
9
+ exports.circularRef = circularRef;
10
+ exports.func = func;
11
+ exports.merge = merge;
12
+ exports.object = object;
13
+ exports.scalar = scalar;
14
+ exports.unknown = unknown;
15
+ exports.updateText = updateText;
16
+
17
+ function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
18
+
19
+ var _register = new WeakSet();
20
+
21
+ function brand(ann) {
22
+ _register.add(ann);
23
+
24
+ return ann;
25
+ }
26
+
27
+ function object(fields, text) {
28
+ return brand({
29
+ type: 'object',
30
+ fields: fields,
31
+ text: text
32
+ });
33
+ }
34
+
35
+ function array(items, text) {
36
+ return brand({
37
+ type: 'array',
38
+ items: items,
39
+ text: text
40
+ });
41
+ }
42
+
43
+ function func(text) {
44
+ return brand({
45
+ type: 'function',
46
+ text: text
47
+ });
48
+ }
49
+
50
+ function unknown(value, text) {
51
+ return brand({
52
+ type: 'unknown',
53
+ value: value,
54
+ text: text
55
+ });
56
+ }
57
+
58
+ function scalar(value, text) {
59
+ return brand({
60
+ type: 'scalar',
61
+ value: value,
62
+ text: text
63
+ });
64
+ }
65
+
66
+ function circularRef(text) {
67
+ return brand({
68
+ type: 'circular-ref',
69
+ text: text
70
+ });
71
+ }
72
+ /**
73
+ * Given an existing Annotation, set the annotation's text to a new value.
74
+ */
75
+
76
+
77
+ function updateText(annotation, text) {
78
+ if (text !== undefined) {
79
+ return brand(_extends({}, annotation, {
80
+ text: text
81
+ }));
82
+ } else {
83
+ return annotation;
84
+ }
85
+ }
86
+ /**
87
+ * Given an existing ObjectAnnotation, merges new Annotations in there.
88
+ */
89
+
90
+
91
+ function merge(objAnnotation, fields) {
92
+ var newFields = _extends({}, objAnnotation.fields, fields);
93
+
94
+ return object(newFields, objAnnotation.text);
95
+ }
96
+
97
+ function asAnnotation(thing) {
98
+ return typeof thing === 'object' && thing !== null && _register.has(thing) ? thing : undefined;
99
+ }
100
+
101
+ function annotateArray(value, text, seen) {
102
+ seen.add(value);
103
+ var items = value.map(function (v) {
104
+ return annotate(v, undefined, seen);
105
+ });
106
+ return array(items, text);
107
+ }
108
+
109
+ function annotateObject(obj, text, seen) {
110
+ seen.add(obj);
111
+ var fields = {};
112
+ Object.keys(obj).forEach(function (key) {
113
+ var value = obj[key];
114
+ fields[key] = annotate(value, undefined, seen);
115
+ });
116
+ return object(fields, text);
117
+ }
118
+
119
+ function annotate(value, text, seen) {
120
+ if (value === null || value === undefined || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'symbol' || typeof value.getMonth === 'function') {
121
+ return scalar(value, text);
122
+ }
123
+
124
+ var ann = asAnnotation(value);
125
+
126
+ if (ann) {
127
+ return updateText(ann, text);
128
+ }
129
+
130
+ if (Array.isArray(value)) {
131
+ // "Circular references" can only exist in objects or arrays
132
+ if (seen.has(value)) {
133
+ return circularRef(text);
134
+ } else {
135
+ return annotateArray(value, text, seen);
136
+ }
137
+ }
138
+
139
+ if (typeof value === 'object') {
140
+ // "Circular references" can only exist in objects or arrays
141
+ if (seen.has(value)) {
142
+ return circularRef(text);
143
+ } else {
144
+ return annotateObject(value, text, seen);
145
+ }
146
+ }
147
+
148
+ if (typeof value === 'function') {
149
+ return func(text);
150
+ }
151
+
152
+ return unknown(value, text);
153
+ }
154
+
155
+ function public_annotate(value, text) {
156
+ return annotate(value, text, new WeakSet());
157
+ }
158
+
159
+ function public_annotateObject(obj, text) {
160
+ return annotateObject(obj, text, new WeakSet());
161
+ }
@@ -0,0 +1,218 @@
1
+ // @flow strict
2
+
3
+ type cast = $FlowFixMe;
4
+
5
+ const _register: WeakSet<{ ... }> = new WeakSet();
6
+
7
+ export type ObjectAnnotation = {|
8
+ +type: 'object',
9
+ +fields: { +[key: string]: Annotation },
10
+ +text?: string,
11
+ |};
12
+
13
+ export type ArrayAnnotation = {|
14
+ +type: 'array',
15
+ +items: $ReadOnlyArray<Annotation>,
16
+ +text?: string,
17
+ |};
18
+
19
+ export type ScalarAnnotation = {|
20
+ +type: 'scalar',
21
+ +value: mixed,
22
+ +text?: string,
23
+ |};
24
+
25
+ export type FunctionAnnotation = {|
26
+ +type: 'function',
27
+ +text?: string,
28
+ |};
29
+
30
+ export type CircularRefAnnotation = {|
31
+ +type: 'circular-ref',
32
+ +text?: string,
33
+ |};
34
+
35
+ export type UnknownAnnotation = {|
36
+ +type: 'unknown',
37
+ +value: mixed,
38
+ +text?: string,
39
+ |};
40
+
41
+ export type Annotation =
42
+ | ObjectAnnotation
43
+ | ArrayAnnotation
44
+ | ScalarAnnotation
45
+ | FunctionAnnotation
46
+ | CircularRefAnnotation
47
+ | UnknownAnnotation;
48
+
49
+ function brand<A: Annotation>(ann: A): A {
50
+ _register.add(ann);
51
+ return ann;
52
+ }
53
+
54
+ export function object(
55
+ fields: { +[key: string]: Annotation },
56
+ text?: string,
57
+ ): ObjectAnnotation {
58
+ return brand({ type: 'object', fields, text });
59
+ }
60
+
61
+ export function array(items: $ReadOnlyArray<Annotation>, text?: string): ArrayAnnotation {
62
+ return brand({
63
+ type: 'array',
64
+ items,
65
+ text,
66
+ });
67
+ }
68
+
69
+ export function func(text?: string): FunctionAnnotation {
70
+ return brand({
71
+ type: 'function',
72
+ text,
73
+ });
74
+ }
75
+
76
+ export function unknown(value: mixed, text?: string): UnknownAnnotation {
77
+ return brand({
78
+ type: 'unknown',
79
+ value,
80
+ text,
81
+ });
82
+ }
83
+
84
+ export function scalar(value: mixed, text?: string): ScalarAnnotation {
85
+ return brand({
86
+ type: 'scalar',
87
+ value,
88
+ text,
89
+ });
90
+ }
91
+
92
+ export function circularRef(text?: string): CircularRefAnnotation {
93
+ return brand({
94
+ type: 'circular-ref',
95
+ text,
96
+ });
97
+ }
98
+
99
+ /**
100
+ * Given an existing Annotation, set the annotation's text to a new value.
101
+ */
102
+ export function updateText<A: Annotation>(annotation: A, text?: string): A {
103
+ if (text !== undefined) {
104
+ return brand({ ...annotation, text });
105
+ } else {
106
+ return annotation;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Given an existing ObjectAnnotation, merges new Annotations in there.
112
+ */
113
+ export function merge(
114
+ objAnnotation: ObjectAnnotation,
115
+ fields: { +[key: string]: Annotation },
116
+ ): ObjectAnnotation {
117
+ const newFields = { ...objAnnotation.fields, ...fields };
118
+ return object(newFields, objAnnotation.text);
119
+ }
120
+
121
+ export function asAnnotation(thing: mixed): Annotation | void {
122
+ return typeof thing === 'object' && thing !== null && _register.has(thing)
123
+ ? ((thing: cast): Annotation)
124
+ : undefined;
125
+ }
126
+
127
+ type RefSet = WeakSet<{ ... } | $ReadOnlyArray<mixed>>;
128
+
129
+ function annotateArray(
130
+ value: $ReadOnlyArray<mixed>,
131
+ text?: string,
132
+ seen: RefSet,
133
+ ): ArrayAnnotation | CircularRefAnnotation {
134
+ seen.add(value);
135
+
136
+ const items = value.map((v) => annotate(v, undefined, seen));
137
+ return array(items, text);
138
+ }
139
+
140
+ function annotateObject(
141
+ obj: { +[string]: mixed },
142
+ text?: string,
143
+ seen: RefSet,
144
+ ): ObjectAnnotation {
145
+ seen.add(obj);
146
+
147
+ const fields = {};
148
+ Object.keys(obj).forEach((key) => {
149
+ const value = obj[key];
150
+ fields[key] = annotate(value, undefined, seen);
151
+ });
152
+ return object(fields, text);
153
+ }
154
+
155
+ function annotate(value: mixed, text?: string, seen: RefSet): Annotation {
156
+ if (
157
+ value === null ||
158
+ value === undefined ||
159
+ typeof value === 'string' ||
160
+ typeof value === 'number' ||
161
+ typeof value === 'boolean' ||
162
+ typeof value === 'symbol' ||
163
+ typeof value.getMonth === 'function'
164
+ ) {
165
+ return scalar(value, text);
166
+ }
167
+
168
+ const ann = asAnnotation(value);
169
+ if (ann) {
170
+ return updateText(ann, text);
171
+ }
172
+
173
+ if (Array.isArray(value)) {
174
+ // "Circular references" can only exist in objects or arrays
175
+ if (seen.has(value)) {
176
+ return circularRef(text);
177
+ } else {
178
+ return annotateArray(value, text, seen);
179
+ }
180
+ }
181
+
182
+ if (typeof value === 'object') {
183
+ // "Circular references" can only exist in objects or arrays
184
+ if (seen.has(value)) {
185
+ return circularRef(text);
186
+ } else {
187
+ return annotateObject(value, text, seen);
188
+ }
189
+ }
190
+
191
+ if (typeof value === 'function') {
192
+ return func(text);
193
+ }
194
+
195
+ return unknown(value, text);
196
+ }
197
+
198
+ function public_annotate(value: mixed, text?: string): Annotation {
199
+ return annotate(value, text, new WeakSet());
200
+ }
201
+
202
+ function public_annotateObject(
203
+ obj: { +[string]: mixed },
204
+ text?: string,
205
+ ): ObjectAnnotation {
206
+ return annotateObject(obj, text, new WeakSet());
207
+ }
208
+
209
+ export {
210
+ // This construct just ensures the "seen" weakmap (used for circular
211
+ // reference detection) isn't made part of the public API.
212
+ public_annotate as annotate,
213
+ public_annotateObject as annotateObject,
214
+ //
215
+ // NOTE: Don't acces theses private APIs directly. They are only exported here
216
+ // to better enable unit testing.
217
+ annotate as __private_annotate,
218
+ };