arktype 1.0.28-alpha → 1.1.0-dev-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 (194) hide show
  1. package/dist/main.d.ts +1018 -0
  2. package/dist/main.js +1450 -0
  3. package/package.json +36 -108
  4. package/LICENSE +0 -7
  5. package/README.md +0 -351
  6. package/dist/cjs/main.js +0 -38
  7. package/dist/cjs/nodes/branch.js +0 -140
  8. package/dist/cjs/nodes/compose.js +0 -163
  9. package/dist/cjs/nodes/discriminate.js +0 -265
  10. package/dist/cjs/nodes/node.js +0 -139
  11. package/dist/cjs/nodes/predicate.js +0 -86
  12. package/dist/cjs/nodes/rules/class.js +0 -25
  13. package/dist/cjs/nodes/rules/collapsibleSet.js +0 -48
  14. package/dist/cjs/nodes/rules/divisor.js +0 -29
  15. package/dist/cjs/nodes/rules/props.js +0 -167
  16. package/dist/cjs/nodes/rules/range.js +0 -105
  17. package/dist/cjs/nodes/rules/regex.js +0 -26
  18. package/dist/cjs/nodes/rules/rules.js +0 -123
  19. package/dist/cjs/package.json +0 -3
  20. package/dist/cjs/parse/ast/ast.js +0 -4
  21. package/dist/cjs/parse/ast/bound.js +0 -16
  22. package/dist/cjs/parse/ast/config.js +0 -13
  23. package/dist/cjs/parse/ast/distributableFunction.js +0 -48
  24. package/dist/cjs/parse/ast/divisor.js +0 -9
  25. package/dist/cjs/parse/ast/intersection.js +0 -30
  26. package/dist/cjs/parse/ast/keyof.js +0 -111
  27. package/dist/cjs/parse/ast/morph.js +0 -58
  28. package/dist/cjs/parse/ast/narrow.js +0 -22
  29. package/dist/cjs/parse/ast/node.js +0 -4
  30. package/dist/cjs/parse/ast/tuple.js +0 -94
  31. package/dist/cjs/parse/ast/union.js +0 -9
  32. package/dist/cjs/parse/ast/utils.js +0 -4
  33. package/dist/cjs/parse/definition.js +0 -61
  34. package/dist/cjs/parse/record.js +0 -37
  35. package/dist/cjs/parse/string/reduce/dynamic.js +0 -167
  36. package/dist/cjs/parse/string/reduce/shared.js +0 -23
  37. package/dist/cjs/parse/string/reduce/static.js +0 -4
  38. package/dist/cjs/parse/string/shift/operand/enclosed.js +0 -54
  39. package/dist/cjs/parse/string/shift/operand/operand.js +0 -11
  40. package/dist/cjs/parse/string/shift/operand/unenclosed.js +0 -53
  41. package/dist/cjs/parse/string/shift/operator/bounds.js +0 -87
  42. package/dist/cjs/parse/string/shift/operator/divisor.js +0 -35
  43. package/dist/cjs/parse/string/shift/operator/operator.js +0 -26
  44. package/dist/cjs/parse/string/shift/scanner.js +0 -114
  45. package/dist/cjs/parse/string/string.js +0 -43
  46. package/dist/cjs/scopes/ark.js +0 -45
  47. package/dist/cjs/scopes/cache.js +0 -52
  48. package/dist/cjs/scopes/expressions.js +0 -29
  49. package/dist/cjs/scopes/jsObjects.js +0 -93
  50. package/dist/cjs/scopes/scope.js +0 -323
  51. package/dist/cjs/scopes/tsKeywords.js +0 -113
  52. package/dist/cjs/scopes/type.js +0 -50
  53. package/dist/cjs/scopes/validation/creditCard.js +0 -47
  54. package/dist/cjs/scopes/validation/date.js +0 -62
  55. package/dist/cjs/scopes/validation/validation.js +0 -108
  56. package/dist/cjs/traverse/problems.js +0 -281
  57. package/dist/cjs/traverse/traverse.js +0 -390
  58. package/dist/cjs/utils/chainableNoOpProxy.js +0 -23
  59. package/dist/cjs/utils/data.js +0 -53
  60. package/dist/cjs/utils/domains.js +0 -30
  61. package/dist/cjs/utils/errors.js +0 -26
  62. package/dist/cjs/utils/freeze.js +0 -15
  63. package/dist/cjs/utils/generics.js +0 -63
  64. package/dist/cjs/utils/numericLiterals.js +0 -75
  65. package/dist/cjs/utils/objectKinds.js +0 -69
  66. package/dist/cjs/utils/paths.js +0 -32
  67. package/dist/cjs/utils/serialize.js +0 -74
  68. package/dist/cjs/utils/unionToTuple.js +0 -4
  69. package/dist/mjs/main.js +0 -8
  70. package/dist/mjs/nodes/branch.js +0 -123
  71. package/dist/mjs/nodes/compose.js +0 -141
  72. package/dist/mjs/nodes/discriminate.js +0 -250
  73. package/dist/mjs/nodes/node.js +0 -117
  74. package/dist/mjs/nodes/predicate.js +0 -69
  75. package/dist/mjs/nodes/rules/class.js +0 -11
  76. package/dist/mjs/nodes/rules/collapsibleSet.js +0 -34
  77. package/dist/mjs/nodes/rules/divisor.js +0 -15
  78. package/dist/mjs/nodes/rules/props.js +0 -149
  79. package/dist/mjs/nodes/rules/range.js +0 -86
  80. package/dist/mjs/nodes/rules/regex.js +0 -11
  81. package/dist/mjs/nodes/rules/rules.js +0 -106
  82. package/dist/mjs/package.json +0 -3
  83. package/dist/mjs/parse/ast/ast.js +0 -1
  84. package/dist/mjs/parse/ast/bound.js +0 -2
  85. package/dist/mjs/parse/ast/config.js +0 -9
  86. package/dist/mjs/parse/ast/distributableFunction.js +0 -34
  87. package/dist/mjs/parse/ast/divisor.js +0 -1
  88. package/dist/mjs/parse/ast/intersection.js +0 -16
  89. package/dist/mjs/parse/ast/keyof.js +0 -103
  90. package/dist/mjs/parse/ast/morph.js +0 -44
  91. package/dist/mjs/parse/ast/narrow.js +0 -14
  92. package/dist/mjs/parse/ast/node.js +0 -1
  93. package/dist/mjs/parse/ast/tuple.js +0 -80
  94. package/dist/mjs/parse/ast/union.js +0 -1
  95. package/dist/mjs/parse/ast/utils.js +0 -1
  96. package/dist/mjs/parse/definition.js +0 -46
  97. package/dist/mjs/parse/record.js +0 -29
  98. package/dist/mjs/parse/string/reduce/dynamic.js +0 -159
  99. package/dist/mjs/parse/string/reduce/shared.js +0 -6
  100. package/dist/mjs/parse/string/reduce/static.js +0 -1
  101. package/dist/mjs/parse/string/shift/operand/enclosed.js +0 -39
  102. package/dist/mjs/parse/string/shift/operand/operand.js +0 -3
  103. package/dist/mjs/parse/string/shift/operand/unenclosed.js +0 -36
  104. package/dist/mjs/parse/string/shift/operator/bounds.js +0 -70
  105. package/dist/mjs/parse/string/shift/operator/divisor.js +0 -21
  106. package/dist/mjs/parse/string/shift/operator/operator.js +0 -13
  107. package/dist/mjs/parse/string/shift/scanner.js +0 -106
  108. package/dist/mjs/parse/string/string.js +0 -28
  109. package/dist/mjs/scopes/ark.js +0 -28
  110. package/dist/mjs/scopes/cache.js +0 -38
  111. package/dist/mjs/scopes/expressions.js +0 -89
  112. package/dist/mjs/scopes/jsObjects.js +0 -82
  113. package/dist/mjs/scopes/scope.js +0 -303
  114. package/dist/mjs/scopes/tsKeywords.js +0 -116
  115. package/dist/mjs/scopes/type.js +0 -35
  116. package/dist/mjs/scopes/validation/creditCard.js +0 -34
  117. package/dist/mjs/scopes/validation/date.js +0 -48
  118. package/dist/mjs/scopes/validation/validation.js +0 -112
  119. package/dist/mjs/traverse/problems.js +0 -260
  120. package/dist/mjs/traverse/traverse.js +0 -373
  121. package/dist/mjs/utils/chainableNoOpProxy.js +0 -15
  122. package/dist/mjs/utils/data.js +0 -38
  123. package/dist/mjs/utils/domains.js +0 -15
  124. package/dist/mjs/utils/errors.js +0 -10
  125. package/dist/mjs/utils/freeze.js +0 -7
  126. package/dist/mjs/utils/generics.js +0 -38
  127. package/dist/mjs/utils/numericLiterals.js +0 -72
  128. package/dist/mjs/utils/objectKinds.js +0 -55
  129. package/dist/mjs/utils/paths.js +0 -18
  130. package/dist/mjs/utils/serialize.js +0 -58
  131. package/dist/mjs/utils/unionToTuple.js +0 -1
  132. package/dist/tsconfig.temp.tsbuildinfo +0 -1
  133. package/dist/types/main.d.ts +0 -15
  134. package/dist/types/nodes/branch.d.ts +0 -29
  135. package/dist/types/nodes/compose.d.ts +0 -98
  136. package/dist/types/nodes/discriminate.d.ts +0 -26
  137. package/dist/types/nodes/node.d.ts +0 -69
  138. package/dist/types/nodes/predicate.d.ts +0 -18
  139. package/dist/types/nodes/rules/class.d.ts +0 -4
  140. package/dist/types/nodes/rules/collapsibleSet.d.ts +0 -4
  141. package/dist/types/nodes/rules/divisor.d.ts +0 -3
  142. package/dist/types/nodes/rules/props.d.ts +0 -43
  143. package/dist/types/nodes/rules/range.d.ts +0 -34
  144. package/dist/types/nodes/rules/regex.d.ts +0 -5
  145. package/dist/types/nodes/rules/rules.d.ts +0 -33
  146. package/dist/types/parse/ast/ast.d.ts +0 -24
  147. package/dist/types/parse/ast/bound.d.ts +0 -27
  148. package/dist/types/parse/ast/config.d.ts +0 -15
  149. package/dist/types/parse/ast/distributableFunction.d.ts +0 -18
  150. package/dist/types/parse/ast/divisor.d.ts +0 -13
  151. package/dist/types/parse/ast/intersection.d.ts +0 -31
  152. package/dist/types/parse/ast/keyof.d.ts +0 -10
  153. package/dist/types/parse/ast/morph.d.ts +0 -18
  154. package/dist/types/parse/ast/narrow.d.ts +0 -21
  155. package/dist/types/parse/ast/node.d.ts +0 -35
  156. package/dist/types/parse/ast/tuple.d.ts +0 -41
  157. package/dist/types/parse/ast/union.d.ts +0 -17
  158. package/dist/types/parse/ast/utils.d.ts +0 -7
  159. package/dist/types/parse/definition.d.ts +0 -30
  160. package/dist/types/parse/record.d.ts +0 -26
  161. package/dist/types/parse/string/reduce/dynamic.d.ts +0 -34
  162. package/dist/types/parse/string/reduce/shared.d.ts +0 -25
  163. package/dist/types/parse/string/reduce/static.d.ts +0 -130
  164. package/dist/types/parse/string/shift/operand/enclosed.d.ts +0 -28
  165. package/dist/types/parse/string/shift/operand/operand.d.ts +0 -9
  166. package/dist/types/parse/string/shift/operand/unenclosed.d.ts +0 -18
  167. package/dist/types/parse/string/shift/operator/bounds.d.ts +0 -21
  168. package/dist/types/parse/string/shift/operator/divisor.d.ts +0 -13
  169. package/dist/types/parse/string/shift/operator/operator.d.ts +0 -13
  170. package/dist/types/parse/string/shift/scanner.d.ts +0 -89
  171. package/dist/types/parse/string/string.d.ts +0 -25
  172. package/dist/types/scopes/ark.d.ts +0 -209
  173. package/dist/types/scopes/cache.d.ts +0 -14
  174. package/dist/types/scopes/expressions.d.ts +0 -136
  175. package/dist/types/scopes/jsObjects.d.ts +0 -26
  176. package/dist/types/scopes/scope.d.ts +0 -99
  177. package/dist/types/scopes/tsKeywords.d.ts +0 -50
  178. package/dist/types/scopes/type.d.ts +0 -67
  179. package/dist/types/scopes/validation/creditCard.d.ts +0 -2
  180. package/dist/types/scopes/validation/date.d.ts +0 -23
  181. package/dist/types/scopes/validation/validation.d.ts +0 -49
  182. package/dist/types/traverse/problems.d.ts +0 -88
  183. package/dist/types/traverse/traverse.d.ts +0 -55
  184. package/dist/types/utils/chainableNoOpProxy.d.ts +0 -14
  185. package/dist/types/utils/data.d.ts +0 -13
  186. package/dist/types/utils/domains.d.ts +0 -32
  187. package/dist/types/utils/errors.d.ts +0 -6
  188. package/dist/types/utils/freeze.d.ts +0 -2
  189. package/dist/types/utils/generics.d.ts +0 -125
  190. package/dist/types/utils/numericLiterals.d.ts +0 -46
  191. package/dist/types/utils/objectKinds.d.ts +0 -84
  192. package/dist/types/utils/paths.d.ts +0 -9
  193. package/dist/types/utils/serialize.d.ts +0 -37
  194. package/dist/types/utils/unionToTuple.d.ts +0 -11
@@ -1,141 +0,0 @@
1
- function _checkPrivateRedeclaration(obj, privateCollection) {
2
- if (privateCollection.has(obj)) {
3
- throw new TypeError("Cannot initialize the same private elements twice on an object");
4
- }
5
- }
6
- function _classApplyDescriptorGet(receiver, descriptor) {
7
- if (descriptor.get) {
8
- return descriptor.get.call(receiver);
9
- }
10
- return descriptor.value;
11
- }
12
- function _classApplyDescriptorSet(receiver, descriptor, value) {
13
- if (descriptor.set) {
14
- descriptor.set.call(receiver, value);
15
- } else {
16
- if (!descriptor.writable) {
17
- throw new TypeError("attempted to set read only private field");
18
- }
19
- descriptor.value = value;
20
- }
21
- }
22
- function _classExtractFieldDescriptor(receiver, privateMap, action) {
23
- if (!privateMap.has(receiver)) {
24
- throw new TypeError("attempted to " + action + " private field on non-instance");
25
- }
26
- return privateMap.get(receiver);
27
- }
28
- function _classPrivateFieldGet(receiver, privateMap) {
29
- var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "get");
30
- return _classApplyDescriptorGet(receiver, descriptor);
31
- }
32
- function _classPrivateFieldInit(obj, privateMap, value) {
33
- _checkPrivateRedeclaration(obj, privateMap);
34
- privateMap.set(obj, value);
35
- }
36
- function _classPrivateFieldSet(receiver, privateMap, value) {
37
- var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "set");
38
- _classApplyDescriptorSet(receiver, descriptor, value);
39
- return value;
40
- }
41
- function _defineProperty(obj, key, value) {
42
- if (key in obj) {
43
- Object.defineProperty(obj, key, {
44
- value: value,
45
- enumerable: true,
46
- configurable: true,
47
- writable: true
48
- });
49
- } else {
50
- obj[key] = value;
51
- }
52
- return obj;
53
- }
54
- import { throwInternalError } from "../utils/errors.js";
55
- import { objectKeysOf } from "../utils/generics.js";
56
- import { Path } from "../utils/paths.js";
57
- import { stringify } from "../utils/serialize.js";
58
- export const composeIntersection = (reducer)=>(l, r, state)=>l === undefined ? r === undefined ? throwInternalError(undefinedOperandsMessage) : r : r === undefined ? l : reducer(l, r, state);
59
- export const undefinedOperandsMessage = `Unexpected operation two undefined operands`;
60
- export const disjointDescriptionWriters = {
61
- domain: ({ l , r })=>`${l.join(", ")} and ${r.join(", ")}`,
62
- range: ({ l , r })=>`${stringifyRange(l)} and ${stringifyRange(r)}`,
63
- class: ({ l , r })=>`classes ${typeof l === "string" ? l : l.name} and ${typeof r === "string" ? r : r.name}`,
64
- tupleLength: ({ l , r })=>`tuples of length ${l} and ${r}`,
65
- value: ({ l , r })=>`literal values ${stringify(l)} and ${stringify(r)}`,
66
- leftAssignability: ({ l , r })=>`literal value ${stringify(l.value)} and ${stringify(r)}`,
67
- rightAssignability: ({ l , r })=>`literal value ${stringify(r.value)} and ${stringify(l)}`,
68
- union: ({ l , r })=>`branches ${stringify(l)} and branches ${stringify(r)}`
69
- };
70
- export const stringifyRange = (range)=>"limit" in range ? `the range of exactly ${range.limit}` : range.min ? range.max ? `the range bounded by ${range.min.comparator}${range.min.limit} and ${range.max.comparator}${range.max.limit}` : `${range.min.comparator}${range.min.limit}` : range.max ? `${range.max.comparator}${range.max.limit}` : "the unbounded range";
71
- var _disjoints = /*#__PURE__*/ new WeakMap();
72
- export class IntersectionState {
73
- get disjoints() {
74
- return _classPrivateFieldGet(this, _disjoints);
75
- }
76
- addDisjoint(kind, l, r) {
77
- _classPrivateFieldGet(this, _disjoints)[`${this.path}`] = {
78
- kind,
79
- l,
80
- r,
81
- lOptional: this.lOptional,
82
- rOptional: this.rOptional
83
- };
84
- return empty;
85
- }
86
- constructor(type, lastOperator){
87
- _defineProperty(this, "type", void 0);
88
- _defineProperty(this, "lastOperator", void 0);
89
- _defineProperty(this, "path", void 0);
90
- _defineProperty(this, "lOptional", void 0);
91
- _defineProperty(this, "rOptional", void 0);
92
- _defineProperty(this, "domain", void 0);
93
- _classPrivateFieldInit(this, _disjoints, {
94
- writable: true,
95
- value: void 0
96
- });
97
- this.type = type;
98
- this.lastOperator = lastOperator;
99
- this.path = new Path();
100
- this.lOptional = false;
101
- this.rOptional = false;
102
- _classPrivateFieldSet(this, _disjoints, {});
103
- }
104
- }
105
- const empty = Symbol("empty");
106
- export const anonymousDisjoint = ()=>empty;
107
- export const isDisjoint = (result)=>result === empty;
108
- const equal = Symbol("equal");
109
- export const equality = ()=>equal;
110
- export const isEquality = (result)=>result === equal;
111
- export const composeKeyedIntersection = (reducer, config)=>(l, r, state)=>{
112
- const result = {};
113
- const keys = objectKeysOf({
114
- ...l,
115
- ...r
116
- });
117
- let lImpliesR = true;
118
- let rImpliesL = true;
119
- for (const k of keys){
120
- const keyResult = typeof reducer === "function" ? reducer(k, l[k], r[k], state) : reducer[k](l[k], r[k], state);
121
- if (isEquality(keyResult)) {
122
- if (l[k] !== undefined) {
123
- result[k] = l[k];
124
- }
125
- } else if (isDisjoint(keyResult)) {
126
- if (config.onEmpty === "omit") {
127
- lImpliesR = false;
128
- rImpliesL = false;
129
- } else {
130
- return empty;
131
- }
132
- } else {
133
- if (keyResult !== undefined) {
134
- result[k] = keyResult;
135
- }
136
- lImpliesR && (lImpliesR = keyResult === l[k]);
137
- rImpliesL && (rImpliesL = keyResult === r[k]);
138
- }
139
- }
140
- return lImpliesR ? rImpliesL ? equality() : l : rImpliesL ? r : result;
141
- };
@@ -1,250 +0,0 @@
1
- import { writeUndiscriminatableMorphUnionMessage } from "../parse/ast/union.js";
2
- import { domainOf } from "../utils/domains.js";
3
- import { throwInternalError, throwParseError } from "../utils/errors.js";
4
- import { isKeyOf, keyCount, objectKeysOf } from "../utils/generics.js";
5
- import { getExactConstructorObjectKind, isArray, objectKindOf } from "../utils/objectKinds.js";
6
- import { Path } from "../utils/paths.js";
7
- import { serializePrimitive } from "../utils/serialize.js";
8
- import { branchIntersection, flattenBranch } from "./branch.js";
9
- import { IntersectionState } from "./compose.js";
10
- import { mappedKeys, propToNode } from "./rules/props.js";
11
- export const flattenBranches = (branches, ctx)=>{
12
- const discriminants = calculateDiscriminants(branches, ctx);
13
- const indices = branches.map((_, i)=>i);
14
- return discriminate(branches, indices, discriminants, ctx);
15
- };
16
- const discriminate = (originalBranches, remainingIndices, discriminants, ctx)=>{
17
- if (remainingIndices.length === 1) {
18
- return flattenBranch(originalBranches[remainingIndices[0]], ctx);
19
- }
20
- const bestDiscriminant = findBestDiscriminant(remainingIndices, discriminants);
21
- if (!bestDiscriminant) {
22
- return [
23
- [
24
- "branches",
25
- remainingIndices.map((i)=>branchIncludesMorph(originalBranches[i], ctx.type.scope) ? throwParseError(writeUndiscriminatableMorphUnionMessage(`${ctx.path}`)) : flattenBranch(originalBranches[i], ctx))
26
- ]
27
- ];
28
- }
29
- const cases = {};
30
- for(const caseKey in bestDiscriminant.indexCases){
31
- const nextIndices = bestDiscriminant.indexCases[caseKey];
32
- cases[caseKey] = discriminate(originalBranches, nextIndices, discriminants, ctx);
33
- if (caseKey !== "default") {
34
- pruneDiscriminant(cases[caseKey], bestDiscriminant.path, bestDiscriminant, ctx);
35
- }
36
- }
37
- return [
38
- [
39
- "switch",
40
- {
41
- path: bestDiscriminant.path,
42
- kind: bestDiscriminant.kind,
43
- cases
44
- }
45
- ]
46
- ];
47
- };
48
- const pruneDiscriminant = (entries, segments, discriminant, ctx)=>{
49
- for(let i = 0; i < entries.length; i++){
50
- const [k, v] = entries[i];
51
- if (!segments.length) {
52
- if (discriminant.kind === "domain") {
53
- if (k === "domain" || k === "domains") {
54
- entries.splice(i, 1);
55
- return;
56
- } else if (k === "class" || k === "value") {
57
- // these keys imply a domain, but also add additional
58
- // information, so can't be pruned
59
- return;
60
- }
61
- } else if (discriminant.kind === k) {
62
- entries.splice(i, 1);
63
- return;
64
- }
65
- } else if ((k === "requiredProp" || k === "prerequisiteProp" || k === "optionalProp") && v[0] === segments[0]) {
66
- if (typeof v[1] === "string") {
67
- if (discriminant.kind !== "domain") {
68
- return throwInternalPruneFailure(discriminant);
69
- }
70
- entries.splice(i, 1);
71
- return;
72
- }
73
- pruneDiscriminant(v[1], segments.slice(1), discriminant, ctx);
74
- if (v[1].length === 0) {
75
- entries.splice(i, 1);
76
- }
77
- return;
78
- }
79
- // check for branch keys, which must be traversed even if there are no
80
- // segments left
81
- if (k === "domains") {
82
- /* c8 ignore next */ if (keyCount(v) !== 1 || !v.object) {
83
- return throwInternalPruneFailure(discriminant);
84
- }
85
- pruneDiscriminant(v.object, segments, discriminant, ctx);
86
- return;
87
- } else if (k === "switch") {
88
- for(const caseKey in v.cases){
89
- pruneDiscriminant(v.cases[caseKey], segments, discriminant, ctx);
90
- }
91
- return;
92
- } else if (k === "branches") {
93
- for (const branch of v){
94
- pruneDiscriminant(branch, segments, discriminant, ctx);
95
- }
96
- return;
97
- }
98
- }
99
- return throwInternalPruneFailure(discriminant);
100
- };
101
- const throwInternalPruneFailure = (discriminant)=>throwInternalError(`Unexpectedly failed to discriminate ${discriminant.kind} at path '${discriminant.path}'`);
102
- const discriminantKinds = {
103
- domain: true,
104
- class: true,
105
- value: true
106
- };
107
- const calculateDiscriminants = (branches, ctx)=>{
108
- const discriminants = {
109
- disjointsByPair: {},
110
- casesByDisjoint: {}
111
- };
112
- for(let lIndex = 0; lIndex < branches.length - 1; lIndex++){
113
- for(let rIndex = lIndex + 1; rIndex < branches.length; rIndex++){
114
- const pairKey = `${lIndex}/${rIndex}`;
115
- const pairDisjoints = [];
116
- discriminants.disjointsByPair[pairKey] = pairDisjoints;
117
- const intersectionState = new IntersectionState(ctx.type, "|");
118
- branchIntersection(branches[lIndex], branches[rIndex], intersectionState);
119
- for(const path in intersectionState.disjoints){
120
- if (path.includes(mappedKeys.index)) {
121
- continue;
122
- }
123
- const { l , r , kind , lOptional , rOptional } = intersectionState.disjoints[path];
124
- if (!isKeyOf(kind, discriminantKinds)) {
125
- continue;
126
- }
127
- if (lOptional || rOptional) {
128
- continue;
129
- }
130
- const lSerialized = serializeDefinitionIfAllowed(kind, l);
131
- const rSerialized = serializeDefinitionIfAllowed(kind, r);
132
- if (lSerialized === undefined || rSerialized === undefined) {
133
- continue;
134
- }
135
- const qualifiedDisjoint = path === "/" ? kind : `${path}/${kind}`;
136
- pairDisjoints.push(qualifiedDisjoint);
137
- if (!discriminants.casesByDisjoint[qualifiedDisjoint]) {
138
- discriminants.casesByDisjoint[qualifiedDisjoint] = {
139
- [lSerialized]: [
140
- lIndex
141
- ],
142
- [rSerialized]: [
143
- rIndex
144
- ]
145
- };
146
- continue;
147
- }
148
- const cases = discriminants.casesByDisjoint[qualifiedDisjoint];
149
- const existingLBranch = cases[lSerialized];
150
- if (!existingLBranch) {
151
- cases[lSerialized] = [
152
- lIndex
153
- ];
154
- } else if (!existingLBranch.includes(lIndex)) {
155
- existingLBranch.push(lIndex);
156
- }
157
- const existingRBranch = cases[rSerialized];
158
- if (!existingRBranch) {
159
- cases[rSerialized] = [
160
- rIndex
161
- ];
162
- } else if (!existingRBranch.includes(rIndex)) {
163
- existingRBranch.push(rIndex);
164
- }
165
- }
166
- }
167
- }
168
- return discriminants;
169
- };
170
- const parseQualifiedDisjoint = (qualifiedDisjoint)=>{
171
- const path = Path.fromString(qualifiedDisjoint);
172
- return [
173
- path,
174
- path.pop()
175
- ];
176
- };
177
- const findBestDiscriminant = (remainingIndices, discriminants)=>{
178
- let bestDiscriminant;
179
- for(let i = 0; i < remainingIndices.length - 1; i++){
180
- const lIndex = remainingIndices[i];
181
- for(let j = i + 1; j < remainingIndices.length; j++){
182
- const rIndex = remainingIndices[j];
183
- const candidates = discriminants.disjointsByPair[`${lIndex}/${rIndex}`];
184
- for (const qualifiedDisjoint of candidates){
185
- const indexCases = discriminants.casesByDisjoint[qualifiedDisjoint];
186
- const filteredCases = {};
187
- const defaultCases = [
188
- ...remainingIndices
189
- ];
190
- let score = 0;
191
- for(const caseKey in indexCases){
192
- const filteredIndices = indexCases[caseKey].filter((i)=>{
193
- const remainingIndex = remainingIndices.indexOf(i);
194
- if (remainingIndex !== -1) {
195
- delete defaultCases[remainingIndex];
196
- return true;
197
- }
198
- });
199
- if (filteredIndices.length === 0) {
200
- continue;
201
- }
202
- filteredCases[caseKey] = filteredIndices;
203
- score++;
204
- }
205
- const defaultCaseKeys = objectKeysOf(defaultCases);
206
- if (defaultCaseKeys.length) {
207
- filteredCases["default"] = defaultCaseKeys.map((k)=>parseInt(k));
208
- }
209
- if (!bestDiscriminant || score > bestDiscriminant.score) {
210
- const [path, kind] = parseQualifiedDisjoint(qualifiedDisjoint);
211
- bestDiscriminant = {
212
- path,
213
- kind,
214
- indexCases: filteredCases,
215
- score
216
- };
217
- if (score === remainingIndices.length) {
218
- // if we find a candidate that discriminates all branches, return early
219
- return bestDiscriminant;
220
- }
221
- }
222
- }
223
- }
224
- }
225
- return bestDiscriminant;
226
- };
227
- export const serializeDefinitionIfAllowed = (kind, definition)=>{
228
- switch(kind){
229
- case "value":
230
- return serializeIfPrimitive(definition);
231
- case "domain":
232
- return definition;
233
- case "class":
234
- return getExactConstructorObjectKind(definition);
235
- default:
236
- return;
237
- }
238
- };
239
- const serializeIfPrimitive = (data)=>{
240
- const domain = domainOf(data);
241
- return domain === "object" || domain === "symbol" ? undefined : serializePrimitive(data);
242
- };
243
- const serializeData = {
244
- value: (data)=>serializeIfPrimitive(data) ?? "default",
245
- class: (data)=>objectKindOf(data) ?? "default",
246
- domain: domainOf
247
- };
248
- export const serializeCase = (kind, data)=>serializeData[kind](data);
249
- const branchIncludesMorph = (branch, $)=>"morph" in branch ? true : "props" in branch ? Object.values(branch.props).some((prop)=>nodeIncludesMorph(propToNode(prop), $)) : false;
250
- const nodeIncludesMorph = (node, $)=>typeof node === "string" ? $.resolve(node).includesMorph : Object.values($.resolveTypeNode(node)).some((predicate)=>predicate === true ? false : isArray(predicate) ? predicate.some((branch)=>branchIncludesMorph(branch, $)) : branchIncludesMorph(predicate, $));
@@ -1,117 +0,0 @@
1
- import { compileDisjointReasonsMessage } from "../parse/ast/intersection.js";
2
- import { throwInternalError, throwParseError } from "../utils/errors.js";
3
- import { entriesOf, hasKey, hasKeys, objectKeysOf } from "../utils/generics.js";
4
- import { Path } from "../utils/paths.js";
5
- import { anonymousDisjoint, composeKeyedIntersection, IntersectionState, isDisjoint, isEquality, undefinedOperandsMessage } from "./compose.js";
6
- import { flattenPredicate, isLiteralCondition, predicateIntersection, predicateUnion } from "./predicate.js";
7
- import { mappedKeys } from "./rules/props.js";
8
- export const isConfigNode = (node)=>"config" in node;
9
- export const nodeIntersection = (l, r, state)=>{
10
- state.domain = undefined;
11
- const lDomains = state.type.scope.resolveTypeNode(l);
12
- const rDomains = state.type.scope.resolveTypeNode(r);
13
- const result = typeNodeIntersection(lDomains, rDomains, state);
14
- if (typeof result === "object" && !hasKeys(result)) {
15
- return hasKeys(state.disjoints) ? anonymousDisjoint() : state.addDisjoint("domain", objectKeysOf(lDomains), objectKeysOf(rDomains));
16
- }
17
- return result === lDomains ? l : result === rDomains ? r : result;
18
- };
19
- const typeNodeIntersection = composeKeyedIntersection((domain, l, r, context)=>{
20
- if (l === undefined) {
21
- return r === undefined ? throwInternalError(undefinedOperandsMessage) : undefined;
22
- }
23
- if (r === undefined) {
24
- return undefined;
25
- }
26
- return predicateIntersection(domain, l, r, context);
27
- }, {
28
- onEmpty: "omit"
29
- });
30
- export const rootIntersection = (l, r, type)=>{
31
- const state = new IntersectionState(type, "&");
32
- const result = nodeIntersection(l, r, state);
33
- return isDisjoint(result) ? throwParseError(compileDisjointReasonsMessage(state.disjoints)) : isEquality(result) ? l : result;
34
- };
35
- export const rootUnion = (l, r, type)=>{
36
- const lDomains = type.scope.resolveTypeNode(l);
37
- const rDomains = type.scope.resolveTypeNode(r);
38
- const result = {};
39
- const domains = objectKeysOf({
40
- ...lDomains,
41
- ...rDomains
42
- });
43
- for (const domain of domains){
44
- result[domain] = hasKey(lDomains, domain) ? hasKey(rDomains, domain) ? predicateUnion(domain, lDomains[domain], rDomains[domain], type) : lDomains[domain] : hasKey(rDomains, domain) ? rDomains[domain] : throwInternalError(undefinedOperandsMessage);
45
- }
46
- return result;
47
- };
48
- const hasImpliedDomain = (flatPredicate)=>flatPredicate[0] && (flatPredicate[0][0] === "value" || flatPredicate[0][0] === "class");
49
- export const flattenType = (type)=>{
50
- const ctx = {
51
- type,
52
- path: new Path(),
53
- lastDomain: "undefined"
54
- };
55
- return flattenNode(type.node, ctx);
56
- };
57
- export const flattenNode = (node, ctx)=>{
58
- if (typeof node === "string") {
59
- return ctx.type.scope.resolve(node).flat;
60
- }
61
- const hasConfig = isConfigNode(node);
62
- const flattenedTypeNode = flattenTypeNode(hasConfig ? node.node : node, ctx);
63
- return hasConfig ? [
64
- [
65
- "config",
66
- {
67
- config: entriesOf(node.config),
68
- node: flattenedTypeNode
69
- }
70
- ]
71
- ] : flattenedTypeNode;
72
- };
73
- export const flattenTypeNode = (node, ctx)=>{
74
- const domains = objectKeysOf(node);
75
- if (domains.length === 1) {
76
- const domain = domains[0];
77
- const predicate = node[domain];
78
- if (predicate === true) {
79
- return domain;
80
- }
81
- ctx.lastDomain = domain;
82
- const flatPredicate = flattenPredicate(predicate, ctx);
83
- return hasImpliedDomain(flatPredicate) ? flatPredicate : [
84
- [
85
- "domain",
86
- domain
87
- ],
88
- ...flatPredicate
89
- ];
90
- }
91
- const result = {};
92
- for (const domain of domains){
93
- ctx.lastDomain = domain;
94
- result[domain] = flattenPredicate(node[domain], ctx);
95
- }
96
- return [
97
- [
98
- "domains",
99
- result
100
- ]
101
- ];
102
- };
103
- export const isLiteralNode = (node, domain)=>{
104
- return resolutionExtendsDomain(node, domain) && isLiteralCondition(node[domain]);
105
- };
106
- export const resolutionExtendsDomain = (resolution, domain)=>{
107
- const domains = objectKeysOf(resolution);
108
- return domains.length === 1 && domains[0] === domain;
109
- };
110
- export const toArrayNode = (node)=>({
111
- object: {
112
- class: Array,
113
- props: {
114
- [mappedKeys.index]: node
115
- }
116
- }
117
- });
@@ -1,69 +0,0 @@
1
- import { listFrom } from "../utils/generics.js";
2
- import { isArray } from "../utils/objectKinds.js";
3
- import { branchIntersection, compareBranches, flattenBranch, isBranchComparison } from "./branch.js";
4
- import { equality, IntersectionState, isEquality } from "./compose.js";
5
- import { flattenBranches } from "./discriminate.js";
6
- const emptyRulesIfTrue = (predicate)=>predicate === true ? {} : predicate;
7
- export const comparePredicates = (l, r, context)=>{
8
- if (l === true && r === true) {
9
- return equality();
10
- }
11
- if (!isArray(l) && !isArray(r)) {
12
- const result = branchIntersection(emptyRulesIfTrue(l), emptyRulesIfTrue(r), context);
13
- return result === l ? l : result === r ? r : result;
14
- }
15
- const lBranches = listFrom(emptyRulesIfTrue(l));
16
- const rBranches = listFrom(emptyRulesIfTrue(r));
17
- const comparison = compareBranches(lBranches, rBranches, context);
18
- if (comparison.equalities.length === lBranches.length && comparison.equalities.length === rBranches.length) {
19
- return equality();
20
- }
21
- if (comparison.lExtendsR.length + comparison.equalities.length === lBranches.length) {
22
- return l;
23
- }
24
- if (comparison.rExtendsL.length + comparison.equalities.length === rBranches.length) {
25
- return r;
26
- }
27
- return comparison;
28
- };
29
- export const predicateIntersection = (domain, l, r, state)=>{
30
- state.domain = domain;
31
- const comparison = comparePredicates(l, r, state);
32
- if (!isBranchComparison(comparison)) {
33
- return comparison;
34
- }
35
- const resultBranches = [
36
- ...comparison.distinctIntersections,
37
- ...comparison.equalities.map((indices)=>comparison.lBranches[indices[0]]),
38
- ...comparison.lExtendsR.map((lIndex)=>comparison.lBranches[lIndex]),
39
- ...comparison.rExtendsL.map((rIndex)=>comparison.rBranches[rIndex])
40
- ];
41
- if (resultBranches.length === 0) {
42
- state.addDisjoint("union", comparison.lBranches, comparison.rBranches);
43
- }
44
- return resultBranches.length === 1 ? resultBranches[0] : resultBranches;
45
- };
46
- export const predicateUnion = (domain, l, r, type)=>{
47
- const state = new IntersectionState(type, "|");
48
- const comparison = comparePredicates(l, r, state);
49
- if (!isBranchComparison(comparison)) {
50
- return isEquality(comparison) || comparison === l ? r : comparison === r ? l : // subtype of the other, it consists of two opposite literals
51
- // and can be simplified to a non-literal boolean.
52
- domain === "boolean" ? true : [
53
- emptyRulesIfTrue(l),
54
- emptyRulesIfTrue(r)
55
- ];
56
- }
57
- const resultBranches = [
58
- ...comparison.lBranches.filter((_, lIndex)=>!comparison.lExtendsR.includes(lIndex) && !comparison.equalities.some((indexPair)=>indexPair[0] === lIndex)),
59
- ...comparison.rBranches.filter((_, rIndex)=>!comparison.rExtendsL.includes(rIndex) && !comparison.equalities.some((indexPair)=>indexPair[1] === rIndex))
60
- ];
61
- return resultBranches.length === 1 ? resultBranches[0] : resultBranches;
62
- };
63
- export const flattenPredicate = (predicate, context)=>{
64
- if (predicate === true) {
65
- return [];
66
- }
67
- return isArray(predicate) ? flattenBranches(predicate, context) : flattenBranch(predicate, context);
68
- };
69
- export const isLiteralCondition = (predicate)=>typeof predicate === "object" && "value" in predicate;
@@ -1,11 +0,0 @@
1
- import { objectKindOf } from "../../utils/objectKinds.js";
2
- import { composeIntersection, equality } from "../compose.js";
3
- export const classIntersection = composeIntersection((l, r, state)=>{
4
- return l === r ? equality() : l instanceof r ? l : r instanceof l ? r : state.addDisjoint("class", l, r);
5
- });
6
- export const checkClass = (expectedClass, state)=>{
7
- if (typeof expectedClass === "string") {
8
- return objectKindOf(state.data) === expectedClass || !state.problems.add("class", expectedClass);
9
- }
10
- return state.data instanceof expectedClass || !state.problems.add("class", expectedClass);
11
- };
@@ -1,34 +0,0 @@
1
- import { equality } from "../compose.js";
2
- export const collapsibleListUnion = (l, r)=>{
3
- if (Array.isArray(l)) {
4
- if (Array.isArray(r)) {
5
- const result = listUnion(l, r);
6
- return result.length === l.length ? result.length === r.length ? equality() : l : result.length === r.length ? r : result;
7
- }
8
- return l.includes(r) ? l : [
9
- ...l,
10
- r
11
- ];
12
- }
13
- if (Array.isArray(r)) {
14
- return r.includes(l) ? r : [
15
- ...r,
16
- l
17
- ];
18
- }
19
- return l === r ? equality() : [
20
- l,
21
- r
22
- ];
23
- };
24
- export const listUnion = (l, r)=>{
25
- const result = [
26
- ...l
27
- ];
28
- for (const expression of r){
29
- if (!l.includes(expression)) {
30
- result.push(expression);
31
- }
32
- }
33
- return result;
34
- };
@@ -1,15 +0,0 @@
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 = (divisor, state)=>state.data % divisor === 0 || !state.problems.add("divisor", divisor);