arktype 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +101 -0
  3. package/dist/api.cjs +15 -0
  4. package/dist/api.d.ts +2 -0
  5. package/dist/api.mjs +1 -0
  6. package/dist/cjs/main.js +462 -0
  7. package/dist/cjs/nodes/branches.js +85 -0
  8. package/dist/cjs/nodes/compose.js +140 -0
  9. package/dist/cjs/nodes/discriminate.js +199 -0
  10. package/dist/cjs/nodes/functors.js +35 -0
  11. package/dist/cjs/nodes/infer.js +4 -0
  12. package/dist/cjs/nodes/node.js +108 -0
  13. package/dist/cjs/nodes/predicate.js +87 -0
  14. package/dist/cjs/nodes/rules/class.js +21 -0
  15. package/dist/cjs/nodes/rules/collapsibleSet.js +49 -0
  16. package/dist/cjs/nodes/rules/divisor.js +33 -0
  17. package/dist/cjs/nodes/rules/props.js +72 -0
  18. package/dist/cjs/nodes/rules/range.js +109 -0
  19. package/dist/cjs/nodes/rules/regex.js +68 -0
  20. package/dist/cjs/nodes/rules/rules.js +156 -0
  21. package/dist/cjs/nodes/rules/subdomain.js +78 -0
  22. package/dist/cjs/package.json +3 -0
  23. package/dist/cjs/parse/definition.js +33 -0
  24. package/dist/cjs/parse/record.js +37 -0
  25. package/dist/cjs/parse/string/ast.js +36 -0
  26. package/dist/cjs/parse/string/reduce/dynamic.js +150 -0
  27. package/dist/cjs/parse/string/reduce/shared.js +23 -0
  28. package/dist/cjs/parse/string/reduce/static.js +4 -0
  29. package/dist/cjs/parse/string/shift/operand/enclosed.js +54 -0
  30. package/dist/cjs/parse/string/shift/operand/operand.js +11 -0
  31. package/dist/cjs/parse/string/shift/operand/unenclosed.js +53 -0
  32. package/dist/cjs/parse/string/shift/operator/bounds.js +87 -0
  33. package/dist/cjs/parse/string/shift/operator/divisor.js +35 -0
  34. package/dist/cjs/parse/string/shift/operator/operator.js +26 -0
  35. package/dist/cjs/parse/string/shift/scanner.js +99 -0
  36. package/dist/cjs/parse/string/string.js +43 -0
  37. package/dist/cjs/parse/tuple/keyof.js +46 -0
  38. package/dist/cjs/parse/tuple/morph.js +56 -0
  39. package/dist/cjs/parse/tuple/narrow.js +15 -0
  40. package/dist/cjs/parse/tuple/tuple.js +85 -0
  41. package/dist/cjs/parse/tuple/utils.js +48 -0
  42. package/dist/cjs/traverse/problems.js +249 -0
  43. package/dist/cjs/traverse/traverse.js +268 -0
  44. package/dist/cjs/utils/chainableNoOpProxy.js +23 -0
  45. package/dist/cjs/utils/domains.js +67 -0
  46. package/dist/cjs/utils/errors.js +26 -0
  47. package/dist/cjs/utils/freeze.js +16 -0
  48. package/dist/cjs/utils/generics.js +36 -0
  49. package/dist/cjs/utils/numericLiterals.js +84 -0
  50. package/dist/cjs/utils/paths.js +32 -0
  51. package/dist/cjs/utils/serialize.js +98 -0
  52. package/dist/cjs/utils/unionToTuple.js +4 -0
  53. package/dist/mjs/main.js +442 -0
  54. package/dist/mjs/nodes/branches.js +71 -0
  55. package/dist/mjs/nodes/compose.js +118 -0
  56. package/dist/mjs/nodes/discriminate.js +184 -0
  57. package/dist/mjs/nodes/functors.js +27 -0
  58. package/dist/mjs/nodes/infer.js +1 -0
  59. package/dist/mjs/nodes/node.js +90 -0
  60. package/dist/mjs/nodes/predicate.js +69 -0
  61. package/dist/mjs/nodes/rules/class.js +7 -0
  62. package/dist/mjs/nodes/rules/collapsibleSet.js +35 -0
  63. package/dist/mjs/nodes/rules/divisor.js +19 -0
  64. package/dist/mjs/nodes/rules/props.js +57 -0
  65. package/dist/mjs/nodes/rules/range.js +90 -0
  66. package/dist/mjs/nodes/rules/regex.js +53 -0
  67. package/dist/mjs/nodes/rules/rules.js +138 -0
  68. package/dist/mjs/nodes/rules/subdomain.js +63 -0
  69. package/dist/mjs/package.json +3 -0
  70. package/dist/mjs/parse/definition.js +17 -0
  71. package/dist/mjs/parse/record.js +29 -0
  72. package/dist/mjs/parse/string/ast.js +19 -0
  73. package/dist/mjs/parse/string/reduce/dynamic.js +142 -0
  74. package/dist/mjs/parse/string/reduce/shared.js +6 -0
  75. package/dist/mjs/parse/string/reduce/static.js +1 -0
  76. package/dist/mjs/parse/string/shift/operand/enclosed.js +39 -0
  77. package/dist/mjs/parse/string/shift/operand/operand.js +3 -0
  78. package/dist/mjs/parse/string/shift/operand/unenclosed.js +36 -0
  79. package/dist/mjs/parse/string/shift/operator/bounds.js +70 -0
  80. package/dist/mjs/parse/string/shift/operator/divisor.js +21 -0
  81. package/dist/mjs/parse/string/shift/operator/operator.js +11 -0
  82. package/dist/mjs/parse/string/shift/scanner.js +91 -0
  83. package/dist/mjs/parse/string/string.js +28 -0
  84. package/dist/mjs/parse/tuple/keyof.js +38 -0
  85. package/dist/mjs/parse/tuple/morph.js +42 -0
  86. package/dist/mjs/parse/tuple/narrow.js +7 -0
  87. package/dist/mjs/parse/tuple/tuple.js +71 -0
  88. package/dist/mjs/parse/tuple/utils.js +34 -0
  89. package/dist/mjs/traverse/problems.js +229 -0
  90. package/dist/mjs/traverse/traverse.js +252 -0
  91. package/dist/mjs/utils/chainableNoOpProxy.js +15 -0
  92. package/dist/mjs/utils/domains.js +48 -0
  93. package/dist/mjs/utils/errors.js +10 -0
  94. package/dist/mjs/utils/freeze.js +8 -0
  95. package/dist/mjs/utils/generics.js +15 -0
  96. package/dist/mjs/utils/numericLiterals.js +71 -0
  97. package/dist/mjs/utils/paths.js +18 -0
  98. package/dist/mjs/utils/serialize.js +81 -0
  99. package/dist/mjs/utils/unionToTuple.js +1 -0
  100. package/dist/tsconfig.temp.tsbuildinfo +1 -0
  101. package/dist/types/main.d.ts +257 -0
  102. package/dist/types/nodes/branches.d.ts +14 -0
  103. package/dist/types/nodes/compose.d.ts +92 -0
  104. package/dist/types/nodes/discriminate.d.ts +27 -0
  105. package/dist/types/nodes/functors.d.ts +6 -0
  106. package/dist/types/nodes/infer.d.ts +35 -0
  107. package/dist/types/nodes/node.d.ts +51 -0
  108. package/dist/types/nodes/predicate.d.ts +88 -0
  109. package/dist/types/nodes/rules/class.d.ts +3 -0
  110. package/dist/types/nodes/rules/collapsibleSet.d.ts +4 -0
  111. package/dist/types/nodes/rules/divisor.d.ts +2 -0
  112. package/dist/types/nodes/rules/props.d.ts +20 -0
  113. package/dist/types/nodes/rules/range.d.ts +33 -0
  114. package/dist/types/nodes/rules/regex.d.ts +14 -0
  115. package/dist/types/nodes/rules/rules.d.ts +44 -0
  116. package/dist/types/nodes/rules/subdomain.d.ts +15 -0
  117. package/dist/types/parse/definition.d.ts +29 -0
  118. package/dist/types/parse/record.d.ts +24 -0
  119. package/dist/types/parse/string/ast.d.ts +42 -0
  120. package/dist/types/parse/string/reduce/dynamic.d.ts +34 -0
  121. package/dist/types/parse/string/reduce/shared.d.ts +24 -0
  122. package/dist/types/parse/string/reduce/static.d.ts +115 -0
  123. package/dist/types/parse/string/shift/operand/enclosed.d.ts +28 -0
  124. package/dist/types/parse/string/shift/operand/operand.d.ts +9 -0
  125. package/dist/types/parse/string/shift/operand/unenclosed.d.ts +18 -0
  126. package/dist/types/parse/string/shift/operator/bounds.d.ts +20 -0
  127. package/dist/types/parse/string/shift/operator/divisor.d.ts +9 -0
  128. package/dist/types/parse/string/shift/operator/operator.d.ts +13 -0
  129. package/dist/types/parse/string/shift/scanner.d.ts +89 -0
  130. package/dist/types/parse/string/string.d.ts +27 -0
  131. package/dist/types/parse/tuple/keyof.d.ts +2 -0
  132. package/dist/types/parse/tuple/morph.d.ts +15 -0
  133. package/dist/types/parse/tuple/narrow.d.ts +13 -0
  134. package/dist/types/parse/tuple/tuple.d.ts +37 -0
  135. package/dist/types/parse/tuple/utils.d.ts +19 -0
  136. package/dist/types/traverse/problems.d.ts +123 -0
  137. package/dist/types/traverse/traverse.d.ts +48 -0
  138. package/dist/types/utils/chainableNoOpProxy.d.ts +14 -0
  139. package/dist/types/utils/domains.d.ts +58 -0
  140. package/dist/types/utils/errors.d.ts +6 -0
  141. package/dist/types/utils/freeze.d.ts +2 -0
  142. package/dist/types/utils/generics.d.ts +118 -0
  143. package/dist/types/utils/numericLiterals.d.ts +28 -0
  144. package/dist/types/utils/paths.d.ts +7 -0
  145. package/dist/types/utils/serialize.d.ts +38 -0
  146. package/dist/types/utils/unionToTuple.d.ts +11 -0
  147. package/package.json +102 -2
@@ -0,0 +1,184 @@
1
+ import { writeUndiscriminatableMorphUnionMessage } from "../parse/string/ast.js";
2
+ import { domainOf, hasSubdomain, subdomainOf } from "../utils/domains.js";
3
+ import { throwParseError } from "../utils/errors.js";
4
+ import { hasKey, isKeyOf, keysOf } from "../utils/generics.js";
5
+ import { Path } from "../utils/paths.js";
6
+ import { serializePrimitive } from "../utils/serialize.js";
7
+ import { IntersectionState } from "./compose.js";
8
+ import { isOptional } from "./rules/props.js";
9
+ import { branchIntersection, flattenBranch } from "./rules/rules.js";
10
+ export const flattenBranches = (branches, ctx)=>{
11
+ const discriminants = calculateDiscriminants(branches, ctx);
12
+ const indices = branches.map((_, i)=>i);
13
+ return discriminate(branches, indices, discriminants, ctx);
14
+ };
15
+ const discriminate = (originalBranches, remainingIndices, discriminants, ctx)=>{
16
+ if (remainingIndices.length === 1) {
17
+ return flattenBranch(originalBranches[remainingIndices[0]], ctx);
18
+ }
19
+ const bestDiscriminant = findBestDiscriminant(remainingIndices, discriminants);
20
+ if (!bestDiscriminant) {
21
+ return [
22
+ [
23
+ "branches",
24
+ remainingIndices.map((i)=>flattenBranch(originalBranches[i], ctx))
25
+ ]
26
+ ];
27
+ }
28
+ const cases = {};
29
+ let caseKey;
30
+ for(caseKey in bestDiscriminant.indexCases){
31
+ const nextIndices = bestDiscriminant.indexCases[caseKey];
32
+ cases[caseKey] = discriminate(originalBranches, nextIndices, discriminants, ctx);
33
+ }
34
+ return [
35
+ [
36
+ "switch",
37
+ {
38
+ path: bestDiscriminant.path,
39
+ kind: bestDiscriminant.kind,
40
+ cases
41
+ }
42
+ ]
43
+ ];
44
+ };
45
+ const discriminantKinds = {
46
+ domain: true,
47
+ subdomain: true,
48
+ value: true
49
+ };
50
+ const calculateDiscriminants = (branches, ctx)=>{
51
+ const discriminants = {
52
+ disjointsByPair: {},
53
+ casesByDisjoint: {}
54
+ };
55
+ const morphBranches = branches.map((branch)=>branchIncludesMorph(branch, ctx.type.meta.scope));
56
+ for(let lIndex = 0; lIndex < branches.length - 1; lIndex++){
57
+ for(let rIndex = lIndex + 1; rIndex < branches.length; rIndex++){
58
+ const pairKey = `${lIndex}/${rIndex}`;
59
+ const pairDisjoints = [];
60
+ discriminants.disjointsByPair[pairKey] = pairDisjoints;
61
+ const intersectionState = new IntersectionState(ctx.type, "|");
62
+ branchIntersection(branches[lIndex], branches[rIndex], intersectionState);
63
+ for(const path in intersectionState.disjoints){
64
+ // designed to match subdomain path segments like "${number}"
65
+ if (path.includes("${")) {
66
+ continue;
67
+ }
68
+ const { l , r , kind } = intersectionState.disjoints[path];
69
+ if (!isKeyOf(kind, discriminantKinds)) {
70
+ continue;
71
+ }
72
+ const lSerialized = serializeIfAllowed(kind, l);
73
+ const rSerialized = serializeIfAllowed(kind, r);
74
+ if (lSerialized === undefined || rSerialized === undefined) {
75
+ continue;
76
+ }
77
+ const qualifiedDisjoint = path === "/" ? kind : `${path}/${kind}`;
78
+ pairDisjoints.push(qualifiedDisjoint);
79
+ if (!discriminants.casesByDisjoint[qualifiedDisjoint]) {
80
+ discriminants.casesByDisjoint[qualifiedDisjoint] = {
81
+ [lSerialized]: [
82
+ lIndex
83
+ ],
84
+ [rSerialized]: [
85
+ rIndex
86
+ ]
87
+ };
88
+ continue;
89
+ }
90
+ const cases = discriminants.casesByDisjoint[qualifiedDisjoint];
91
+ if (!hasKey(cases, lSerialized)) {
92
+ cases[lSerialized] = [
93
+ lIndex
94
+ ];
95
+ } else if (!cases[lSerialized].includes(lIndex)) {
96
+ cases[lSerialized].push(lIndex);
97
+ }
98
+ if (!hasKey(cases, rSerialized)) {
99
+ cases[rSerialized] = [
100
+ rIndex
101
+ ];
102
+ } else if (!cases[rSerialized].includes(rIndex)) {
103
+ cases[rSerialized].push(rIndex);
104
+ }
105
+ }
106
+ if ((morphBranches[lIndex] === true || morphBranches[rIndex] === true) && pairDisjoints.length === 0) {
107
+ return throwParseError(writeUndiscriminatableMorphUnionMessage(`${ctx.path}`));
108
+ }
109
+ }
110
+ }
111
+ return discriminants;
112
+ };
113
+ const parseQualifiedDisjoint = (qualifiedDisjoint)=>{
114
+ const path = Path.fromString(qualifiedDisjoint);
115
+ return [
116
+ path,
117
+ path.pop()
118
+ ];
119
+ };
120
+ const findBestDiscriminant = (remainingIndices, discriminants)=>{
121
+ let bestDiscriminant;
122
+ for(let i = 0; i < remainingIndices.length - 1; i++){
123
+ const lIndex = remainingIndices[i];
124
+ for(let j = i + 1; j < remainingIndices.length; j++){
125
+ const rIndex = remainingIndices[j];
126
+ const candidates = discriminants.disjointsByPair[`${lIndex}/${rIndex}`];
127
+ for (const qualifiedDisjoint of candidates){
128
+ const indexCases = discriminants.casesByDisjoint[qualifiedDisjoint];
129
+ const filteredCases = {};
130
+ const defaultCases = [
131
+ ...remainingIndices
132
+ ];
133
+ let score = 0;
134
+ let caseKey;
135
+ for(caseKey in indexCases){
136
+ const filteredIndices = indexCases[caseKey].filter((i)=>{
137
+ const remainingIndex = remainingIndices.indexOf(i);
138
+ if (remainingIndex !== -1) {
139
+ delete defaultCases[remainingIndex];
140
+ return true;
141
+ }
142
+ });
143
+ if (filteredIndices.length === 0) {
144
+ continue;
145
+ }
146
+ filteredCases[caseKey] = filteredIndices;
147
+ score++;
148
+ }
149
+ const defaultCaseKeys = keysOf(defaultCases);
150
+ if (defaultCaseKeys.length) {
151
+ const defaultIndices = defaultCaseKeys.map((k)=>parseInt(k));
152
+ filteredCases["default"] = defaultIndices;
153
+ }
154
+ if (!bestDiscriminant || score > bestDiscriminant.score) {
155
+ const [path, kind] = parseQualifiedDisjoint(qualifiedDisjoint);
156
+ bestDiscriminant = {
157
+ path,
158
+ kind,
159
+ indexCases: filteredCases,
160
+ score
161
+ };
162
+ if (score === remainingIndices.length) {
163
+ // if we find a candidate that discriminates all branches, return early
164
+ return bestDiscriminant;
165
+ }
166
+ }
167
+ }
168
+ }
169
+ }
170
+ return bestDiscriminant;
171
+ };
172
+ export const serializeIfAllowed = (kind, data)=>kind === "value" ? serializeIfPrimitive(data) : `${data}`;
173
+ const serializeIfPrimitive = (data)=>{
174
+ const domain = domainOf(data);
175
+ return domain === "object" || domain === "symbol" ? undefined : serializePrimitive(data);
176
+ };
177
+ const caseSerializers = {
178
+ value: (data)=>serializeIfPrimitive(data) ?? "default",
179
+ subdomain: subdomainOf,
180
+ domain: domainOf
181
+ };
182
+ export const serializeCase = (kind, data)=>caseSerializers[kind](data);
183
+ const branchIncludesMorph = (branch, $)=>"morph" in branch ? true : "props" in branch ? Object.values(branch.props).some((prop)=>nodeIncludesMorph(isOptional(prop) ? prop[1] : prop, $)) : false;
184
+ const nodeIncludesMorph = (node, $)=>typeof node === "string" ? $.resolve(node).meta.includesMorph : Object.values(node).some((predicate)=>predicate === true ? false : hasSubdomain(predicate, "Array") ? predicate.some((branch)=>branchIncludesMorph(branch, $)) : branchIncludesMorph(predicate, $));
@@ -0,0 +1,27 @@
1
+ export const functors = {
2
+ Array: (node)=>({
3
+ object: {
4
+ subdomain: [
5
+ "Array",
6
+ node
7
+ ]
8
+ }
9
+ }),
10
+ Set: (node)=>({
11
+ object: {
12
+ subdomain: [
13
+ "Set",
14
+ node
15
+ ]
16
+ }
17
+ }),
18
+ Map: (k, v)=>({
19
+ object: {
20
+ subdomain: [
21
+ "Map",
22
+ k,
23
+ v
24
+ ]
25
+ }
26
+ })
27
+ };
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,90 @@
1
+ import { compileDisjointReasonsMessage } from "../parse/string/ast.js";
2
+ import { throwParseError } from "../utils/errors.js";
3
+ import { hasKey, hasKeys, keysOf } from "../utils/generics.js";
4
+ import { Path } from "../utils/paths.js";
5
+ import { anonymousDisjoint, composeKeyedIntersection, IntersectionState, isDisjoint, isEquality, throwUndefinedOperandsError } from "./compose.js";
6
+ import { flattenPredicate, isLiteralCondition, predicateIntersection, predicateUnion, resolutionExtendsDomain } from "./predicate.js";
7
+ export const nodeIntersection = (l, r, state)=>{
8
+ state.domain = undefined;
9
+ const lResolution = state.type.meta.scope.resolveNode(l);
10
+ const rResolution = state.type.meta.scope.resolveNode(r);
11
+ const result = resolutionIntersection(lResolution, rResolution, state);
12
+ if (typeof result === "object" && !hasKeys(result)) {
13
+ return hasKeys(state.disjoints) ? anonymousDisjoint() : state.addDisjoint("domain", keysOf(lResolution), keysOf(rResolution));
14
+ }
15
+ return result === lResolution ? l : result === rResolution ? r : result;
16
+ };
17
+ const resolutionIntersection = composeKeyedIntersection((domain, l, r, context)=>{
18
+ if (l === undefined) {
19
+ return r === undefined ? throwUndefinedOperandsError() : undefined;
20
+ }
21
+ if (r === undefined) {
22
+ return undefined;
23
+ }
24
+ return predicateIntersection(domain, l, r, context);
25
+ }, {
26
+ onEmpty: "omit"
27
+ });
28
+ export const intersection = (l, r, type)=>{
29
+ const state = new IntersectionState(type, "&");
30
+ const result = nodeIntersection(l, r, state);
31
+ return isDisjoint(result) ? throwParseError(compileDisjointReasonsMessage(state.disjoints)) : isEquality(result) ? l : result;
32
+ };
33
+ export const union = (l, r, type)=>{
34
+ const lResolution = type.meta.scope.resolveNode(l);
35
+ const rResolution = type.meta.scope.resolveNode(r);
36
+ const result = {};
37
+ const domains = keysOf({
38
+ ...lResolution,
39
+ ...rResolution
40
+ });
41
+ for (const domain of domains){
42
+ result[domain] = hasKey(lResolution, domain) ? hasKey(rResolution, domain) ? predicateUnion(domain, lResolution[domain], rResolution[domain], type) : lResolution[domain] : hasKey(rResolution, domain) ? rResolution[domain] : throwUndefinedOperandsError();
43
+ }
44
+ return result;
45
+ };
46
+ const hasImpliedDomain = (flatPredicate)=>flatPredicate[0] && (flatPredicate[0][0] === "subdomain" || flatPredicate[0][0] === "value");
47
+ export const flattenType = (type)=>{
48
+ const ctx = {
49
+ type,
50
+ path: new Path(),
51
+ lastDomain: "undefined"
52
+ };
53
+ return flattenNode(type.node, ctx);
54
+ };
55
+ export const flattenNode = (node, ctx)=>{
56
+ if (typeof node === "string") {
57
+ return ctx.type.meta.scope.resolve(node).flat;
58
+ }
59
+ const domains = keysOf(node);
60
+ if (domains.length === 1) {
61
+ const domain = domains[0];
62
+ const predicate = node[domain];
63
+ if (predicate === true) {
64
+ return domain;
65
+ }
66
+ ctx.lastDomain = domain;
67
+ const flatPredicate = flattenPredicate(predicate, ctx);
68
+ return hasImpliedDomain(flatPredicate) ? flatPredicate : [
69
+ [
70
+ "domain",
71
+ domain
72
+ ],
73
+ ...flatPredicate
74
+ ];
75
+ }
76
+ const result = {};
77
+ for (const domain1 of domains){
78
+ ctx.lastDomain = domain1;
79
+ result[domain1] = flattenPredicate(node[domain1], ctx);
80
+ }
81
+ return [
82
+ [
83
+ "domains",
84
+ result
85
+ ]
86
+ ];
87
+ };
88
+ export const isLiteralNode = (node, domain)=>{
89
+ return resolutionExtendsDomain(node, domain) && isLiteralCondition(node[domain]);
90
+ };
@@ -0,0 +1,69 @@
1
+ import { hasSubdomain } from "../utils/domains.js";
2
+ import { collapseIfSingleton, keysOf, listFrom } from "../utils/generics.js";
3
+ import { compareBranches, isBranchComparison } from "./branches.js";
4
+ import { equality, IntersectionState, isEquality } from "./compose.js";
5
+ import { flattenBranches } from "./discriminate.js";
6
+ import { branchIntersection, flattenBranch } from "./rules/rules.js";
7
+ const emptyRulesIfTrue = (predicate)=>predicate === true ? {} : predicate;
8
+ export const comparePredicates = (l, r, context)=>{
9
+ if (l === true && r === true) {
10
+ return equality();
11
+ }
12
+ if (!hasSubdomain(l, "Array") && !hasSubdomain(r, "Array")) {
13
+ const result = branchIntersection(emptyRulesIfTrue(l), emptyRulesIfTrue(r), context);
14
+ return result === l ? l : result === r ? r : result;
15
+ }
16
+ const lBranches = listFrom(emptyRulesIfTrue(l));
17
+ const rBranches = listFrom(emptyRulesIfTrue(r));
18
+ const comparison = compareBranches(lBranches, rBranches, context);
19
+ if (comparison.equalities.length === lBranches.length && comparison.equalities.length === rBranches.length) {
20
+ return equality();
21
+ }
22
+ if (comparison.lSubconditionsOfR.length + comparison.equalities.length === lBranches.length) {
23
+ return l;
24
+ }
25
+ if (comparison.rSubconditionsOfL.length + comparison.equalities.length === rBranches.length) {
26
+ return r;
27
+ }
28
+ return comparison;
29
+ };
30
+ export const predicateIntersection = (domain, l, r, state)=>{
31
+ state.domain = domain;
32
+ const comparison = comparePredicates(l, r, state);
33
+ if (!isBranchComparison(comparison)) {
34
+ return comparison;
35
+ }
36
+ return collapseIfSingleton([
37
+ ...comparison.distinctIntersections,
38
+ ...comparison.equalities.map((indices)=>comparison.lConditions[indices[0]]),
39
+ ...comparison.lSubconditionsOfR.map((lIndex)=>comparison.lConditions[lIndex]),
40
+ ...comparison.rSubconditionsOfL.map((rIndex)=>comparison.rConditions[rIndex])
41
+ ]);
42
+ };
43
+ export const predicateUnion = (domain, l, r, type)=>{
44
+ const state = new IntersectionState(type, "|");
45
+ const comparison = comparePredicates(l, r, state);
46
+ if (!isBranchComparison(comparison)) {
47
+ return isEquality(comparison) || comparison === l ? r : comparison === r ? l : // subtype of the other, it consists of two opposite literals
48
+ // and can be simplified to a non-literal boolean.
49
+ domain === "boolean" ? true : [
50
+ emptyRulesIfTrue(l),
51
+ emptyRulesIfTrue(r)
52
+ ];
53
+ }
54
+ return collapseIfSingleton([
55
+ ...comparison.lConditions.filter((_, lIndex)=>!comparison.lSubconditionsOfR.includes(lIndex) && !comparison.equalities.some((indexPair)=>indexPair[0] === lIndex)),
56
+ ...comparison.rConditions.filter((_, rIndex)=>!comparison.rSubconditionsOfL.includes(rIndex) && !comparison.equalities.some((indexPair)=>indexPair[1] === rIndex))
57
+ ]);
58
+ };
59
+ export const flattenPredicate = (predicate, context)=>{
60
+ if (predicate === true) {
61
+ return [];
62
+ }
63
+ return hasSubdomain(predicate, "Array") ? flattenBranches(predicate, context) : flattenBranch(predicate, context);
64
+ };
65
+ export const isLiteralCondition = (predicate)=>typeof predicate === "object" && "value" in predicate;
66
+ export const resolutionExtendsDomain = (resolution, domain)=>{
67
+ const domains = keysOf(resolution);
68
+ return domains.length === 1 && domains[0] === domain;
69
+ };
@@ -0,0 +1,7 @@
1
+ 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);
6
+ }
7
+ };
@@ -0,0 +1,35 @@
1
+ import { hasSubdomain } from "../../utils/domains.js";
2
+ import { equality } from "../compose.js";
3
+ export const collapsibleListUnion = (l, r)=>{
4
+ if (hasSubdomain(l, "Array")) {
5
+ if (hasSubdomain(r, "Array")) {
6
+ const result = listUnion(l, r);
7
+ return result.length === l.length ? result.length === r.length ? equality() : l : result.length === r.length ? r : result;
8
+ }
9
+ return l.includes(r) ? l : [
10
+ ...l,
11
+ r
12
+ ];
13
+ }
14
+ if (hasSubdomain(r, "Array")) {
15
+ return r.includes(l) ? r : [
16
+ ...r,
17
+ l
18
+ ];
19
+ }
20
+ return l === r ? equality() : [
21
+ l,
22
+ r
23
+ ];
24
+ };
25
+ export const listUnion = (l, r)=>{
26
+ const result = [
27
+ ...l
28
+ ];
29
+ for (const expression of r){
30
+ if (!l.includes(expression)) {
31
+ result.push(expression);
32
+ }
33
+ }
34
+ return result;
35
+ };
@@ -0,0 +1,19 @@
1
+ import { composeIntersection, equality } from "../compose.js";
2
+ export const divisorIntersection = composeIntersection((l, r)=>l === r ? equality() : Math.abs(l * r / greatestCommonDivisor(l, r)));
3
+ // https://en.wikipedia.org/wiki/Euclidean_algorithm
4
+ const greatestCommonDivisor = (l, r)=>{
5
+ let previous;
6
+ let greatestCommonDivisor = l;
7
+ let current = r;
8
+ while(current !== 0){
9
+ previous = current;
10
+ current = greatestCommonDivisor % current;
11
+ greatestCommonDivisor = previous;
12
+ }
13
+ return greatestCommonDivisor;
14
+ };
15
+ export const checkDivisor = (data, divisor, state)=>{
16
+ if (data % divisor !== 0) {
17
+ state.problems.add("divisor", data, divisor);
18
+ }
19
+ };
@@ -0,0 +1,57 @@
1
+ import { composeIntersection, composeKeyedIntersection, equality, isDisjoint } from "../compose.js";
2
+ import { flattenNode, nodeIntersection } from "../node.js";
3
+ 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)=>{
6
+ if (l === undefined) {
7
+ return r === undefined ? equality() : r;
8
+ }
9
+ if (r === undefined) {
10
+ return l;
11
+ }
12
+ context.path.push(propKey);
13
+ const result = nodeIntersection(nodeFrom(l), nodeFrom(r), context);
14
+ context.path.pop();
15
+ const resultIsOptional = isOptional(l) && isOptional(r);
16
+ if (isDisjoint(result) && resultIsOptional) {
17
+ // If an optional key has an empty intersection, the type can
18
+ // still be satisfied as long as the key is not included. Set
19
+ // the node to never rather than invalidating the type.
20
+ return {};
21
+ }
22
+ return result;
23
+ }, {
24
+ onEmpty: "bubble"
25
+ }));
26
+ export const flattenProps = (entries, props, ctx)=>{
27
+ const requiredProps = [];
28
+ const optionalProps = [];
29
+ for(const k in props){
30
+ const prop = props[k];
31
+ ctx.path.push(k);
32
+ if (isOptional(prop)) {
33
+ optionalProps.push([
34
+ k,
35
+ flattenNode(prop[1], ctx)
36
+ ]);
37
+ } else {
38
+ requiredProps.push([
39
+ k,
40
+ flattenNode(prop, ctx)
41
+ ]);
42
+ }
43
+ ctx.path.pop();
44
+ }
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
+ };
@@ -0,0 +1,90 @@
1
+ import { sizeOf } from "../../utils/domains.js";
2
+ import { composeIntersection, equality } from "../compose.js";
3
+ export const minComparators = {
4
+ ">": true,
5
+ ">=": true
6
+ };
7
+ export const maxComparators = {
8
+ "<": true,
9
+ "<=": true
10
+ };
11
+ export const isEqualityRange = (range)=>"comparator" in range;
12
+ export const rangeIntersection = composeIntersection((l, r, state)=>{
13
+ if (isEqualityRange(l)) {
14
+ if (isEqualityRange(r)) {
15
+ return l.limit === r.limit ? equality() : state.addDisjoint("range", l, r);
16
+ }
17
+ return rangeAllows(r, l.limit) ? l : state.addDisjoint("range", l, r);
18
+ }
19
+ if (isEqualityRange(r)) {
20
+ return rangeAllows(l, r.limit) ? r : state.addDisjoint("range", l, r);
21
+ }
22
+ const stricterMin = compareStrictness("min", l.min, r.min);
23
+ const stricterMax = compareStrictness("max", l.max, r.max);
24
+ if (stricterMin === "l") {
25
+ if (stricterMax === "r") {
26
+ return compareStrictness("min", l.min, r.max) === "l" ? state.addDisjoint("range", l, r) : {
27
+ min: l.min,
28
+ max: r.max
29
+ };
30
+ }
31
+ return l;
32
+ }
33
+ if (stricterMin === "r") {
34
+ if (stricterMax === "l") {
35
+ return compareStrictness("max", l.max, r.min) === "l" ? state.addDisjoint("range", l, r) : {
36
+ min: r.min,
37
+ max: l.max
38
+ };
39
+ }
40
+ return r;
41
+ }
42
+ return stricterMax === "l" ? l : stricterMax === "r" ? r : equality();
43
+ });
44
+ const rangeAllows = (range, n)=>isEqualityRange(range) ? n === range.limit : minAllows(range.min, n) && maxAllows(range.max, n);
45
+ const minAllows = (min, n)=>!min || n < min.limit || n === min.limit && !isExclusive(min.comparator);
46
+ const maxAllows = (max, n)=>!max || n > max.limit || n === max.limit && !isExclusive(max.comparator);
47
+ export const flattenRange = (entries, range, ctx)=>{
48
+ const units = ctx.lastDomain === "string" ? "characters" : ctx.lastDomain === "object" ? "items" : undefined;
49
+ if (isEqualityRange(range)) {
50
+ return entries.push([
51
+ "bound",
52
+ units ? {
53
+ ...range,
54
+ units
55
+ } : range
56
+ ]);
57
+ }
58
+ if (range.min) {
59
+ entries.push([
60
+ "bound",
61
+ units ? {
62
+ ...range.min,
63
+ units
64
+ } : range.min
65
+ ]);
66
+ }
67
+ if (range.max) {
68
+ entries.push([
69
+ "bound",
70
+ units ? {
71
+ ...range.max,
72
+ units
73
+ } : range.max
74
+ ]);
75
+ }
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
+ };
82
+ const comparatorCheckers = {
83
+ "<": (size, limit)=>size < limit,
84
+ ">": (size, limit)=>size > limit,
85
+ "<=": (size, limit)=>size <= limit,
86
+ ">=": (size, limit)=>size >= limit,
87
+ "==": (size, limit)=>size === limit
88
+ };
89
+ export const compareStrictness = (kind, l, r)=>!l ? !r ? "=" : "r" : !r ? "l" : l.limit === r.limit ? isExclusive(l.comparator) ? isExclusive(r.comparator) ? "=" : "l" : isExclusive(r.comparator) ? "r" : "=" : kind === "min" ? l.limit > r.limit ? "l" : "r" : l.limit < r.limit ? "l" : "r";
90
+ const isExclusive = (comparator)=>comparator.length === 1;
@@ -0,0 +1,53 @@
1
+ import { composeIntersection } from "../compose.js";
2
+ import { collapsibleListUnion } from "./collapsibleSet.js";
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
+ export const getRegex = (source)=>{
19
+ if (!regexCache[source]) {
20
+ regexCache[source] = new RegExp(source);
21
+ }
22
+ return regexCache[source];
23
+ };
24
+ export const checkRegex = (data, regex, state)=>{
25
+ if (!regex.test(data)) {
26
+ state.problems.add("regex", data, regex);
27
+ }
28
+ };
29
+ 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
+ };