arktype 0.1.4 → 0.3.0

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 (106) hide show
  1. package/README.md +1 -1
  2. package/dist/api.cjs +4 -3
  3. package/dist/api.d.ts +3 -2
  4. package/dist/api.mjs +2 -1
  5. package/dist/cjs/nodes/{branches.js → branch.js} +56 -10
  6. package/dist/cjs/nodes/compose.js +1 -2
  7. package/dist/cjs/nodes/discriminate.js +7 -13
  8. package/dist/cjs/nodes/node.js +32 -4
  9. package/dist/cjs/nodes/predicate.js +7 -7
  10. package/dist/cjs/nodes/rules/class.js +10 -4
  11. package/dist/cjs/nodes/rules/divisor.js +1 -5
  12. package/dist/cjs/nodes/rules/props.js +75 -25
  13. package/dist/cjs/nodes/rules/range.js +1 -5
  14. package/dist/cjs/nodes/rules/regex.js +2 -44
  15. package/dist/cjs/nodes/rules/rules.js +21 -61
  16. package/dist/cjs/parse/definition.js +2 -2
  17. package/dist/cjs/parse/string/reduce/dynamic.js +1 -2
  18. package/dist/cjs/parse/string/shift/operator/bounds.js +1 -1
  19. package/dist/cjs/parse/string/string.js +2 -2
  20. package/dist/cjs/parse/tuple/keyof.js +37 -18
  21. package/dist/cjs/parse/tuple/morph.js +7 -6
  22. package/dist/cjs/parse/tuple/tuple.js +16 -9
  23. package/dist/cjs/scopes/cache.js +39 -0
  24. package/dist/cjs/scopes/jsObjects.js +133 -0
  25. package/dist/cjs/{main.js → scopes/scope.js} +31 -364
  26. package/dist/cjs/scopes/standard.js +44 -0
  27. package/dist/cjs/scopes/tsKeywords.js +113 -0
  28. package/dist/cjs/scopes/type.js +67 -0
  29. package/dist/cjs/scopes/validation.js +64 -0
  30. package/dist/cjs/traverse/problems.js +55 -95
  31. package/dist/cjs/traverse/traverse.js +127 -134
  32. package/dist/cjs/utils/numericLiterals.js +3 -0
  33. package/dist/cjs/utils/objectKinds.js +1 -2
  34. package/dist/mjs/nodes/{branches.js → branch.js} +45 -2
  35. package/dist/mjs/nodes/compose.js +1 -2
  36. package/dist/mjs/nodes/discriminate.js +6 -12
  37. package/dist/mjs/nodes/node.js +30 -3
  38. package/dist/mjs/nodes/predicate.js +2 -2
  39. package/dist/mjs/nodes/rules/class.js +10 -4
  40. package/dist/mjs/nodes/rules/divisor.js +1 -5
  41. package/dist/mjs/nodes/rules/props.js +74 -27
  42. package/dist/mjs/nodes/rules/range.js +1 -5
  43. package/dist/mjs/nodes/rules/regex.js +1 -43
  44. package/dist/mjs/nodes/rules/rules.js +22 -61
  45. package/dist/mjs/parse/definition.js +1 -1
  46. package/dist/mjs/parse/string/reduce/dynamic.js +2 -3
  47. package/dist/mjs/parse/string/shift/operator/bounds.js +1 -1
  48. package/dist/mjs/parse/string/string.js +2 -2
  49. package/dist/mjs/parse/tuple/keyof.js +38 -19
  50. package/dist/mjs/parse/tuple/morph.js +7 -6
  51. package/dist/mjs/parse/tuple/tuple.js +17 -10
  52. package/dist/mjs/scopes/cache.js +25 -0
  53. package/dist/mjs/scopes/jsObjects.js +119 -0
  54. package/dist/mjs/{main.js → scopes/scope.js} +15 -344
  55. package/dist/mjs/scopes/standard.js +27 -0
  56. package/dist/mjs/scopes/tsKeywords.js +99 -0
  57. package/dist/mjs/scopes/type.js +53 -0
  58. package/dist/mjs/scopes/validation.js +51 -0
  59. package/dist/mjs/traverse/problems.js +55 -95
  60. package/dist/mjs/traverse/traverse.js +129 -135
  61. package/dist/mjs/utils/numericLiterals.js +2 -1
  62. package/dist/mjs/utils/objectKinds.js +1 -1
  63. package/dist/tsconfig.temp.tsbuildinfo +1 -1
  64. package/dist/types/nodes/branch.d.ts +36 -0
  65. package/dist/types/nodes/compose.d.ts +6 -11
  66. package/dist/types/nodes/discriminate.d.ts +1 -1
  67. package/dist/types/nodes/infer.d.ts +16 -15
  68. package/dist/types/nodes/node.d.ts +18 -9
  69. package/dist/types/nodes/predicate.d.ts +18 -57
  70. package/dist/types/nodes/rules/class.d.ts +3 -2
  71. package/dist/types/nodes/rules/divisor.d.ts +2 -1
  72. package/dist/types/nodes/rules/props.d.ts +19 -11
  73. package/dist/types/nodes/rules/range.d.ts +2 -1
  74. package/dist/types/nodes/rules/regex.d.ts +2 -11
  75. package/dist/types/nodes/rules/rules.d.ts +11 -21
  76. package/dist/types/parse/definition.d.ts +1 -1
  77. package/dist/types/parse/string/ast.d.ts +4 -2
  78. package/dist/types/parse/string/reduce/shared.d.ts +1 -1
  79. package/dist/types/parse/string/reduce/static.d.ts +1 -1
  80. package/dist/types/parse/string/shift/operator/bounds.d.ts +1 -1
  81. package/dist/types/parse/string/string.d.ts +1 -1
  82. package/dist/types/parse/tuple/keyof.d.ts +2 -2
  83. package/dist/types/parse/tuple/morph.d.ts +1 -1
  84. package/dist/types/parse/tuple/narrow.d.ts +1 -1
  85. package/dist/types/parse/tuple/tuple.d.ts +1 -1
  86. package/dist/types/scopes/cache.d.ts +14 -0
  87. package/dist/types/scopes/jsObjects.d.ts +36 -0
  88. package/dist/types/scopes/scope.d.ts +76 -0
  89. package/dist/types/scopes/standard.d.ts +280 -0
  90. package/dist/types/scopes/tsKeywords.d.ts +32 -0
  91. package/dist/types/scopes/type.d.ts +47 -0
  92. package/dist/types/scopes/validation.d.ts +21 -0
  93. package/dist/types/traverse/problems.d.ts +35 -53
  94. package/dist/types/traverse/traverse.d.ts +30 -24
  95. package/dist/types/utils/generics.d.ts +0 -1
  96. package/dist/types/utils/numericLiterals.d.ts +2 -0
  97. package/dist/types/utils/objectKinds.d.ts +43 -43
  98. package/package.json +2 -3
  99. package/dist/cjs/nodes/functors.js +0 -35
  100. package/dist/cjs/nodes/rules/objectKind.js +0 -78
  101. package/dist/mjs/nodes/functors.js +0 -27
  102. package/dist/mjs/nodes/rules/objectKind.js +0 -63
  103. package/dist/types/main.d.ts +0 -324
  104. package/dist/types/nodes/branches.d.ts +0 -14
  105. package/dist/types/nodes/functors.d.ts +0 -6
  106. package/dist/types/nodes/rules/objectKind.d.ts +0 -15
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ isLuhnValid: ()=>isLuhnValid,
13
+ validationScope: ()=>validationScope,
14
+ validation: ()=>validation
15
+ });
16
+ const _scopeTs = require("./scope.js");
17
+ const isLuhnValid = (creditCardInput)=>{
18
+ const sanitized = creditCardInput.replace(/[- ]+/g, "");
19
+ let sum = 0;
20
+ let digit;
21
+ let tmpNum;
22
+ let shouldDouble;
23
+ for(let i = sanitized.length - 1; i >= 0; i--){
24
+ digit = sanitized.substring(i, i + 1);
25
+ tmpNum = parseInt(digit, 10);
26
+ if (shouldDouble) {
27
+ tmpNum *= 2;
28
+ if (tmpNum >= 10) {
29
+ sum += tmpNum % 10 + 1;
30
+ } else {
31
+ sum += tmpNum;
32
+ }
33
+ } else {
34
+ sum += tmpNum;
35
+ }
36
+ shouldDouble = !shouldDouble;
37
+ }
38
+ return !!(sum % 10 === 0 ? sanitized : false);
39
+ };
40
+ const validationScope = (0, _scopeTs.scope)({
41
+ // Character sets
42
+ alpha: /^[A-Za-z]*$/,
43
+ alphanumeric: /^[A-Za-z\d]*$/,
44
+ lowercase: /^[a-z]*$/,
45
+ uppercase: /^[A-Z]*$/,
46
+ // https://github.com/validatorjs/validator.js
47
+ creditCard: /^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/,
48
+ // https://www.regular-expressions.info
49
+ email: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
50
+ // https://github.com/validatorjs/validator.js
51
+ uuid: /^[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}$/,
52
+ integer: [
53
+ "node",
54
+ {
55
+ number: {
56
+ divisor: 1
57
+ }
58
+ }
59
+ ]
60
+ }, {
61
+ name: "validation",
62
+ standard: false
63
+ });
64
+ const validation = validationScope.compile();
@@ -15,16 +15,15 @@ _export(exports, {
15
15
  describeDomains: ()=>describeDomains,
16
16
  describeBranches: ()=>describeBranches,
17
17
  DataWrapper: ()=>DataWrapper,
18
- defaultProblemWriters: ()=>defaultProblemWriters,
19
- compileProblemOptions: ()=>compileProblemOptions
18
+ defaultProblemWriters: ()=>defaultProblemWriters
20
19
  });
21
20
  const _scannerTs = require("../parse/string/shift/scanner.js");
22
21
  const _domainsTs = require("../utils/domains.js");
23
- const _genericsTs = require("../utils/generics.js");
22
+ const _numericLiteralsTs = require("../utils/numericLiterals.js");
24
23
  const _objectKindsTs = require("../utils/objectKinds.js");
25
24
  const _pathsTs = require("../utils/paths.js");
26
25
  const _serializeTs = require("../utils/serialize.js");
27
- var _definitions_code, _definitions_code1, _definitions_code2, _clausesByPath, _pathKey;
26
+ var _definitions_code, _definitions_code1;
28
27
  class ArkTypeError extends TypeError {
29
28
  constructor(problems){
30
29
  super(problems.summary);
@@ -36,51 +35,54 @@ class Problem {
36
35
  return this.message;
37
36
  }
38
37
  get message() {
39
- return this.writers.message(this.reason, this.path);
38
+ return this.writers.addContext(this.reason, this.path);
40
39
  }
41
40
  get reason() {
42
- return this.writers.reason(this.mustBe, this.was);
41
+ return this.writers.writeReason(this.mustBe, new DataWrapper(this.data));
43
42
  }
44
43
  get mustBe() {
45
- return this.writers.mustBe(this.rule);
44
+ return this.writers.mustBe(this.source);
46
45
  }
47
- get was() {
48
- return this.writers.was(new DataWrapper(this.data));
49
- }
50
- constructor(code, path, data, rule, writers){
46
+ constructor(code, path, data, source, writers){
51
47
  this.code = code;
52
48
  this.path = path;
53
49
  this.data = data;
54
- this.rule = rule;
50
+ this.source = source;
55
51
  this.writers = writers;
52
+ if (this.code === "multi") {
53
+ this.parts = this.source;
54
+ }
56
55
  }
57
56
  }
58
57
  class ProblemArray extends Array {
59
- add(code, data, input) {
60
- const problem = new Problem(code, // copy the path to avoid future mutations affecting it
61
- _pathsTs.Path.from(this.state.path), data, input, this.state.type.meta.problems[code]);
62
- const pathKey = `${this.state.path}`;
63
- // TODO: Fix multi
64
- // const existing = this.byPath[pathKey]
65
- // if (existing) {
66
- // if (existing.code === "multi") {
67
- // existing.message += `\n• ${problem.message}`
68
- // } else {
69
- // this.byPath[pathKey] = new Problem(
70
- // "multi",
71
- // existing.path,
72
- // `• ${existing.message}\n• ${problem.message}`
73
- // )
74
- // }
75
- // } else {
76
- // }
77
- this.byPath[pathKey] = problem;
78
- this.push(problem);
58
+ add(code, data, source, opts) {
59
+ // copy the path to avoid future mutations affecting it
60
+ const path = opts?.path ?? _pathsTs.Path.from(this.state.path);
61
+ const problem = new Problem(code, path, data, source, this.state.getConfigForProblemCode(code));
62
+ const pathKey = `${path}`;
63
+ const existing = this.byPath[pathKey];
64
+ if (existing) {
65
+ if (existing.parts) {
66
+ existing.parts.push(problem);
67
+ } else {
68
+ const problemIntersection = new Problem("multi", existing.path, data, [
69
+ existing,
70
+ problem
71
+ ], this.state.getConfigForProblemCode("multi"));
72
+ const existingIndex = this.indexOf(existing);
73
+ // If existing is found (which it always should be unless this was externally mutated),
74
+ // replace it with the new problem intersection. In case it isn't for whatever reason,
75
+ // just append the intersection.
76
+ this[existingIndex === -1 ? this.length : existingIndex] = problemIntersection;
77
+ this.byPath[pathKey] = problemIntersection;
78
+ }
79
+ } else {
80
+ this.byPath[pathKey] = problem;
81
+ this.push(problem);
82
+ }
83
+ return false;
79
84
  }
80
85
  get summary() {
81
- if (this.length === 1) {
82
- return this[0].message;
83
- }
84
86
  return this.join("\n");
85
87
  }
86
88
  toString() {
@@ -124,9 +126,6 @@ class DataWrapper {
124
126
  get domain() {
125
127
  return (0, _domainsTs.domainOf)(this.value);
126
128
  }
127
- get objectKind() {
128
- return (0, _objectKindsTs.objectKindOf)(this.value) ?? "non-object";
129
- }
130
129
  get size() {
131
130
  return typeof this.value === "string" || Array.isArray(this.value) ? this.value.length : typeof this.value === "number" ? this.value : 0;
132
131
  }
@@ -140,48 +139,42 @@ class DataWrapper {
140
139
  this.value = value;
141
140
  }
142
141
  }
143
- const writeDefaultWasDescription = (data)=>`${data}`;
144
- const writeDefaultProblemReason = (mustBe, was)=>`must be ${mustBe}${was && ` (was ${was})`}`;
145
- const writeDefaultProblemMessage = (reason, path)=>path.length ? `${path} ${reason}` : capitalize(reason);
142
+ const writeDefaultReason = (mustBe, was)=>`must be ${mustBe}${was && ` (was ${was})`}`;
143
+ const addDefaultContext = (reason, path)=>path.length === 0 ? capitalize(reason) : path.length === 1 && (0, _numericLiteralsTs.isWellFormedInteger)(path[0]) ? `Item at index ${path[0]} ${reason}` : `${path} ${reason}`;
146
144
  const compileDefaultProblemWriters = (definitions)=>{
147
145
  let code;
148
146
  for(code in definitions){
149
- (_definitions_code = definitions[code]).was ?? (_definitions_code.was = writeDefaultWasDescription);
150
- (_definitions_code1 = definitions[code]).reason ?? (_definitions_code1.reason = writeDefaultProblemReason);
151
- (_definitions_code2 = definitions[code]).message ?? (_definitions_code2.message = writeDefaultProblemMessage);
147
+ (_definitions_code = definitions[code]).writeReason ?? (_definitions_code.writeReason = writeDefaultReason);
148
+ (_definitions_code1 = definitions[code]).addContext ?? (_definitions_code1.addContext = addDefaultContext);
152
149
  }
153
150
  return definitions;
154
151
  };
155
152
  const defaultProblemWriters = compileDefaultProblemWriters({
156
153
  divisor: {
157
- mustBe: (divisor)=>divisor === 1 ? `an integer` : `divisible by ${divisor}`
154
+ mustBe: (divisor)=>divisor === 1 ? `an integer` : `a multiple of ${divisor}`
158
155
  },
159
156
  class: {
160
- mustBe: (constructor)=>`an instance of ${constructor.name}`,
161
- was: (data)=>data.className
157
+ mustBe: (expected)=>typeof expected === "string" ? _objectKindsTs.objectKindDescriptions[expected] : `an instance of ${expected.name}`,
158
+ writeReason: (mustBe, data)=>writeDefaultReason(mustBe, data.className)
162
159
  },
163
160
  domain: {
164
161
  mustBe: (domain)=>_domainsTs.domainDescriptions[domain],
165
- was: (data)=>data.domain
162
+ writeReason: (mustBe, data)=>writeDefaultReason(mustBe, data.domain)
166
163
  },
167
164
  domainBranches: {
168
165
  mustBe: (domains)=>describeDomains(domains),
169
- was: (data)=>data.domain
170
- },
171
- objectKind: {
172
- mustBe: (kind)=>_objectKindsTs.objectKindDescriptions[kind],
173
- was: (data)=>data.objectKind
166
+ writeReason: (mustBe, data)=>writeDefaultReason(mustBe, data.domain)
174
167
  },
175
168
  missing: {
176
169
  mustBe: ()=>"defined",
177
- was: ()=>""
170
+ writeReason: (mustBe)=>writeDefaultReason(mustBe, "")
178
171
  },
179
172
  bound: {
180
173
  mustBe: (bound)=>`${_scannerTs.Scanner.comparatorDescriptions[bound.comparator]} ${bound.limit}${bound.units ? ` ${bound.units}` : ""}`,
181
- was: (data)=>`${data.size}`
174
+ writeReason: (mustBe, data)=>writeDefaultReason(mustBe, `${data.size}`)
182
175
  },
183
176
  regex: {
184
- mustBe: (regex)=>`a string matching /${regex.source}/`
177
+ mustBe: (expression)=>`a string matching ${expression}`
185
178
  },
186
179
  value: {
187
180
  mustBe: _serializeTs.stringify
@@ -190,46 +183,13 @@ const defaultProblemWriters = compileDefaultProblemWriters({
190
183
  mustBe: (values)=>describeBranches(values.map(_serializeTs.stringify))
191
184
  },
192
185
  branches: {
193
- mustBe: (branchProblems)=>{
194
- const clausesByPath = {};
195
- for (const problem of branchProblems){
196
- const pathKey = `${problem.path}`;
197
- (_clausesByPath = clausesByPath)[_pathKey = pathKey] ?? (_clausesByPath[_pathKey] = []);
198
- clausesByPath[pathKey].push(problem.mustBe);
199
- }
200
- return describeBranches(Object.entries(clausesByPath).map(([path, clauses])=>`${path} must be ${clauses.length === 1 ? clauses[0] : describeBranches(clauses)}`));
201
- },
202
- reason: (mustBe, data)=>`${mustBe} (was ${data})`,
203
- message: (reason, path)=>path.length ? `At ${path}, ${reason}` : reason
186
+ mustBe: (branchProblems)=>describeBranches(branchProblems.map((problem)=>`${problem.path} must be ${problem.parts ? describeBranches(problem.parts.map((part)=>part.mustBe)) : problem.mustBe}`)),
187
+ writeReason: (mustBe, data)=>`${mustBe} (was ${data})`,
188
+ addContext: (reason, path)=>path.length ? `At ${path}, ${reason}` : reason
204
189
  },
205
190
  multi: {
206
- mustBe: (problems)=>"• " + problems.join("\n• "),
207
- reason: (mustBe)=>mustBe
191
+ mustBe: (problems)=>"• " + problems.map((_)=>_.mustBe).join("\n• "),
192
+ writeReason: (mustBe, data)=>`${data} must be...\n${mustBe}`,
193
+ addContext: (reason, path)=>path.length ? `At ${path}, ${reason}` : reason
208
194
  }
209
195
  });
210
- const codes = (0, _genericsTs.keysOf)(defaultProblemWriters);
211
- const compileProblemOptions = (opts, base = defaultProblemWriters)=>{
212
- if (!opts) {
213
- return base;
214
- }
215
- const { all , ...byCode } = opts;
216
- const result = {};
217
- let code;
218
- if (all) {
219
- for (code of codes){
220
- result[code] = {
221
- ...base[code],
222
- ...all,
223
- ...byCode[code]
224
- };
225
- }
226
- } else {
227
- for (code of codes){
228
- result[code] = byCode[code] ? {
229
- ...base[code],
230
- ...byCode[code]
231
- } : base[code];
232
- }
233
- }
234
- return result;
235
- };
@@ -12,7 +12,7 @@ _export(exports, {
12
12
  TraversalState: ()=>TraversalState,
13
13
  traverse: ()=>traverse,
14
14
  checkEntries: ()=>checkEntries,
15
- checkObjectKind: ()=>checkObjectKind
15
+ checkRequiredProp: ()=>checkRequiredProp
16
16
  });
17
17
  const _discriminateJs = require("../nodes/discriminate.js");
18
18
  const _classJs = require("../nodes/rules/class.js");
@@ -21,9 +21,7 @@ const _rangeJs = require("../nodes/rules/range.js");
21
21
  const _regexJs = require("../nodes/rules/regex.js");
22
22
  const _rulesJs = require("../nodes/rules/rules.js");
23
23
  const _domainsJs = require("../utils/domains.js");
24
- const _errorsJs = require("../utils/errors.js");
25
24
  const _genericsJs = require("../utils/generics.js");
26
- const _objectKindsJs = require("../utils/objectKinds.js");
27
25
  const _pathsJs = require("../utils/paths.js");
28
26
  const _serializeJs = require("../utils/serialize.js");
29
27
  const _problemsJs = require("./problems.js");
@@ -69,9 +67,37 @@ function _classPrivateFieldSet(receiver, privateMap, value) {
69
67
  }
70
68
  var _seen = /*#__PURE__*/ new WeakMap();
71
69
  class TraversalState {
72
- traverseResolution(data, name) {
70
+ getConfigForProblemCode(code) {
71
+ if (!this.configs.length) {
72
+ return _problemsJs.defaultProblemWriters[code];
73
+ }
74
+ for(let i = this.configs.length - 1; i >= 0; i--){
75
+ if (this.configs[i][code] || this.configs[i]["defaults"]) {
76
+ return {
77
+ ..._problemsJs.defaultProblemWriters[code],
78
+ ...this.configs[i]["defaults"],
79
+ ...this.configs[i][code]
80
+ };
81
+ }
82
+ }
83
+ return _problemsJs.defaultProblemWriters[code];
84
+ }
85
+ traverseKey(key, node) {
86
+ const lastData = this.data;
87
+ this.data = this.data[key];
88
+ // TODO: make path externally readonly
89
+ this.path.push(key);
90
+ const isValid = traverse(node, this);
91
+ this.path.pop();
92
+ lastData[key] = this.data;
93
+ this.data = lastData;
94
+ return isValid;
95
+ }
96
+ traverseResolution(name) {
73
97
  const resolution = this.type.meta.scope.resolve(name);
74
98
  const id = resolution.meta.id;
99
+ // this assignment helps with narrowing
100
+ const data = this.data;
75
101
  const isObject = (0, _domainsJs.hasDomain)(data, "object");
76
102
  if (isObject) {
77
103
  if ((0, _genericsJs.hasKey)(_classPrivateFieldGet(this, _seen), id)) {
@@ -79,7 +105,7 @@ class TraversalState {
79
105
  // if data has already been checked by this alias as part of
80
106
  // a resolution higher up on the call stack, it must be valid
81
107
  // or we wouldn't be here
82
- return;
108
+ return true;
83
109
  }
84
110
  _classPrivateFieldGet(this, _seen)[id].push(data);
85
111
  } else {
@@ -88,181 +114,148 @@ class TraversalState {
88
114
  ];
89
115
  }
90
116
  }
91
- // TODO: type not an accurate reflection of context because not always included
92
- const lastType = this.type;
117
+ const lastResolution = this.type;
93
118
  this.type = resolution;
94
- traverse(data, resolution.flat, this);
95
- this.type = lastType;
119
+ const isValid = traverse(resolution.flat, this);
120
+ this.type = lastResolution;
96
121
  if (isObject) {
97
122
  _classPrivateFieldGet(this, _seen)[id].pop();
98
123
  }
124
+ return isValid;
99
125
  }
100
- traverseBranches(data, branches) {
101
- const lastProblems = this.problems;
102
- const lastPath = this.path;
126
+ traverseBranches(branches) {
103
127
  const lastFailFast = this.failFast;
104
128
  this.failFast = true;
105
- const branchProblems = [];
129
+ const lastProblems = this.problems;
130
+ const branchProblems = new _problemsJs.Problems(this);
131
+ this.problems = branchProblems;
132
+ const lastPath = this.path;
133
+ let hasValidBranch = false;
106
134
  for (const branch of branches){
107
- this.problems = new _problemsJs.Problems(this);
108
135
  this.path = new _pathsJs.Path();
109
- checkEntries(data, branch, this);
110
- if (!this.problems.length) {
136
+ if (checkEntries(branch, this)) {
137
+ hasValidBranch = true;
111
138
  break;
112
139
  }
113
- branchProblems.push(this.problems[0]);
114
140
  }
115
- this.failFast = lastFailFast;
116
141
  this.path = lastPath;
117
142
  this.problems = lastProblems;
118
- if (branchProblems.length === branches.length) {
119
- this.problems.add("branches", data, branchProblems);
120
- }
143
+ this.failFast = lastFailFast;
144
+ return hasValidBranch || this.problems.add("branches", this.data, branchProblems);
121
145
  }
122
- constructor(type){
146
+ constructor(data, type){
123
147
  _classPrivateFieldInit(this, _seen, {
124
148
  writable: true,
125
149
  value: void 0
126
150
  });
151
+ this.data = data;
127
152
  this.type = type;
128
153
  this.path = new _pathsJs.Path();
129
154
  this.problems = new _problemsJs.Problems(this);
130
155
  this.failFast = false;
131
156
  _classPrivateFieldSet(this, _seen, {});
157
+ this.configs = type.meta.scope.config ? [
158
+ type.meta.scope.config
159
+ ] : [];
132
160
  }
133
161
  }
134
- const traverse = (data, node, state)=>{
135
- if (typeof node === "string") {
136
- if ((0, _domainsJs.domainOf)(data) !== node) {
137
- return state.problems.add("domain", data, node);
138
- }
139
- return;
140
- }
141
- return checkEntries(data, node, state);
142
- };
143
- const checkEntries = (data, entries, state)=>{
144
- let problemsPrecedence = Number.POSITIVE_INFINITY;
145
- const initialProblemsCount = state.problems.length;
146
- for (const [k, v] of entries){
147
- if (_rulesJs.precedenceMap[k] > problemsPrecedence) {
148
- return;
149
- }
162
+ const traverse = (node, state)=>typeof node === "string" ? (0, _domainsJs.domainOf)(state.data) === node || state.problems.add("domain", state.data, node) : checkEntries(node, state);
163
+ const checkEntries = (entries, state)=>{
164
+ let isValid = true;
165
+ for(let i = 0; i < entries.length; i++){
166
+ const [k, v] = entries[i];
150
167
  if (k === "morph") {
151
168
  if (typeof v === "function") {
152
- return v(data);
153
- }
154
- let out = data;
155
- for (const morph of v){
156
- out = morph(out);
157
- }
158
- return out;
159
- } else {
160
- checkers[k](data, v, state);
161
- if (state.problems.length > initialProblemsCount) {
162
- if (state.failFast) {
163
- return;
169
+ // TODO: allow problem from morph
170
+ state.data = v(state.data);
171
+ } else {
172
+ for (const morph of v){
173
+ state.data = morph(state.data);
164
174
  }
165
- problemsPrecedence = _rulesJs.precedenceMap[k];
166
175
  }
176
+ return true;
167
177
  }
168
- }
169
- return data;
170
- };
171
- const createPropChecker = (propKind)=>(data, props, state)=>{
172
- const rootPath = state.path;
173
- for (const [propKey, propNode] of props){
174
- state.path.push(propKey);
175
- if (!(0, _genericsJs.hasKey)(data, propKey)) {
176
- if (propKind !== "optionalProps") {
177
- state.problems.add("missing", undefined, undefined);
178
- }
179
- } else {
180
- traverse(data[propKey], propNode, state);
178
+ const entryAllowsData = entryCheckers[k](v, state);
179
+ isValid && (isValid = entryAllowsData);
180
+ if (!isValid) {
181
+ if (state.failFast) {
182
+ return false;
183
+ }
184
+ if (i < entries.length - 1 && _rulesJs.precedenceMap[k] < _rulesJs.precedenceMap[entries[i + 1][0]]) {
185
+ // if we've encountered a problem, there is at least one entry
186
+ // remaining, and the next entry is of a higher precedence level
187
+ // than the current entry, return immediately
188
+ return false;
181
189
  }
182
- state.path.pop();
183
- }
184
- state.path = rootPath;
185
- };
186
- const checkRequiredProps = createPropChecker("requiredProps");
187
- const checkOptionalProps = createPropChecker("optionalProps");
188
- const checkObjectKind = (data, rule, state)=>{
189
- const dataObjectKind = (0, _objectKindsJs.objectKindOf)(data);
190
- if (typeof rule === "string") {
191
- if (dataObjectKind !== rule) {
192
- return state.problems.add("objectKind", data, rule);
193
- }
194
- return;
195
- }
196
- if (dataObjectKind !== rule[0]) {
197
- return state.problems.add("objectKind", data, rule[0]);
198
- }
199
- if (dataObjectKind === "Array" && typeof rule[2] === "number") {
200
- const actual = data.length;
201
- const expected = rule[2];
202
- if (expected !== actual) {
203
- return state.problems.add("bound", data, {
204
- comparator: "==",
205
- limit: expected,
206
- units: "items"
207
- });
208
190
  }
209
191
  }
210
- if (dataObjectKind === "Array" || dataObjectKind === "Set") {
211
- let i = 0;
212
- for (const item of data){
213
- state.path.push(`${i}`);
214
- traverse(item, rule[1], state);
215
- state.path.pop();
216
- i++;
217
- }
218
- } else {
219
- return (0, _errorsJs.throwInternalError)(`Unexpected objectKind entry ${(0, _serializeJs.stringify)(rule)}`);
192
+ return isValid;
193
+ };
194
+ const checkRequiredProp = (prop, state)=>{
195
+ if (prop[0] in state.data) {
196
+ return state.traverseKey(prop[0], prop[1]);
220
197
  }
221
- return true;
198
+ return state.problems.add("missing", undefined, undefined, {
199
+ path: state.path.concat(prop[0])
200
+ });
222
201
  };
223
- const checkers = {
202
+ const entryCheckers = {
224
203
  regex: _regexJs.checkRegex,
225
204
  divisor: _divisorJs.checkDivisor,
226
- domains: (data, domains, state)=>{
227
- const entries = domains[(0, _domainsJs.domainOf)(data)];
228
- if (entries) {
229
- checkEntries(data, entries, state);
230
- } else {
231
- state.problems.add("domainBranches", data, (0, _genericsJs.keysOf)(domains));
205
+ domains: (domains, state)=>{
206
+ const entries = domains[(0, _domainsJs.domainOf)(state.data)];
207
+ return entries ? checkEntries(entries, state) : state.problems.add("domainBranches", state.data, (0, _genericsJs.keysOf)(domains));
208
+ },
209
+ // TODO: remove data from problem params
210
+ domain: (domain, state)=>(0, _domainsJs.domainOf)(state.data) === domain || state.problems.add("domain", state.data, domain),
211
+ bound: _rangeJs.checkBound,
212
+ optionalProp: (prop, state)=>{
213
+ if (prop[0] in state.data) {
214
+ return state.traverseKey(prop[0], prop[1]);
232
215
  }
216
+ return true;
233
217
  },
234
- domain: (data, domain, state)=>{
235
- if ((0, _domainsJs.domainOf)(data) !== domain) {
236
- state.problems.add("domain", data, domain);
218
+ // these checks work the same way, the keys are only distinct so that
219
+ // prerequisite props can have a higher precedence
220
+ requiredProp: checkRequiredProp,
221
+ prerequisiteProp: checkRequiredProp,
222
+ indexProp: (node, state)=>{
223
+ if (!Array.isArray(state.data)) {
224
+ return state.problems.add("class", state.data, "Array");
237
225
  }
226
+ let isValid = true;
227
+ for(let i = 0; i < state.data.length; i++){
228
+ isValid && (isValid = state.traverseKey(`${i}`, node));
229
+ if (!isValid && state.failFast) {
230
+ return false;
231
+ }
232
+ }
233
+ return isValid;
238
234
  },
239
- objectKind: checkObjectKind,
240
- bound: _rangeJs.checkBound,
241
- requiredProps: checkRequiredProps,
242
- optionalProps: checkOptionalProps,
243
- branches: (data, branches, state)=>state.traverseBranches(data, branches),
244
- switch: (data, rule, state)=>{
245
- const dataAtPath = (0, _pathsJs.getPath)(data, rule.path);
235
+ branches: (branches, state)=>state.traverseBranches(branches),
236
+ switch: (rule, state)=>{
237
+ const dataAtPath = (0, _pathsJs.getPath)(state.data, rule.path);
246
238
  const caseKey = (0, _discriminateJs.serializeCase)(rule.kind, dataAtPath);
247
239
  if ((0, _genericsJs.hasKey)(rule.cases, caseKey)) {
248
- return checkEntries(data, rule.cases[caseKey], state);
240
+ return checkEntries(rule.cases[caseKey], state);
249
241
  }
250
242
  const caseKeys = (0, _genericsJs.keysOf)(rule.cases);
251
- const lastPath = state.path;
252
- state.path = state.path.concat(rule.path);
253
- if (rule.kind === "value") {
254
- state.problems.add("valueBranches", dataAtPath, caseKeys.map((k)=>(0, _serializeJs.deserializePrimitive)(k)));
255
- } else {
256
- state.problems.add("domainBranches", dataAtPath, caseKeys);
257
- }
258
- state.path = lastPath;
243
+ const missingCasePath = state.path.concat(rule.path);
244
+ return rule.kind === "value" ? state.problems.add("valueBranches", dataAtPath, caseKeys.map((k)=>(0, _serializeJs.deserializePrimitive)(k)), {
245
+ path: missingCasePath
246
+ }) : state.problems.add("domainBranches", dataAtPath, caseKeys, {
247
+ path: missingCasePath
248
+ });
259
249
  },
260
- alias: (data, name, state)=>state.traverseResolution(data, name),
250
+ alias: (name, state)=>state.traverseResolution(name),
261
251
  class: _classJs.checkClass,
262
- narrow: (data, narrow, state)=>narrow(data, state.problems),
263
- value: (data, value, state)=>{
264
- if (data !== value) {
265
- state.problems.add("value", data, value);
266
- }
267
- }
252
+ // TODO: fix
253
+ narrow: (narrow, state)=>narrow(state.data, state.problems),
254
+ config: ({ config , node }, state)=>{
255
+ state.configs.push(config);
256
+ const result = traverse(node, state);
257
+ state.configs.pop();
258
+ return result;
259
+ },
260
+ value: (value, state)=>state.data === value || state.problems.add("value", state.data, value)
268
261
  };
@@ -10,6 +10,8 @@ function _export(target, all) {
10
10
  }
11
11
  _export(exports, {
12
12
  wellFormedIntegerMatcher: ()=>wellFormedIntegerMatcher,
13
+ isWellFormedInteger: ()=>isWellFormedInteger,
14
+ wellFormedNonNegativeIntegerMatcher: ()=>wellFormedNonNegativeIntegerMatcher,
13
15
  writeMalformedNumericLiteralMessage: ()=>writeMalformedNumericLiteralMessage,
14
16
  tryParseWellFormedNumber: ()=>tryParseWellFormedNumber,
15
17
  tryParseWellFormedInteger: ()=>tryParseWellFormedInteger,
@@ -35,6 +37,7 @@ const numberLikeMatcher = /^-?\d*\.?\d*$/;
35
37
  const isNumberLike = (s)=>s.length !== 0 && numberLikeMatcher.test(s);
36
38
  const wellFormedIntegerMatcher = /^(?:0|(?:-?[1-9]\d*))$/;
37
39
  const isWellFormedInteger = (s)=>wellFormedIntegerMatcher.test(s);
40
+ const wellFormedNonNegativeIntegerMatcher = /^(?:0|(?:[1-9]\d*))$/;
38
41
  const integerLikeMatcher = /^-?\d+$/;
39
42
  const isIntegerLike = (s)=>integerLikeMatcher.test(s);
40
43
  const numericLiteralDescriptions = {