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
@@ -9,14 +9,13 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
+ defaultObjectKinds: ()=>defaultObjectKinds,
12
13
  objectKindOf: ()=>objectKindOf,
13
14
  hasObjectKind: ()=>hasObjectKind,
14
15
  isArray: ()=>isArray,
15
16
  objectKindDescriptions: ()=>objectKindDescriptions
16
17
  });
17
18
  const _domainsTs = require("./domains.js");
18
- // Built-in object constructors based on a subset of:
19
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
20
19
  const defaultObjectKinds = {
21
20
  Array,
22
21
  Date,
@@ -1,7 +1,8 @@
1
+ import { writeImplicitNeverMessage } from "../parse/string/ast.js";
1
2
  import { domainOf, hasDomain } from "../utils/domains.js";
2
- import { throwInternalError } from "../utils/errors.js";
3
+ import { throwInternalError, throwParseError } from "../utils/errors.js";
3
4
  import { isDisjoint, isEquality } from "./compose.js";
4
- import { branchIntersection } from "./rules/rules.js";
5
+ import { flattenRules, rulesIntersection } from "./rules/rules.js";
5
6
  export const isBranchComparison = (comparison)=>comparison?.lBranches !== undefined;
6
7
  export const compareBranches = (lConditions, rConditions, state)=>{
7
8
  const result = {
@@ -69,3 +70,45 @@ export const compareBranches = (lConditions, rConditions, state)=>{
69
70
  result.distinctIntersections = pairs.flatMap((pairs)=>pairs.distinct ?? []);
70
71
  return result;
71
72
  };
73
+ export const isMorphBranch = (branch)=>"morph" in branch;
74
+ export const flattenBranch = (branch, ctx)=>{
75
+ if (isMorphBranch(branch)) {
76
+ const result = flattenRules(branch.rules, ctx);
77
+ if (branch.morph) {
78
+ result.push([
79
+ "morph",
80
+ branch.morph
81
+ ]);
82
+ }
83
+ return result;
84
+ }
85
+ return flattenRules(branch, ctx);
86
+ };
87
+ const rulesOf = (branch)=>branch.rules ?? branch;
88
+ export const branchIntersection = (l, r, state)=>{
89
+ const lRules = rulesOf(l);
90
+ const rRules = rulesOf(r);
91
+ const rulesResult = rulesIntersection(lRules, rRules, state);
92
+ if ("morph" in l) {
93
+ if ("morph" in r) {
94
+ if (l.morph === r.morph) {
95
+ return isEquality(rulesResult) || isDisjoint(rulesResult) ? rulesResult : {
96
+ rules: rulesResult,
97
+ morph: l.morph
98
+ };
99
+ }
100
+ return state.lastOperator === "&" ? throwParseError(writeImplicitNeverMessage(state.path, "Intersection", "of morphs")) : {};
101
+ }
102
+ return isDisjoint(rulesResult) ? rulesResult : {
103
+ rules: isEquality(rulesResult) ? l.rules : rulesResult,
104
+ morph: l.morph
105
+ };
106
+ }
107
+ if ("morph" in r) {
108
+ return isDisjoint(rulesResult) ? rulesResult : {
109
+ rules: isEquality(rulesResult) ? r.rules : rulesResult,
110
+ morph: r.morph
111
+ };
112
+ }
113
+ return rulesResult;
114
+ };
@@ -46,9 +46,8 @@ export const composeIntersection = (reducer)=>(l, r, state)=>l === undefined ? r
46
46
  export const throwUndefinedOperandsError = ()=>throwInternalError(`Unexpected operation two undefined operands`);
47
47
  export const disjointDescriptionWriters = {
48
48
  domain: ({ l , r })=>`${l.join(", ")} and ${r.join(", ")}`,
49
- objectKind: ({ l , r })=>`${l} and ${r}`,
50
49
  range: ({ l , r })=>`${stringifyRange(l)} and ${stringifyRange(r)}`,
51
- class: ({ l , r })=>`classes ${l.name} and ${r.name}`,
50
+ class: ({ l , r })=>`classes ${typeof l === "string" ? l : l.name} and ${typeof r === "string" ? r : r.name}`,
52
51
  tupleLength: ({ l , r })=>`tuples of length ${l} and ${r}`,
53
52
  value: ({ l , r })=>`literal values ${serialize(l)} and ${serialize(r)}`,
54
53
  leftAssignability: ({ l , r })=>`literal value ${serialize(l.value)} and ${serialize(r)}`,
@@ -5,9 +5,9 @@ import { hasKey, isKeyOf, keysOf } from "../utils/generics.js";
5
5
  import { isArray, objectKindOf } from "../utils/objectKinds.js";
6
6
  import { Path } from "../utils/paths.js";
7
7
  import { serializePrimitive } from "../utils/serialize.js";
8
+ import { branchIntersection, flattenBranch } from "./branch.js";
8
9
  import { IntersectionState } from "./compose.js";
9
- import { isOptional } from "./rules/props.js";
10
- import { branchIntersection, flattenBranch } from "./rules/rules.js";
10
+ import { mappedKeys, propToNode } from "./rules/props.js";
11
11
  export const flattenBranches = (branches, ctx)=>{
12
12
  const discriminants = calculateDiscriminants(branches, ctx);
13
13
  const indices = branches.map((_, i)=>i);
@@ -22,7 +22,7 @@ const discriminate = (originalBranches, remainingIndices, discriminants, ctx)=>{
22
22
  return [
23
23
  [
24
24
  "branches",
25
- remainingIndices.map((i)=>flattenBranch(originalBranches[i], ctx))
25
+ remainingIndices.map((i)=>branchIncludesMorph(originalBranches[i], ctx.type.meta.scope) ? throwParseError(writeUndiscriminatableMorphUnionMessage(`${ctx.path}`)) : flattenBranch(originalBranches[i], ctx))
26
26
  ]
27
27
  ];
28
28
  }
@@ -53,7 +53,6 @@ const calculateDiscriminants = (branches, ctx)=>{
53
53
  disjointsByPair: {},
54
54
  casesByDisjoint: {}
55
55
  };
56
- const morphBranches = branches.map((branch)=>branchIncludesMorph(branch, ctx.type.meta.scope));
57
56
  for(let lIndex = 0; lIndex < branches.length - 1; lIndex++){
58
57
  for(let rIndex = lIndex + 1; rIndex < branches.length; rIndex++){
59
58
  const pairKey = `${lIndex}/${rIndex}`;
@@ -62,8 +61,7 @@ const calculateDiscriminants = (branches, ctx)=>{
62
61
  const intersectionState = new IntersectionState(ctx.type, "|");
63
62
  branchIntersection(branches[lIndex], branches[rIndex], intersectionState);
64
63
  for(const path in intersectionState.disjoints){
65
- // designed to match objectKind path segments like "${number}"
66
- if (path.includes("${")) {
64
+ if (path.includes(mappedKeys.index)) {
67
65
  continue;
68
66
  }
69
67
  const { l , r , kind } = intersectionState.disjoints[path];
@@ -104,9 +102,6 @@ const calculateDiscriminants = (branches, ctx)=>{
104
102
  cases[rSerialized].push(rIndex);
105
103
  }
106
104
  }
107
- if ((morphBranches[lIndex] === true || morphBranches[rIndex] === true) && pairDisjoints.length === 0) {
108
- return throwParseError(writeUndiscriminatableMorphUnionMessage(`${ctx.path}`));
109
- }
110
105
  }
111
106
  }
112
107
  return discriminants;
@@ -149,8 +144,7 @@ const findBestDiscriminant = (remainingIndices, discriminants)=>{
149
144
  }
150
145
  const defaultCaseKeys = keysOf(defaultCases);
151
146
  if (defaultCaseKeys.length) {
152
- const defaultIndices = defaultCaseKeys.map((k)=>parseInt(k));
153
- filteredCases["default"] = defaultIndices;
147
+ filteredCases["default"] = defaultCaseKeys.map((k)=>parseInt(k));
154
148
  }
155
149
  if (!bestDiscriminant || score > bestDiscriminant.score) {
156
150
  const [path, kind] = parseQualifiedDisjoint(qualifiedDisjoint);
@@ -181,5 +175,5 @@ const caseSerializers = {
181
175
  domain: domainOf
182
176
  };
183
177
  export const serializeCase = (kind, data)=>caseSerializers[kind](data);
184
- const branchIncludesMorph = (branch, $)=>"morph" in branch ? true : "props" in branch ? Object.values(branch.props).some((prop)=>nodeIncludesMorph(isOptional(prop) ? prop[1] : prop, $)) : false;
178
+ const branchIncludesMorph = (branch, $)=>"morph" in branch ? true : "props" in branch ? Object.values(branch.props).some((prop)=>nodeIncludesMorph(propToNode(prop), $)) : false;
185
179
  const nodeIncludesMorph = (node, $)=>typeof node === "string" ? $.resolve(node).meta.includesMorph : Object.values(node).some((predicate)=>predicate === true ? false : isArray(predicate) ? predicate.some((branch)=>branchIncludesMorph(branch, $)) : branchIncludesMorph(predicate, $));
@@ -4,6 +4,7 @@ import { hasKey, hasKeys, keysOf } from "../utils/generics.js";
4
4
  import { Path } from "../utils/paths.js";
5
5
  import { anonymousDisjoint, composeKeyedIntersection, IntersectionState, isDisjoint, isEquality, throwUndefinedOperandsError } from "./compose.js";
6
6
  import { flattenPredicate, isLiteralCondition, predicateIntersection, predicateUnion, resolutionExtendsDomain } from "./predicate.js";
7
+ import { mappedKeys } from "./rules/props.js";
7
8
  export const nodeIntersection = (l, r, state)=>{
8
9
  state.domain = undefined;
9
10
  const lResolution = state.type.meta.scope.resolveNode(l);
@@ -43,18 +44,36 @@ export const union = (l, r, type)=>{
43
44
  }
44
45
  return result;
45
46
  };
46
- const hasImpliedDomain = (flatPredicate)=>flatPredicate[0] && (flatPredicate[0][0] === "objectKind" || flatPredicate[0][0] === "value");
47
+ const hasImpliedDomain = (flatPredicate)=>flatPredicate[0] && (flatPredicate[0][0] === "value" || flatPredicate[0][0] === "class");
47
48
  export const flattenType = (type)=>{
48
49
  const ctx = {
49
50
  type,
50
51
  path: new Path(),
51
52
  lastDomain: "undefined"
52
53
  };
53
- return flattenNode(type.node, ctx);
54
+ return type.meta.config ? [
55
+ [
56
+ "config",
57
+ {
58
+ config: type.meta.config,
59
+ node: flattenNode(type.node, ctx)
60
+ }
61
+ ]
62
+ ] : flattenNode(type.node, ctx);
54
63
  };
55
64
  export const flattenNode = (node, ctx)=>{
56
65
  if (typeof node === "string") {
57
- return ctx.type.meta.scope.resolve(node).flat;
66
+ const resolution = ctx.type.meta.scope.resolve(node);
67
+ const updatedScopeConfig = resolution.meta.scope !== ctx.type.meta.scope && resolution.meta.scope.config;
68
+ return updatedScopeConfig ? [
69
+ [
70
+ "config",
71
+ {
72
+ config: updatedScopeConfig,
73
+ node: resolution.flat
74
+ }
75
+ ]
76
+ ] : resolution.flat;
58
77
  }
59
78
  const domains = keysOf(node);
60
79
  if (domains.length === 1) {
@@ -88,3 +107,11 @@ export const flattenNode = (node, ctx)=>{
88
107
  export const isLiteralNode = (node, domain)=>{
89
108
  return resolutionExtendsDomain(node, domain) && isLiteralCondition(node[domain]);
90
109
  };
110
+ export const arrayOf = (node)=>({
111
+ object: {
112
+ class: "Array",
113
+ props: {
114
+ [mappedKeys.index]: node
115
+ }
116
+ }
117
+ });
@@ -1,9 +1,9 @@
1
1
  import { keysOf, listFrom } from "../utils/generics.js";
2
2
  import { isArray } from "../utils/objectKinds.js";
3
- import { compareBranches, isBranchComparison } from "./branches.js";
3
+ import { branchIntersection, compareBranches, flattenBranch, isBranchComparison } from "./branch.js";
4
4
  import { equality, IntersectionState, isEquality } from "./compose.js";
5
5
  import { flattenBranches } from "./discriminate.js";
6
- import { branchIntersection, flattenBranch } from "./rules/rules.js";
6
+ import "./rules/rules.js";
7
7
  const emptyRulesIfTrue = (predicate)=>predicate === true ? {} : predicate;
8
8
  export const comparePredicates = (l, r, context)=>{
9
9
  if (l === true && r === true) {
@@ -1,7 +1,13 @@
1
+ import { defaultObjectKinds, objectKindOf } from "../../utils/objectKinds.js";
1
2
  import { composeIntersection, equality } from "../compose.js";
2
- export const classIntersection = composeIntersection((l, r, state)=>l === r ? equality() : l instanceof r ? l : r instanceof l ? r : state.addDisjoint("class", l, r));
3
- export const checkClass = (data, expectedClass, state)=>{
4
- if (!(data instanceof expectedClass)) {
5
- state.problems.add("class", data, expectedClass);
3
+ export const classIntersection = composeIntersection((l, r, state)=>{
4
+ const lClass = typeof l === "string" ? defaultObjectKinds[l] : l;
5
+ const rClass = typeof r === "string" ? defaultObjectKinds[r] : r;
6
+ return lClass === rClass ? equality() : lClass instanceof rClass ? l : rClass instanceof lClass ? r : state.addDisjoint("class", l, r);
7
+ });
8
+ export const checkClass = (expectedClass, state)=>{
9
+ if (typeof expectedClass === "string") {
10
+ return objectKindOf(state.data) === expectedClass || state.problems.add("class", state.data, expectedClass);
6
11
  }
12
+ return state.data instanceof expectedClass || state.problems.add("class", state.data, expectedClass);
7
13
  };
@@ -12,8 +12,4 @@ const greatestCommonDivisor = (l, r)=>{
12
12
  }
13
13
  return greatestCommonDivisor;
14
14
  };
15
- export const checkDivisor = (data, divisor, state)=>{
16
- if (data % divisor !== 0) {
17
- state.problems.add("divisor", data, divisor);
18
- }
19
- };
15
+ export const checkDivisor = (divisor, state)=>state.data % divisor === 0 || state.problems.add("divisor", state.data, divisor);
@@ -1,8 +1,50 @@
1
- import { composeIntersection, composeKeyedIntersection, equality, isDisjoint } from "../compose.js";
2
- import { flattenNode, nodeIntersection } from "../node.js";
1
+ import { hasKey } from "../../utils/generics.js";
2
+ import { composeIntersection, composeKeyedIntersection, equality, isDisjoint, isEquality } from "../compose.js";
3
+ import { flattenNode, isLiteralNode, nodeIntersection } from "../node.js";
3
4
  export const isOptional = (prop)=>prop[0] === "?";
4
- const nodeFrom = (prop)=>isOptional(prop) ? prop[1] : prop;
5
- export const propsIntersection = composeIntersection(composeKeyedIntersection((propKey, l, r, context)=>{
5
+ export const isPrerequisite = (prop)=>prop[0] === "!";
6
+ export const mappedKeys = {
7
+ index: "[index]"
8
+ };
9
+ export const propToNode = (prop)=>isOptional(prop) || isPrerequisite(prop) ? prop[1] : prop;
10
+ const getTupleLengthIfPresent = (result)=>{
11
+ if (typeof result.length === "object" && isPrerequisite(result.length) && typeof result.length[1] !== "string" && isLiteralNode(result.length[1], "number")) {
12
+ return result.length[1].number.value;
13
+ }
14
+ };
15
+ export const propsIntersection = composeIntersection((l, r, state)=>{
16
+ const result = propKeysIntersection(l, r, state);
17
+ if (typeof result === "symbol") {
18
+ return result;
19
+ }
20
+ const lengthValue = getTupleLengthIfPresent(result);
21
+ if (lengthValue === undefined || !hasKey(result, mappedKeys.index)) {
22
+ return result;
23
+ }
24
+ // if we are at this point, we have an array with an exact length (i.e.
25
+ // a tuple) and an index signature. Intersection each tuple item with
26
+ // the index signature node and remove the index signature via a new
27
+ // updated result, copied from result to avoid mutating existing references.
28
+ const { [mappedKeys.index]: indexProp , ...updatedResult } = result;
29
+ const indexNode = propToNode(indexProp);
30
+ for(let i = 0; i < lengthValue; i++){
31
+ if (!updatedResult[i]) {
32
+ updatedResult[i] = indexNode;
33
+ continue;
34
+ }
35
+ const existingNodeAtIndex = propToNode(updatedResult[i]);
36
+ state.path.push(`${i}`);
37
+ const updatedResultAtIndex = nodeIntersection(existingNodeAtIndex, indexNode, state);
38
+ state.path.pop();
39
+ if (isDisjoint(updatedResultAtIndex)) {
40
+ return updatedResultAtIndex;
41
+ } else if (!isEquality(updatedResultAtIndex) && updatedResultAtIndex !== existingNodeAtIndex) {
42
+ updatedResult[i] = updatedResultAtIndex;
43
+ }
44
+ }
45
+ return updatedResult;
46
+ });
47
+ const propKeysIntersection = composeKeyedIntersection((propKey, l, r, context)=>{
6
48
  if (l === undefined) {
7
49
  return r === undefined ? equality() : r;
8
50
  }
@@ -10,7 +52,7 @@ export const propsIntersection = composeIntersection(composeKeyedIntersection((p
10
52
  return l;
11
53
  }
12
54
  context.path.push(propKey);
13
- const result = nodeIntersection(nodeFrom(l), nodeFrom(r), context);
55
+ const result = nodeIntersection(propToNode(l), propToNode(r), context);
14
56
  context.path.pop();
15
57
  const resultIsOptional = isOptional(l) && isOptional(r);
16
58
  if (isDisjoint(result) && resultIsOptional) {
@@ -22,36 +64,41 @@ export const propsIntersection = composeIntersection(composeKeyedIntersection((p
22
64
  return result;
23
65
  }, {
24
66
  onEmpty: "bubble"
25
- }));
67
+ });
26
68
  export const flattenProps = (entries, props, ctx)=>{
27
- const requiredProps = [];
28
- const optionalProps = [];
29
69
  for(const k in props){
30
70
  const prop = props[k];
31
71
  ctx.path.push(k);
32
- if (isOptional(prop)) {
33
- optionalProps.push([
34
- k,
35
- flattenNode(prop[1], ctx)
72
+ if (k === mappedKeys.index) {
73
+ entries.push([
74
+ "indexProp",
75
+ flattenNode(propToNode(prop), ctx)
76
+ ]);
77
+ } else if (isOptional(prop)) {
78
+ entries.push([
79
+ "optionalProp",
80
+ [
81
+ k,
82
+ flattenNode(prop[1], ctx)
83
+ ]
84
+ ]);
85
+ } else if (isPrerequisite(prop)) {
86
+ entries.push([
87
+ "prerequisiteProp",
88
+ [
89
+ k,
90
+ flattenNode(prop[1], ctx)
91
+ ]
36
92
  ]);
37
93
  } else {
38
- requiredProps.push([
39
- k,
40
- flattenNode(prop, ctx)
94
+ entries.push([
95
+ "requiredProp",
96
+ [
97
+ k,
98
+ flattenNode(prop, ctx)
99
+ ]
41
100
  ]);
42
101
  }
43
102
  ctx.path.pop();
44
103
  }
45
- if (requiredProps.length) {
46
- entries.push([
47
- "requiredProps",
48
- requiredProps
49
- ]);
50
- }
51
- if (optionalProps.length) {
52
- entries.push([
53
- "optionalProps",
54
- optionalProps
55
- ]);
56
- }
57
104
  };
@@ -74,11 +74,7 @@ export const flattenRange = (entries, range, ctx)=>{
74
74
  ]);
75
75
  }
76
76
  };
77
- export const checkBound = (data, bound, state)=>{
78
- if (!comparatorCheckers[bound.comparator](sizeOf(data), bound.limit)) {
79
- state.problems.add("bound", data, bound);
80
- }
81
- };
77
+ export const checkBound = (bound, state)=>comparatorCheckers[bound.comparator](sizeOf(state.data), bound.limit) || state.problems.add("bound", state.data, bound);
82
78
  const comparatorCheckers = {
83
79
  "<": (size, limit)=>size < limit,
84
80
  ">": (size, limit)=>size > limit,
@@ -1,53 +1,11 @@
1
1
  import { composeIntersection } from "../compose.js";
2
2
  import { collapsibleListUnion } from "./collapsibleSet.js";
3
3
  const regexCache = {};
4
- // Non-trivial expressions should have an explanation or atttribution
5
- export const sources = {
6
- // Character sets
7
- alpha: /^[A-Z]*$/i,
8
- alphanumeric: /^[A-Z\d]*$/i,
9
- lowercase: /^[a-z]*$/,
10
- uppercase: /^[A-Z]*$/,
11
- // https://github.com/validatorjs/validator.js
12
- 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}))$/,
13
- // https://www.regular-expressions.info
14
- email: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
15
- // https://github.com/validatorjs/validator.js
16
- uuid: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i
17
- };
18
4
  export const getRegex = (source)=>{
19
5
  if (!regexCache[source]) {
20
6
  regexCache[source] = new RegExp(source);
21
7
  }
22
8
  return regexCache[source];
23
9
  };
24
- export const checkRegex = (data, regex, state)=>{
25
- if (!regex.test(data)) {
26
- state.problems.add("regex", data, regex);
27
- }
28
- };
10
+ export const checkRegex = (source, state)=>getRegex(source).test(state.data) || state.problems.add("regex", state.data, `/${source}/`);
29
11
  export const regexIntersection = composeIntersection(collapsibleListUnion);
30
- // https://github.com/validatorjs/validator.js
31
- export const isLuhnValid = (creditCardInput)=>{
32
- const sanitized = creditCardInput.replace(/[- ]+/g, "");
33
- let sum = 0;
34
- let digit;
35
- let tmpNum;
36
- let shouldDouble;
37
- for(let i = sanitized.length - 1; i >= 0; i--){
38
- digit = sanitized.substring(i, i + 1);
39
- tmpNum = parseInt(digit, 10);
40
- if (shouldDouble) {
41
- tmpNum *= 2;
42
- if (tmpNum >= 10) {
43
- sum += tmpNum % 10 + 1;
44
- } else {
45
- sum += tmpNum;
46
- }
47
- } else {
48
- sum += tmpNum;
49
- }
50
- shouldDouble = !shouldDouble;
51
- }
52
- return !!(sum % 10 === 0 ? sanitized : false);
53
- };
@@ -1,46 +1,14 @@
1
- import { writeImplicitNeverMessage } from "../../parse/string/ast.js";
2
- import { throwParseError } from "../../utils/errors.js";
3
1
  import { listFrom } from "../../utils/generics.js";
4
- import { composeIntersection, composeKeyedIntersection, equality, isDisjoint, isEquality } from "../compose.js";
2
+ import { composeIntersection, composeKeyedIntersection, equality } from "../compose.js";
5
3
  import { classIntersection } from "./class.js";
6
4
  import { collapsibleListUnion } from "./collapsibleSet.js";
7
5
  import { divisorIntersection } from "./divisor.js";
8
- import { flattenObjectKind, objectKindIntersection } from "./objectKind.js";
9
6
  import { flattenProps, propsIntersection } from "./props.js";
10
7
  import { flattenRange, rangeIntersection } from "./range.js";
11
- import { getRegex, regexIntersection } from "./regex.js";
12
- const rulesOf = (branch)=>branch.input ?? branch;
13
- export const branchIntersection = (l, r, state)=>{
14
- const lRules = rulesOf(l);
15
- const rRules = rulesOf(r);
16
- const rulesResult = rulesIntersection(lRules, rRules, state);
17
- if ("morph" in l) {
18
- if ("morph" in r) {
19
- if (l.morph === r.morph) {
20
- return isEquality(rulesResult) || isDisjoint(rulesResult) ? rulesResult : {
21
- input: rulesResult,
22
- morph: l.morph
23
- };
24
- }
25
- return state.lastOperator === "&" ? throwParseError(writeImplicitNeverMessage(state.path, "Intersection", "of morphs")) : {};
26
- }
27
- return isDisjoint(rulesResult) ? rulesResult : {
28
- input: isEquality(rulesResult) ? l.input : rulesResult,
29
- morph: l.morph
30
- };
31
- }
32
- if ("morph" in r) {
33
- return isDisjoint(rulesResult) ? rulesResult : {
34
- input: isEquality(rulesResult) ? r.input : rulesResult,
35
- morph: r.morph
36
- };
37
- }
38
- return rulesResult;
39
- };
8
+ import { regexIntersection } from "./regex.js";
40
9
  export const rulesIntersection = (l, r, state)=>"value" in l ? "value" in r ? l.value === r.value ? equality() : state.addDisjoint("value", l.value, r.value) : literalSatisfiesRules(l.value, r, state) ? l : state.addDisjoint("leftAssignability", l, r) : "value" in r ? literalSatisfiesRules(r.value, l, state) ? r : state.addDisjoint("rightAssignability", l, r) : narrowableRulesIntersection(l, r, state);
41
10
  const narrowIntersection = composeIntersection(collapsibleListUnion);
42
11
  export const narrowableRulesIntersection = composeKeyedIntersection({
43
- objectKind: objectKindIntersection,
44
12
  divisor: divisorIntersection,
45
13
  regex: regexIntersection,
46
14
  props: propsIntersection,
@@ -50,13 +18,20 @@ export const narrowableRulesIntersection = composeKeyedIntersection({
50
18
  }, {
51
19
  onEmpty: "bubble"
52
20
  });
21
+ export const flattenRules = (rules, ctx)=>{
22
+ const entries = [];
23
+ let k;
24
+ for(k in rules){
25
+ ruleFlatteners[k](entries, rules[k], ctx);
26
+ }
27
+ return entries.sort((l, r)=>precedenceMap[l[0]] - precedenceMap[r[0]]);
28
+ };
53
29
  const ruleFlatteners = {
54
- objectKind: flattenObjectKind,
55
30
  regex: (entries, rule)=>{
56
31
  for (const source of listFrom(rule)){
57
32
  entries.push([
58
33
  "regex",
59
- getRegex(source)
34
+ source
60
35
  ]);
61
36
  }
62
37
  },
@@ -91,44 +66,30 @@ const ruleFlatteners = {
91
66
  };
92
67
  export const precedenceMap = {
93
68
  // Critical: No other checks are performed if these fail
69
+ config: 0,
94
70
  domain: 0,
95
71
  value: 0,
96
72
  domains: 0,
97
73
  branches: 0,
98
- objectKind: 0,
99
74
  switch: 0,
100
75
  alias: 0,
76
+ class: 0,
101
77
  // Shallow: All shallow checks will be performed even if one or more fail
102
- class: 1,
103
78
  regex: 1,
104
79
  divisor: 1,
105
80
  bound: 1,
81
+ // Prerequisite: These are deep checks with special priority, e.g. the
82
+ // length of a tuple, which causes other deep props not to be checked if it
83
+ // is invalid
84
+ prerequisiteProp: 2,
106
85
  // Deep: Performed if all shallow checks pass, even if one or more deep checks fail
107
- requiredProps: 2,
108
- optionalProps: 2,
86
+ requiredProp: 3,
87
+ optionalProp: 3,
88
+ indexProp: 3,
109
89
  // Narrow: Only performed if all shallow and deep checks pass
110
- narrow: 3,
90
+ narrow: 4,
111
91
  // Morph: Only performed if all validation passes
112
- morph: 4
113
- };
114
- export const flattenBranch = (branch, ctx)=>{
115
- if ("morph" in branch) {
116
- const result = flattenRules(branch.input, ctx);
117
- result.push([
118
- "morph",
119
- branch.morph
120
- ]);
121
- return result;
122
- }
123
- return flattenRules(branch, ctx);
124
- };
125
- const flattenRules = (rules, ctx)=>{
126
- const entries = [];
127
- let k;
128
- for(k in rules){
129
- ruleFlatteners[k](entries, rules[k], ctx);
130
- }
131
- return entries.sort((l, r)=>precedenceMap[l[0]] - precedenceMap[r[0]]);
92
+ morph: 5
132
93
  };
133
94
  export const literalSatisfiesRules = (data, rules, state)=>!state.type.meta.scope.type([
134
95
  "node",
@@ -1,4 +1,4 @@
1
- import { isType } from "../main.js";
1
+ import { isType } from "../scopes/type.js";
2
2
  import { domainOf } from "../utils/domains.js";
3
3
  import { throwParseError } from "../utils/errors.js";
4
4
  import { objectKindOf } from "../utils/objectKinds.js";
@@ -1,5 +1,4 @@
1
- import { functors } from "../../../nodes/functors.js";
2
- import { intersection, isLiteralNode, union } from "../../../nodes/node.js";
1
+ import { arrayOf, intersection, isLiteralNode, union } from "../../../nodes/node.js";
3
2
  import { minComparators } from "../../../nodes/rules/range.js";
4
3
  import { throwInternalError, throwParseError } from "../../../utils/errors.js";
5
4
  import { isKeyOf } from "../../../utils/generics.js";
@@ -52,7 +51,7 @@ export class DynamicState {
52
51
  this.root = node;
53
52
  }
54
53
  rootToArray() {
55
- this.root = functors.Array(this.ejectRoot());
54
+ this.root = arrayOf(this.ejectRoot());
56
55
  }
57
56
  intersect(node) {
58
57
  this.root = intersection(this.ejectRoot(), node, this.ctx.type);
@@ -54,7 +54,7 @@ const distributeRange = (range, s)=>{
54
54
  if (resolution.object === true) {
55
55
  return false;
56
56
  }
57
- return listFrom(resolution.object).every((branch)=>hasKey(branch, "objectKind") && (branch.objectKind === "Array" || branch.objectKind[0] === "Array"));
57
+ return listFrom(resolution.object).every((branch)=>hasKey(branch, "class") && branch.class === "Array");
58
58
  default:
59
59
  return false;
60
60
  }
@@ -1,4 +1,4 @@
1
- import { functors } from "../../nodes/functors.js";
1
+ import { arrayOf } from "../../nodes/node.js";
2
2
  import { DynamicState } from "./reduce/dynamic.js";
3
3
  import { parseOperand } from "./shift/operand/operand.js";
4
4
  import { parseOperator } from "./shift/operator/operator.js";
@@ -10,7 +10,7 @@ export const maybeNaiveParse = (def, ctx)=>{
10
10
  if (def.endsWith("[]")) {
11
11
  const elementDef = def.slice(0, -2);
12
12
  if (ctx.type.meta.scope.addReferenceIfResolvable(def, ctx)) {
13
- return functors.Array(elementDef);
13
+ return arrayOf(elementDef);
14
14
  }
15
15
  }
16
16
  };