arktype 0.5.1 → 1.0.0-alpha

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 (93) hide show
  1. package/README.md +1 -1
  2. package/dist/api.cjs +4 -2
  3. package/dist/api.d.ts +1 -1
  4. package/dist/api.mjs +1 -1
  5. package/dist/cjs/nodes/branch.js +3 -3
  6. package/dist/cjs/nodes/compose.js +4 -4
  7. package/dist/cjs/nodes/discriminate.js +2 -2
  8. package/dist/cjs/nodes/node.js +33 -30
  9. package/dist/cjs/nodes/predicate.js +1 -7
  10. package/dist/cjs/nodes/rules/props.js +39 -0
  11. package/dist/cjs/nodes/rules/rules.js +5 -2
  12. package/dist/cjs/parse/ast/config.js +13 -0
  13. package/dist/cjs/parse/ast/distributableFunction.js +2 -2
  14. package/dist/cjs/parse/ast/keyof.js +1 -1
  15. package/dist/cjs/parse/ast/morph.js +4 -3
  16. package/dist/cjs/parse/ast/narrow.js +8 -1
  17. package/dist/cjs/{nodes/infer.js → parse/ast/node.js} +0 -0
  18. package/dist/cjs/parse/ast/tuple.js +2 -1
  19. package/dist/cjs/parse/definition.js +2 -2
  20. package/dist/cjs/parse/string/reduce/dynamic.js +2 -2
  21. package/dist/cjs/parse/string/shift/operand/unenclosed.js +1 -1
  22. package/dist/cjs/parse/string/string.js +3 -3
  23. package/dist/cjs/scopes/{standard.js → ark.js} +9 -8
  24. package/dist/cjs/scopes/expressions.js +9 -9
  25. package/dist/cjs/scopes/scope.js +73 -75
  26. package/dist/cjs/scopes/type.js +24 -38
  27. package/dist/cjs/scopes/validation/creditCard.js +47 -0
  28. package/dist/cjs/scopes/validation/date.js +63 -0
  29. package/dist/cjs/scopes/validation/validation.js +95 -0
  30. package/dist/cjs/traverse/problems.js +48 -19
  31. package/dist/cjs/traverse/traverse.js +80 -25
  32. package/dist/cjs/utils/generics.js +16 -0
  33. package/dist/cjs/utils/serialize.js +29 -53
  34. package/dist/mjs/nodes/branch.js +2 -2
  35. package/dist/mjs/nodes/compose.js +5 -5
  36. package/dist/mjs/nodes/discriminate.js +2 -2
  37. package/dist/mjs/nodes/node.js +31 -31
  38. package/dist/mjs/nodes/predicate.js +1 -6
  39. package/dist/mjs/nodes/rules/props.js +39 -0
  40. package/dist/mjs/nodes/rules/rules.js +5 -2
  41. package/dist/mjs/parse/ast/config.js +5 -0
  42. package/dist/mjs/parse/ast/distributableFunction.js +2 -2
  43. package/dist/mjs/parse/ast/keyof.js +1 -1
  44. package/dist/mjs/parse/ast/morph.js +5 -4
  45. package/dist/mjs/parse/ast/narrow.js +9 -2
  46. package/dist/mjs/{nodes/infer.js → parse/ast/node.js} +0 -0
  47. package/dist/mjs/parse/ast/tuple.js +2 -1
  48. package/dist/mjs/parse/definition.js +2 -2
  49. package/dist/mjs/parse/string/reduce/dynamic.js +2 -2
  50. package/dist/mjs/parse/string/shift/operand/unenclosed.js +1 -1
  51. package/dist/mjs/parse/string/string.js +3 -3
  52. package/dist/mjs/scopes/{standard.js → ark.js} +8 -7
  53. package/dist/mjs/scopes/expressions.js +9 -9
  54. package/dist/mjs/scopes/scope.js +70 -76
  55. package/dist/mjs/scopes/type.js +22 -38
  56. package/dist/mjs/scopes/validation/creditCard.js +34 -0
  57. package/dist/mjs/scopes/validation/date.js +49 -0
  58. package/dist/mjs/scopes/validation/validation.js +81 -0
  59. package/dist/mjs/traverse/problems.js +45 -18
  60. package/dist/mjs/traverse/traverse.js +82 -27
  61. package/dist/mjs/utils/generics.js +11 -0
  62. package/dist/mjs/utils/serialize.js +29 -52
  63. package/dist/tsconfig.temp.tsbuildinfo +1 -1
  64. package/dist/types/nodes/branch.d.ts +8 -6
  65. package/dist/types/nodes/node.d.ts +24 -12
  66. package/dist/types/nodes/predicate.d.ts +4 -8
  67. package/dist/types/nodes/rules/props.d.ts +23 -8
  68. package/dist/types/nodes/rules/rules.d.ts +2 -2
  69. package/dist/types/parse/ast/ast.d.ts +1 -1
  70. package/dist/types/parse/ast/config.d.ts +10 -0
  71. package/dist/types/parse/ast/distributableFunction.d.ts +1 -1
  72. package/dist/types/parse/ast/morph.d.ts +2 -2
  73. package/dist/types/parse/ast/narrow.d.ts +1 -1
  74. package/dist/types/{nodes/infer.d.ts → parse/ast/node.d.ts} +14 -14
  75. package/dist/types/parse/ast/tuple.d.ts +8 -7
  76. package/dist/types/parse/definition.d.ts +2 -2
  77. package/dist/types/parse/string/reduce/dynamic.d.ts +5 -5
  78. package/dist/types/parse/string/string.d.ts +3 -3
  79. package/dist/types/scopes/{standard.d.ts → ark.d.ts} +15 -86
  80. package/dist/types/scopes/expressions.d.ts +3 -3
  81. package/dist/types/scopes/scope.d.ts +24 -11
  82. package/dist/types/scopes/type.d.ts +37 -20
  83. package/dist/types/scopes/validation/creditCard.d.ts +2 -0
  84. package/dist/types/scopes/validation/date.d.ts +23 -0
  85. package/dist/types/scopes/validation/validation.d.ts +28 -0
  86. package/dist/types/traverse/problems.d.ts +14 -8
  87. package/dist/types/traverse/traverse.d.ts +18 -3
  88. package/dist/types/utils/generics.d.ts +10 -5
  89. package/dist/types/utils/serialize.d.ts +0 -1
  90. package/package.json +2 -2
  91. package/dist/cjs/scopes/validation.js +0 -79
  92. package/dist/mjs/scopes/validation.js +0 -66
  93. package/dist/types/scopes/validation.d.ts +0 -25
@@ -0,0 +1,49 @@
1
+ import { rootType } from "../scope.js";
2
+ const dayDelimiterMatcher = /^[./-]$/;
3
+ // ISO 8601 date/time modernized from https://github.com/validatorjs/validator.js/blob/master/src/lib/isISO8601.js
4
+ // Based on https://tc39.es/ecma262/#sec-date-time-string-format, the T
5
+ // delimiter for date/time is mandatory. Regex from validator.js strict matcher:
6
+ const iso8601Matcher = /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
7
+ const isValidDateInstance = (date)=>!isNaN(date);
8
+ const writeFormattedMustBe = (format)=>`a ${format}-formatted date`;
9
+ export const tryParseDate = (data, opts)=>{
10
+ if (!opts?.format) {
11
+ const result = new Date(data);
12
+ return isValidDateInstance(result) ? result : "a valid date";
13
+ }
14
+ if (opts.format === "iso8601") {
15
+ return iso8601Matcher.test(data) ? new Date(data) : writeFormattedMustBe("iso8601");
16
+ }
17
+ const dataParts = data.split(dayDelimiterMatcher);
18
+ // will be the first delimiter matched, if there is one
19
+ const delimiter = data[dataParts[0].length];
20
+ const formatParts = delimiter ? opts.format.split(delimiter) : [
21
+ opts.format
22
+ ];
23
+ if (dataParts.length !== formatParts.length) {
24
+ return writeFormattedMustBe(opts.format);
25
+ }
26
+ const parsedParts = {};
27
+ for(let i = 0; i < formatParts.length; i++){
28
+ if (dataParts[i].length !== formatParts[i].length && // if format is "m" or "d", data is allowed to be 1 or 2 characters
29
+ !(formatParts[i].length === 1 && dataParts[i].length === 2)) {
30
+ return writeFormattedMustBe(opts.format);
31
+ }
32
+ parsedParts[formatParts[i][0]] = dataParts[i];
33
+ }
34
+ const date = new Date(`${parsedParts.m}/${parsedParts.d}/${parsedParts.y}`);
35
+ if (`${date.getDate()}` === parsedParts.d) {
36
+ return date;
37
+ }
38
+ return writeFormattedMustBe(opts.format);
39
+ };
40
+ export const parsedDate = rootType([
41
+ rootType.from({
42
+ string: true
43
+ }),
44
+ "|>",
45
+ (s, problems)=>{
46
+ const result = tryParseDate(s);
47
+ return typeof result === "string" ? problems.mustBe(result) : result;
48
+ }
49
+ ]);
@@ -0,0 +1,81 @@
1
+ import { wellFormedIntegerMatcher, wellFormedNumberMatcher } from "../../utils/numericLiterals.js";
2
+ import { rootType, scope } from "../scope.js";
3
+ import { creditCard } from "./creditCard.js";
4
+ import { parsedDate } from "./date.js";
5
+ // Non-trivial expressions should have an explanation or attribution
6
+ const parsedNumber = rootType([
7
+ wellFormedNumberMatcher,
8
+ "|>",
9
+ (s)=>parseFloat(s)
10
+ ], {
11
+ mustBe: "a well-formed numeric string"
12
+ });
13
+ const parsedInteger = rootType([
14
+ wellFormedIntegerMatcher,
15
+ "|>",
16
+ (s)=>parseInt(s)
17
+ ], {
18
+ mustBe: "a well-formed integer string"
19
+ });
20
+ // https://www.regular-expressions.info/email.html
21
+ const email = rootType(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, {
22
+ mustBe: "a valid email"
23
+ });
24
+ // https://github.com/validatorjs/validator.js/blob/master/src/lib/isUUID.js
25
+ const uuid = rootType(/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/, {
26
+ mustBe: "a valid UUID"
27
+ });
28
+ // https://semver.org/
29
+ const semver = rootType(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/, {
30
+ mustBe: "a valid semantic version (see https://semver.org/)"
31
+ });
32
+ export const validationScope = scope({
33
+ // Character sets
34
+ alpha: [
35
+ /^[A-Za-z]*$/,
36
+ ":",
37
+ {
38
+ mustBe: "only letters"
39
+ }
40
+ ],
41
+ alphanumeric: [
42
+ /^[A-Za-z\d]*$/,
43
+ ":",
44
+ {
45
+ mustBe: "only letters and digits"
46
+ }
47
+ ],
48
+ lowercase: [
49
+ /^[a-z]*$/,
50
+ ":",
51
+ {
52
+ mustBe: "only lowercase letters"
53
+ }
54
+ ],
55
+ uppercase: [
56
+ /^[A-Z]*$/,
57
+ ":",
58
+ {
59
+ mustBe: "only uppercase letters"
60
+ }
61
+ ],
62
+ creditCard,
63
+ email,
64
+ uuid,
65
+ parsedNumber,
66
+ parsedInteger,
67
+ parsedDate,
68
+ semver,
69
+ integer: [
70
+ "node",
71
+ {
72
+ number: {
73
+ divisor: 1
74
+ }
75
+ }
76
+ ]
77
+ }, {
78
+ name: "validation",
79
+ standard: false
80
+ });
81
+ export const validation = validationScope.compile();
@@ -38,17 +38,17 @@ function _classPrivateFieldSet(receiver, privateMap, value) {
38
38
  _classApplyDescriptorSet(receiver, descriptor, value);
39
39
  return value;
40
40
  }
41
- var _definitions_code, _definitions_code1;
42
41
  import { Scanner } from "../parse/string/shift/scanner.js";
43
42
  import { DataWrapper } from "../utils/data.js";
44
43
  import { domainDescriptions } from "../utils/domains.js";
44
+ import { objectKeysOf } from "../utils/generics.js";
45
45
  import { isWellFormedInteger } from "../utils/numericLiterals.js";
46
46
  import { objectKindDescriptions } from "../utils/objectKinds.js";
47
47
  import { Path } from "../utils/paths.js";
48
48
  import { stringify } from "../utils/serialize.js";
49
49
  export class ArkTypeError extends TypeError {
50
50
  constructor(problems){
51
- super(problems.summary);
51
+ super(`${problems}`);
52
52
  this.cause = problems;
53
53
  }
54
54
  }
@@ -63,7 +63,7 @@ export class Problem {
63
63
  return this.writers.writeReason(this.mustBe, new DataWrapper(this.data));
64
64
  }
65
65
  get mustBe() {
66
- return this.writers.mustBe(this.source);
66
+ return typeof this.writers.mustBe === "string" ? this.writers.mustBe : this.writers.mustBe(this.source);
67
67
  }
68
68
  constructor(code, path, data, source, writers){
69
69
  this.code = code;
@@ -78,13 +78,16 @@ export class Problem {
78
78
  }
79
79
  var _state = /*#__PURE__*/ new WeakMap();
80
80
  class ProblemArray extends Array {
81
+ mustBe(description, opts) {
82
+ return this.add("custom", description, opts);
83
+ }
81
84
  add(code, source, opts) {
82
85
  // copy the path to avoid future mutations affecting it
83
86
  const path = opts?.path ?? Path.from(_classPrivateFieldGet(this, _state).path);
84
87
  const data = // we have to check for the presence of the key explicitly since the
85
88
  // data could be undefined or null
86
89
  opts && "data" in opts ? opts.data : _classPrivateFieldGet(this, _state).data;
87
- const problem = new Problem(code, path, data, source, _classPrivateFieldGet(this, _state).getConfigForProblemCode(code));
90
+ const problem = new Problem(code, path, data, source, _classPrivateFieldGet(this, _state).getProblemConfig(code));
88
91
  this.addProblem(problem);
89
92
  return problem;
90
93
  }
@@ -98,7 +101,7 @@ class ProblemArray extends Array {
98
101
  const problemIntersection = new Problem("multi", existing.path, existing.data, [
99
102
  existing,
100
103
  problem
101
- ], _classPrivateFieldGet(this, _state).getConfigForProblemCode("multi"));
104
+ ], _classPrivateFieldGet(this, _state).getProblemConfig("multi"));
102
105
  const existingIndex = this.indexOf(existing);
103
106
  // If existing is found (which it always should be unless this was externally mutated),
104
107
  // replace it with the new problem intersection. In case it isn't for whatever reason,
@@ -113,10 +116,10 @@ class ProblemArray extends Array {
113
116
  this.count++;
114
117
  }
115
118
  get summary() {
116
- return this.join("\n");
119
+ return `${this}`;
117
120
  }
118
121
  toString() {
119
- return this.summary;
122
+ return this.join("\n");
120
123
  }
121
124
  throw() {
122
125
  throw new ArkTypeError(this);
@@ -155,15 +158,7 @@ export const describeBranches = (descriptions)=>{
155
158
  };
156
159
  const writeDefaultReason = (mustBe, was)=>`must be ${mustBe}${was && ` (was ${was})`}`;
157
160
  const addDefaultContext = (reason, path)=>path.length === 0 ? capitalize(reason) : path.length === 1 && isWellFormedInteger(path[0]) ? `Item at index ${path[0]} ${reason}` : `${path} ${reason}`;
158
- const compileDefaultProblemWriters = (definitions)=>{
159
- let code;
160
- for(code in definitions){
161
- (_definitions_code = definitions[code]).writeReason ?? (_definitions_code.writeReason = writeDefaultReason);
162
- (_definitions_code1 = definitions[code]).addContext ?? (_definitions_code1.addContext = addDefaultContext);
163
- }
164
- return definitions;
165
- };
166
- export const defaultProblemWriters = compileDefaultProblemWriters({
161
+ const defaultProblemConfig = {
167
162
  divisor: {
168
163
  mustBe: (divisor)=>divisor === 1 ? `an integer` : `a multiple of ${divisor}`
169
164
  },
@@ -179,6 +174,10 @@ export const defaultProblemWriters = compileDefaultProblemWriters({
179
174
  mustBe: ()=>"defined",
180
175
  writeReason: (mustBe)=>writeDefaultReason(mustBe, "")
181
176
  },
177
+ extraneous: {
178
+ mustBe: ()=>"removed",
179
+ writeReason: (mustBe)=>writeDefaultReason(mustBe, "")
180
+ },
182
181
  bound: {
183
182
  mustBe: (bound)=>`${Scanner.comparatorDescriptions[bound.comparator]} ${bound.limit}${bound.units ? ` ${bound.units}` : ""}`,
184
183
  writeReason: (mustBe, data)=>writeDefaultReason(mustBe, `${data.size}`)
@@ -199,10 +198,38 @@ export const defaultProblemWriters = compileDefaultProblemWriters({
199
198
  writeReason: (mustBe, data)=>`${data} must be...\n${mustBe}`,
200
199
  addContext: (reason, path)=>path.length ? `At ${path}, ${reason}` : reason
201
200
  },
202
- mustBe: {
201
+ custom: {
203
202
  mustBe: (mustBe)=>mustBe
204
203
  },
205
204
  cases: {
206
205
  mustBe: (cases)=>describeBranches(cases)
207
206
  }
208
- });
207
+ };
208
+ export const problemCodes = objectKeysOf(defaultProblemConfig);
209
+ const compileDefaultProblemWriters = ()=>{
210
+ const result = {};
211
+ let code;
212
+ for (code of problemCodes){
213
+ result[code] = {
214
+ mustBe: defaultProblemConfig[code].mustBe,
215
+ writeReason: defaultProblemConfig[code].writeReason ?? writeDefaultReason,
216
+ addContext: defaultProblemConfig[code].addContext ?? addDefaultContext
217
+ };
218
+ }
219
+ return result;
220
+ };
221
+ export const defaultProblemWriters = compileDefaultProblemWriters();
222
+ export const compileProblemWriters = (input)=>{
223
+ if (!input) {
224
+ return defaultProblemWriters;
225
+ }
226
+ const result = {};
227
+ for (const code of problemCodes){
228
+ result[code] = {
229
+ mustBe: input[code]?.mustBe ?? defaultProblemConfig[code].mustBe,
230
+ writeReason: input[code]?.writeReason ?? defaultProblemConfig[code].writeReason ?? input.writeReason ?? writeDefaultReason,
231
+ addContext: input[code]?.addContext ?? defaultProblemConfig[code].addContext ?? input.addContext ?? addDefaultContext
232
+ };
233
+ }
234
+ return result;
235
+ };
@@ -44,27 +44,44 @@ import { checkDivisor } from "../nodes/rules/divisor.js";
44
44
  import { checkBound } from "../nodes/rules/range.js";
45
45
  import { checkRegex } from "../nodes/rules/regex.js";
46
46
  import { precedenceMap } from "../nodes/rules/rules.js";
47
+ import { isCheckResult } from "../scopes/type.js";
47
48
  import { domainOf, hasDomain } from "../utils/domains.js";
48
49
  import { throwInternalError } from "../utils/errors.js";
49
50
  import { hasKey, objectKeysOf } from "../utils/generics.js";
50
51
  import { getPath, Path } from "../utils/paths.js";
51
- import { defaultProblemWriters, domainsToDescriptions, objectKindsToDescriptions, Problem, Problems } from "./problems.js";
52
+ import { domainsToDescriptions, objectKindsToDescriptions, Problem, Problems } from "./problems.js";
53
+ const initializeTraversalConfig = ()=>({
54
+ mustBe: [],
55
+ writeReason: [],
56
+ addContext: [],
57
+ keys: []
58
+ });
59
+ const problemWriterKeys = [
60
+ "mustBe",
61
+ "writeReason",
62
+ "addContext"
63
+ ];
52
64
  var _seen = /*#__PURE__*/ new WeakMap();
53
65
  export class TraversalState {
54
- getConfigForProblemCode(code) {
55
- if (!this.configs.length) {
56
- return defaultProblemWriters[code];
57
- }
58
- for(let i = this.configs.length - 1; i >= 0; i--){
59
- if (this.configs[i][code] || this.configs[i]["defaults"]) {
60
- return {
61
- ...defaultProblemWriters[code],
62
- ...this.configs[i]["defaults"],
63
- ...this.configs[i][code]
64
- };
65
- }
66
+ getProblemConfig(code) {
67
+ const result = {};
68
+ for (const k of problemWriterKeys){
69
+ result[k] = this.traversalConfig[k][0] ?? this.rootScope.config.codes[code][k];
70
+ }
71
+ return result;
72
+ }
73
+ getConfigKey(k) {
74
+ return this.traversalConfig[k][0];
75
+ }
76
+ traverseConfig(configEntries, node) {
77
+ for (const entry of configEntries){
78
+ this.traversalConfig[entry[0]].unshift(entry[1]);
66
79
  }
67
- return defaultProblemWriters[code];
80
+ const isValid = traverse(node, this);
81
+ for (const entry1 of configEntries){
82
+ this.traversalConfig[entry1[0]].shift();
83
+ }
84
+ return isValid;
68
85
  }
69
86
  traverseKey(key, node) {
70
87
  const lastData = this.data;
@@ -77,8 +94,8 @@ export class TraversalState {
77
94
  return isValid;
78
95
  }
79
96
  traverseResolution(name) {
80
- const resolution = this.type.meta.scope.resolve(name);
81
- const id = resolution.meta.id;
97
+ const resolution = this.type.scope.resolve(name);
98
+ const id = resolution.qualifiedName;
82
99
  // this assignment helps with narrowing
83
100
  const data = this.data;
84
101
  const isObject = hasDomain(data, "object");
@@ -98,10 +115,10 @@ export class TraversalState {
98
115
  ];
99
116
  }
100
117
  }
101
- const lastResolution = this.type;
118
+ const lastType = this.type;
102
119
  this.type = resolution;
103
120
  const isValid = traverse(resolution.flat, this);
104
- this.type = lastResolution;
121
+ this.type = lastType;
105
122
  if (isObject) {
106
123
  _classPrivateFieldGet(this, _seen)[id].pop();
107
124
  }
@@ -137,10 +154,9 @@ export class TraversalState {
137
154
  this.path = new Path();
138
155
  this.problems = new Problems(this);
139
156
  this.failFast = false;
157
+ this.traversalConfig = initializeTraversalConfig();
140
158
  _classPrivateFieldSet(this, _seen, {});
141
- this.configs = type.meta.scope.config ? [
142
- type.meta.scope.config
143
- ] : [];
159
+ this.rootScope = type.scope;
144
160
  }
145
161
  }
146
162
  export const traverse = (node, state)=>typeof node === "string" ? domainOf(state.data) === node || !state.problems.add("domain", node) : checkEntries(node, state);
@@ -174,6 +190,31 @@ export const checkRequiredProp = (prop, state)=>{
174
190
  });
175
191
  return false;
176
192
  };
193
+ const createPropChecker = (kind)=>(props, state)=>{
194
+ let isValid = true;
195
+ const unseenRequired = {
196
+ ...props.required
197
+ };
198
+ for(const k in state.data){
199
+ if (props.required[k]) {
200
+ isValid || (isValid = state.traverseKey(k, props.required[k]));
201
+ delete unseenRequired[k];
202
+ } else if (props.optional[k]) {
203
+ isValid || (isValid = state.traverseKey(k, props.optional[k]));
204
+ } else if (kind === "distilledProps") {
205
+ delete state.data[k];
206
+ } else {
207
+ state.problems.add("extraneous", state.data[k], {
208
+ path: state.path.concat(k)
209
+ });
210
+ isValid = false;
211
+ }
212
+ if (!isValid && state.failFast) {
213
+ return false;
214
+ }
215
+ }
216
+ return isValid;
217
+ };
177
218
  const entryCheckers = {
178
219
  regex: checkRegex,
179
220
  divisor: checkDivisor,
@@ -225,13 +266,15 @@ const entryCheckers = {
225
266
  },
226
267
  alias: (name, state)=>state.traverseResolution(name),
227
268
  class: checkClass,
228
- narrow: (narrow, state)=>narrow(state.data, state.problems),
229
- config: ({ config , node }, state)=>{
230
- state.configs.push(config);
231
- const result = traverse(node, state);
232
- state.configs.pop();
269
+ narrow: (narrow, state)=>{
270
+ const lastProblemsCount = state.problems.count;
271
+ const result = narrow(state.data, state.problems);
272
+ if (!result && state.problems.count === lastProblemsCount) {
273
+ state.problems.mustBe(narrow.name ? `valid according to ${narrow.name}` : "valid");
274
+ }
233
275
  return result;
234
276
  },
277
+ config: ({ config , node }, state)=>state.traverseConfig(config, node),
235
278
  value: (value, state)=>state.data === value || !state.problems.add("value", value),
236
279
  morph: (morph, state)=>{
237
280
  const out = morph(state.data, state.problems);
@@ -243,7 +286,19 @@ const entryCheckers = {
243
286
  state.problems.addProblem(out);
244
287
  return false;
245
288
  }
289
+ if (isCheckResult(out)) {
290
+ if (out.problems) {
291
+ for (const problem of out.problems){
292
+ state.problems.addProblem(problem);
293
+ }
294
+ return false;
295
+ }
296
+ state.data = out.data;
297
+ return true;
298
+ }
246
299
  state.data = out;
247
300
  return true;
248
- }
301
+ },
302
+ distilledProps: createPropChecker("distilledProps"),
303
+ strictProps: createPropChecker("strictProps")
249
304
  };
@@ -24,8 +24,19 @@ export const hasKey = (o, k)=>{
24
24
  const valueAtKey = o?.[k];
25
25
  return valueAtKey !== undefined && valueAtKey !== null;
26
26
  };
27
+ export const hasSingleKey = (o, k)=>k in o && Object.keys(o).length === 1;
27
28
  export const keyCount = (o)=>Object.keys(o).length;
28
29
  export const hasKeys = (value)=>hasDomain(value, "object") ? Object.keys(value).length !== 0 : false;
30
+ const id = Symbol("id");
31
+ export const nominal = (o, name)=>Object.assign(o, {
32
+ [id]: name
33
+ });
34
+ export const composeNamed = (f, name)=>// define within a key to dynamically assign a name to the function
35
+ ({
36
+ [name]: (...args)=>nominal(f(...args), name)
37
+ })[name];
38
+ export const getNominalId = (data)=>hasDomain(data, "object") && id in data ? data[id] : undefined;
39
+ export const hasNominalId = (data, name)=>getNominalId(data) === name;
29
40
  export const listFrom = (data)=>Array.isArray(data) ? data : [
30
41
  data
31
42
  ];
@@ -1,74 +1,51 @@
1
1
  import { domainOf } from "./domains.js";
2
2
  import { isKeyOf } from "./generics.js";
3
3
  import { tryParseWellFormedBigint, tryParseWellFormedNumber } from "./numericLiterals.js";
4
- export const snapshot = (data, opts = {})=>snapshotRecurse(data, opts, []);
5
- const snapshotRecurse = (v, context, seen)=>{
6
- switch(domainOf(v)){
4
+ export const snapshot = (data, opts = {})=>serializeRecurse(data, opts, []);
5
+ export const stringify = (data, indent)=>{
6
+ switch(domainOf(data)){
7
+ case "object":
8
+ return JSON.stringify(serializeRecurse(data, stringifyOpts, []), null, indent);
9
+ case "symbol":
10
+ return stringifyOpts.onSymbol(data);
11
+ default:
12
+ return serializePrimitive(data);
13
+ }
14
+ };
15
+ const stringifyOpts = {
16
+ onCycle: ()=>"(cycle)",
17
+ onSymbol: (v)=>`(symbol${v.description && ` ${v.description}`})`,
18
+ onFunction: (v)=>`(function${v.name && ` ${v.name}`})`
19
+ };
20
+ const serializeRecurse = (data, context, seen)=>{
21
+ switch(domainOf(data)){
7
22
  case "object":
8
- if (typeof v === "function") {
9
- return stringifyOpts.onFunction(v);
23
+ if (typeof data === "function") {
24
+ return stringifyOpts.onFunction(data);
10
25
  }
11
- if (seen.includes(v)) {
26
+ if (seen.includes(data)) {
12
27
  return "(cycle)";
13
28
  }
14
29
  const nextSeen = [
15
30
  ...seen,
16
- v
31
+ data
17
32
  ];
18
- if (Array.isArray(v)) {
19
- return v.map((item)=>snapshotRecurse(item, context, nextSeen));
33
+ if (Array.isArray(data)) {
34
+ return data.map((item)=>serializeRecurse(item, context, nextSeen));
20
35
  }
21
36
  const result = {};
22
- for(const k in v){
23
- result[k] = snapshotRecurse(v[k], context, nextSeen);
37
+ for(const k in data){
38
+ result[k] = serializeRecurse(data[k], context, nextSeen);
24
39
  }
25
40
  return result;
26
41
  case "symbol":
27
- return stringifyOpts.onSymbol(v);
42
+ return stringifyOpts.onSymbol(data);
28
43
  case "bigint":
29
- return `${v}n`;
44
+ return `${data}n`;
30
45
  case "undefined":
31
46
  return "undefined";
32
47
  default:
33
- return v;
34
- }
35
- };
36
- export const serialize = (data, opts = {}, indent)=>{
37
- const seen = [];
38
- return JSON.stringify(data, (k, v)=>{
39
- switch(domainOf(v)){
40
- case "object":
41
- if (seen.includes(v)) {
42
- return opts.onCycle?.(v);
43
- }
44
- if (typeof v === "function") {
45
- return opts.onFunction?.(v);
46
- }
47
- return v;
48
- case "undefined":
49
- return "undefined";
50
- case "symbol":
51
- return opts.onSymbol?.(v);
52
- case "bigint":
53
- return `${v}n`;
54
- default:
55
- return v;
56
- }
57
- }, indent);
58
- };
59
- const stringifyOpts = {
60
- onCycle: ()=>"(cycle)",
61
- onSymbol: (v)=>`(symbol${v.description && ` ${v.description}`})`,
62
- onFunction: (v)=>`(function${v.name && ` ${v.name}`})`
63
- };
64
- export const stringify = (data, indent)=>{
65
- switch(domainOf(data)){
66
- case "object":
67
- return serialize(data, stringifyOpts, indent);
68
- case "symbol":
69
- return stringifyOpts.onSymbol(data);
70
- default:
71
- return serializePrimitive(data);
48
+ return data;
72
49
  }
73
50
  };
74
51
  export const serializePrimitive = (value)=>typeof value === "string" ? `'${value}'` : typeof value === "bigint" ? `${value}n` : `${value}`;