arktype 2.0.0-dev.1 → 2.0.0-dev.11

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 (221) hide show
  1. package/out/api.d.ts +6 -0
  2. package/out/api.js +5 -0
  3. package/out/ark.d.ts +15 -39
  4. package/out/ark.js +9 -18
  5. package/out/config.d.ts +1 -0
  6. package/out/config.js +2 -0
  7. package/out/generic.d.ts +21 -0
  8. package/out/generic.js +24 -0
  9. package/out/main.d.ts +6 -7
  10. package/out/main.js +4 -3
  11. package/out/match.d.ts +57 -34
  12. package/out/match.js +51 -17
  13. package/out/module.d.ts +12 -0
  14. package/out/module.js +3 -0
  15. package/out/parser/definition.d.ts +14 -14
  16. package/out/parser/definition.js +10 -13
  17. package/out/parser/generic.d.ts +5 -7
  18. package/out/parser/generic.js +7 -11
  19. package/out/parser/objectLiteral.d.ts +44 -18
  20. package/out/parser/objectLiteral.js +57 -51
  21. package/out/parser/semantic/bounds.d.ts +10 -8
  22. package/out/parser/semantic/bounds.js +0 -1
  23. package/out/parser/semantic/divisor.d.ts +5 -7
  24. package/out/parser/semantic/divisor.js +0 -1
  25. package/out/parser/semantic/infer.d.ts +24 -0
  26. package/out/parser/semantic/infer.js +1 -0
  27. package/out/parser/semantic/utils.d.ts +3 -7
  28. package/out/parser/semantic/utils.js +0 -1
  29. package/out/parser/semantic/validate.d.ts +16 -13
  30. package/out/parser/semantic/validate.js +1 -1
  31. package/out/parser/string/reduce/dynamic.d.ts +13 -13
  32. package/out/parser/string/reduce/dynamic.js +31 -26
  33. package/out/parser/string/reduce/shared.d.ts +14 -28
  34. package/out/parser/string/reduce/shared.js +4 -3
  35. package/out/parser/string/reduce/static.d.ts +27 -24
  36. package/out/parser/string/reduce/static.js +0 -1
  37. package/out/parser/string/shift/operand/date.d.ts +2 -2
  38. package/out/parser/string/shift/operand/date.js +4 -7
  39. package/out/parser/string/shift/operand/enclosed.d.ts +3 -4
  40. package/out/parser/string/shift/operand/enclosed.js +14 -14
  41. package/out/parser/string/shift/operand/genericArgs.d.ts +9 -10
  42. package/out/parser/string/shift/operand/genericArgs.js +6 -10
  43. package/out/parser/string/shift/operand/operand.d.ts +3 -4
  44. package/out/parser/string/shift/operand/operand.js +8 -12
  45. package/out/parser/string/shift/operand/unenclosed.d.ts +16 -21
  46. package/out/parser/string/shift/operand/unenclosed.js +24 -36
  47. package/out/parser/string/shift/operator/bounds.d.ts +8 -12
  48. package/out/parser/string/shift/operator/bounds.js +45 -56
  49. package/out/parser/string/shift/operator/divisor.d.ts +1 -3
  50. package/out/parser/string/shift/operator/divisor.js +1 -3
  51. package/out/parser/string/shift/operator/operator.d.ts +1 -2
  52. package/out/parser/string/shift/operator/operator.js +12 -19
  53. package/out/parser/string/shift/scanner.d.ts +2 -2
  54. package/out/parser/string/shift/scanner.js +14 -16
  55. package/out/parser/string/string.d.ts +8 -6
  56. package/out/parser/string/string.js +1 -3
  57. package/out/parser/tuple.d.ts +102 -43
  58. package/out/parser/tuple.js +119 -87
  59. package/out/scope.d.ts +44 -119
  60. package/out/scope.js +39 -209
  61. package/out/type.d.ts +43 -64
  62. package/out/type.js +30 -131
  63. package/package.json +12 -10
  64. package/__tests__/array.test.ts +0 -272
  65. package/__tests__/astUtils.test.ts +0 -17
  66. package/__tests__/badDefinitionType.test.ts +0 -51
  67. package/__tests__/basis.test.ts +0 -46
  68. package/__tests__/bounds.test.ts +0 -388
  69. package/__tests__/cast.test.ts +0 -32
  70. package/__tests__/completions.test.ts +0 -46
  71. package/__tests__/config.test.ts +0 -168
  72. package/__tests__/cyclic.test.ts +0 -144
  73. package/__tests__/dateLiteral.test.ts +0 -32
  74. package/__tests__/declared.test.ts +0 -123
  75. package/__tests__/discrimination.test.ts +0 -74
  76. package/__tests__/divisor.test.ts +0 -90
  77. package/__tests__/enclosed.test.ts +0 -93
  78. package/__tests__/examples.test.ts +0 -56
  79. package/__tests__/expressions.test.ts +0 -138
  80. package/__tests__/generateBenchData.ts +0 -89
  81. package/__tests__/generated/cyclic.ts +0 -3058
  82. package/__tests__/generic.test.ts +0 -294
  83. package/__tests__/group.test.ts +0 -72
  84. package/__tests__/hkt.test.ts +0 -22
  85. package/__tests__/imports.test.ts +0 -113
  86. package/__tests__/instanceof.test.ts +0 -102
  87. package/__tests__/intersection.test.ts +0 -104
  88. package/__tests__/jsdoc.test.ts +0 -64
  89. package/__tests__/keyTraversal.test.ts +0 -73
  90. package/__tests__/keyof.test.ts +0 -134
  91. package/__tests__/keywords.test.ts +0 -188
  92. package/__tests__/literal.test.ts +0 -51
  93. package/__tests__/match.test.ts +0 -34
  94. package/__tests__/methods.bench.ts +0 -22
  95. package/__tests__/morph.test.ts +0 -409
  96. package/__tests__/narrow.test.ts +0 -102
  97. package/__tests__/nodeDefinitions.test.ts +0 -190
  98. package/__tests__/object.bench.ts +0 -28
  99. package/__tests__/objectLiteral.test.ts +0 -300
  100. package/__tests__/operand.bench.ts +0 -45
  101. package/__tests__/operator.bench.ts +0 -130
  102. package/__tests__/regex.test.ts +0 -58
  103. package/__tests__/scope.bench.ts +0 -39
  104. package/__tests__/scope.test.ts +0 -140
  105. package/__tests__/string.test.ts +0 -48
  106. package/__tests__/submodule.test.ts +0 -99
  107. package/__tests__/this.test.ts +0 -57
  108. package/__tests__/thunk.test.ts +0 -80
  109. package/__tests__/traverse.test.ts +0 -119
  110. package/__tests__/tsGenerics.test.ts +0 -12
  111. package/__tests__/typeMethods.test.ts +0 -69
  112. package/__tests__/typeReference.test.ts +0 -39
  113. package/__tests__/unenclosed.test.ts +0 -120
  114. package/__tests__/union.test.ts +0 -147
  115. package/ark.ts +0 -91
  116. package/main.ts +0 -18
  117. package/match.ts +0 -116
  118. package/out/ark.d.ts.map +0 -1
  119. package/out/ark.js.map +0 -1
  120. package/out/arkConfig.d.ts +0 -2
  121. package/out/arkConfig.d.ts.map +0 -1
  122. package/out/arkConfig.js +0 -10
  123. package/out/arkConfig.js.map +0 -1
  124. package/out/main.d.ts.map +0 -1
  125. package/out/main.js.map +0 -1
  126. package/out/match.d.ts.map +0 -1
  127. package/out/match.js.map +0 -1
  128. package/out/parser/definition.d.ts.map +0 -1
  129. package/out/parser/definition.js.map +0 -1
  130. package/out/parser/generic.d.ts.map +0 -1
  131. package/out/parser/generic.js.map +0 -1
  132. package/out/parser/objectLiteral.d.ts.map +0 -1
  133. package/out/parser/objectLiteral.js.map +0 -1
  134. package/out/parser/semantic/bounds.d.ts.map +0 -1
  135. package/out/parser/semantic/bounds.js.map +0 -1
  136. package/out/parser/semantic/divisor.d.ts.map +0 -1
  137. package/out/parser/semantic/divisor.js.map +0 -1
  138. package/out/parser/semantic/intersections.d.ts +0 -14
  139. package/out/parser/semantic/intersections.d.ts.map +0 -1
  140. package/out/parser/semantic/intersections.js +0 -2
  141. package/out/parser/semantic/intersections.js.map +0 -1
  142. package/out/parser/semantic/semantic.d.ts +0 -33
  143. package/out/parser/semantic/semantic.d.ts.map +0 -1
  144. package/out/parser/semantic/semantic.js +0 -2
  145. package/out/parser/semantic/semantic.js.map +0 -1
  146. package/out/parser/semantic/utils.d.ts.map +0 -1
  147. package/out/parser/semantic/utils.js.map +0 -1
  148. package/out/parser/semantic/validate.d.ts.map +0 -1
  149. package/out/parser/semantic/validate.js.map +0 -1
  150. package/out/parser/shared.d.ts +0 -54
  151. package/out/parser/shared.d.ts.map +0 -1
  152. package/out/parser/shared.js +0 -47
  153. package/out/parser/shared.js.map +0 -1
  154. package/out/parser/string/reduce/dynamic.d.ts.map +0 -1
  155. package/out/parser/string/reduce/dynamic.js.map +0 -1
  156. package/out/parser/string/reduce/shared.d.ts.map +0 -1
  157. package/out/parser/string/reduce/shared.js.map +0 -1
  158. package/out/parser/string/reduce/static.d.ts.map +0 -1
  159. package/out/parser/string/reduce/static.js.map +0 -1
  160. package/out/parser/string/shift/operand/date.d.ts.map +0 -1
  161. package/out/parser/string/shift/operand/date.js.map +0 -1
  162. package/out/parser/string/shift/operand/enclosed.d.ts.map +0 -1
  163. package/out/parser/string/shift/operand/enclosed.js.map +0 -1
  164. package/out/parser/string/shift/operand/genericArgs.d.ts.map +0 -1
  165. package/out/parser/string/shift/operand/genericArgs.js.map +0 -1
  166. package/out/parser/string/shift/operand/operand.d.ts.map +0 -1
  167. package/out/parser/string/shift/operand/operand.js.map +0 -1
  168. package/out/parser/string/shift/operand/unenclosed.d.ts.map +0 -1
  169. package/out/parser/string/shift/operand/unenclosed.js.map +0 -1
  170. package/out/parser/string/shift/operator/bounds.d.ts.map +0 -1
  171. package/out/parser/string/shift/operator/bounds.js.map +0 -1
  172. package/out/parser/string/shift/operator/divisor.d.ts.map +0 -1
  173. package/out/parser/string/shift/operator/divisor.js.map +0 -1
  174. package/out/parser/string/shift/operator/operator.d.ts.map +0 -1
  175. package/out/parser/string/shift/operator/operator.js.map +0 -1
  176. package/out/parser/string/shift/scanner.d.ts.map +0 -1
  177. package/out/parser/string/shift/scanner.js.map +0 -1
  178. package/out/parser/string/string.d.ts.map +0 -1
  179. package/out/parser/string/string.js.map +0 -1
  180. package/out/parser/tuple.d.ts.map +0 -1
  181. package/out/parser/tuple.js.map +0 -1
  182. package/out/scope.d.ts.map +0 -1
  183. package/out/scope.js.map +0 -1
  184. package/out/test.d.ts +0 -2
  185. package/out/test.d.ts.map +0 -1
  186. package/out/test.js +0 -7
  187. package/out/test.js.map +0 -1
  188. package/out/tsconfig.build.tsbuildinfo +0 -1
  189. package/out/type.d.ts.map +0 -1
  190. package/out/type.js.map +0 -1
  191. package/out/util.d.ts +0 -19
  192. package/out/util.d.ts.map +0 -1
  193. package/out/util.js +0 -7
  194. package/out/util.js.map +0 -1
  195. package/parser/definition.ts +0 -159
  196. package/parser/generic.ts +0 -68
  197. package/parser/objectLiteral.ts +0 -197
  198. package/parser/semantic/bounds.ts +0 -61
  199. package/parser/semantic/divisor.ts +0 -13
  200. package/parser/semantic/intersections.ts +0 -46
  201. package/parser/semantic/semantic.ts +0 -144
  202. package/parser/semantic/utils.ts +0 -26
  203. package/parser/semantic/validate.ts +0 -109
  204. package/parser/shared.ts +0 -152
  205. package/parser/string/reduce/dynamic.ts +0 -196
  206. package/parser/string/reduce/shared.ts +0 -101
  207. package/parser/string/reduce/static.ts +0 -298
  208. package/parser/string/shift/operand/date.ts +0 -54
  209. package/parser/string/shift/operand/enclosed.ts +0 -118
  210. package/parser/string/shift/operand/genericArgs.ts +0 -127
  211. package/parser/string/shift/operand/operand.ts +0 -48
  212. package/parser/string/shift/operand/unenclosed.ts +0 -268
  213. package/parser/string/shift/operator/bounds.ts +0 -264
  214. package/parser/string/shift/operator/divisor.ts +0 -36
  215. package/parser/string/shift/operator/operator.ts +0 -82
  216. package/parser/string/shift/scanner.ts +0 -209
  217. package/parser/string/string.ts +0 -90
  218. package/parser/tuple.ts +0 -474
  219. package/scope.ts +0 -574
  220. package/type.ts +0 -347
  221. package/util.ts +0 -36
@@ -1,114 +1,145 @@
1
- import { keywords, schema } from "@arktype/schema";
2
- import { isArray, objectKindOrDomainOf, printable, throwParseError } from "@arktype/util";
3
- import { writeUnsatisfiableExpressionError } from "./semantic/validate.js";
4
- import { parseEntry } from "./shared.js";
1
+ import { jsObjects, makeRootAndArrayPropertiesMutable, tsKeywords } from "@arktype/schema";
2
+ import { append, objectKindOrDomainOf, throwParseError } from "@arktype/util";
5
3
  import { writeMissingRightOperandMessage } from "./string/shift/operand/unenclosed.js";
6
4
  export const parseTuple = (def, ctx) => maybeParseTupleExpression(def, ctx) ?? parseTupleLiteral(def, ctx);
7
5
  export const parseTupleLiteral = (def, ctx) => {
8
- const props = [];
9
- let isVariadic = false;
10
- for (let i = 0; i < def.length; i++) {
11
- let elementDef = def[i];
12
- ctx.path.push(`${i}`);
13
- if (typeof elementDef === "string" && elementDef.startsWith("...")) {
14
- elementDef = elementDef.slice(3);
15
- isVariadic = true;
6
+ let sequences = [{}];
7
+ let i = 0;
8
+ while (i < def.length) {
9
+ let spread = false;
10
+ let optional = false;
11
+ if (def[i] === "..." && i < def.length - 1) {
12
+ spread = true;
13
+ i++;
16
14
  }
17
- else if (isArray(elementDef) &&
18
- elementDef.length === 2 &&
19
- elementDef[0] === "...") {
20
- elementDef = elementDef[1];
21
- isVariadic = true;
15
+ const element = ctx.$.parse(def[i], ctx);
16
+ i++;
17
+ if (def[i] === "?") {
18
+ if (spread)
19
+ return throwParseError(spreadOptionalMessage);
20
+ optional = true;
21
+ i++;
22
22
  }
23
- const parsedEntry = parseEntry([`${i}`, elementDef]);
24
- const value = ctx.scope.parse(parsedEntry.innerValue, ctx);
25
- if (isVariadic) {
26
- if (!value.extends(keywords.Array)) {
27
- return throwParseError(writeNonArrayRestMessage(elementDef));
28
- }
29
- if (i !== def.length - 1) {
30
- return throwParseError(prematureRestMessage);
31
- }
32
- // TODO: Fix builtins.arrayIndexTypeNode()
33
- const elementType = value.getPath();
34
- // TODO: first variadic i
35
- props.push({ key: keywords.number, value: elementType });
23
+ if (spread) {
24
+ if (!element.extends(jsObjects.Array))
25
+ return throwParseError(writeNonArraySpreadMessage(element.expression));
26
+ // a spread must be distributed over branches e.g.:
27
+ // def: [string, ...(number[] | [true, false])]
28
+ // nodes: [string, ...number[]] | [string, true, false]
29
+ sequences = sequences.flatMap(base =>
30
+ // since appendElement mutates base, we have to shallow-ish clone it for each branch
31
+ element.branches.map(branch => appendSpreadBranch(makeRootAndArrayPropertiesMutable(base), branch)));
36
32
  }
37
33
  else {
38
- props.push({
39
- key: {
40
- name: `${i}`,
41
- prerequisite: false,
42
- optional: parsedEntry.kind === "optional"
43
- },
44
- value
45
- });
34
+ sequences = sequences.map(base => appendElement(base, optional ? "optional" : "required", element));
46
35
  }
47
- ctx.path.pop();
48
36
  }
49
- if (!isVariadic) {
50
- props.push({
51
- key: {
52
- name: "length",
53
- prerequisite: true,
54
- optional: false
55
- },
56
- // , ctx
57
- value: schema({ unit: def.length })
58
- });
37
+ return ctx.$.raw.schema(sequences.map(sequence => ({
38
+ proto: Array,
39
+ sequence
40
+ })));
41
+ };
42
+ const appendElement = (base, kind, element) => {
43
+ switch (kind) {
44
+ case "required":
45
+ if (base.optionals)
46
+ // e.g. [string?, number]
47
+ return throwParseError(requiredPostOptionalMessage);
48
+ if (base.variadic) {
49
+ // e.g. [...string[], number]
50
+ base.postfix = append(base.postfix, element);
51
+ }
52
+ else {
53
+ // e.g. [string, number]
54
+ base.prefix = append(base.prefix, element);
55
+ }
56
+ return base;
57
+ case "optional":
58
+ if (base.variadic)
59
+ // e.g. [...string[], number?]
60
+ return throwParseError(optionalPostVariadicMessage);
61
+ // e.g. [string, number?]
62
+ base.optionals = append(base.optionals, element);
63
+ return base;
64
+ case "variadic":
65
+ // e.g. [...string[], number, ...string[]]
66
+ if (base.postfix)
67
+ throwParseError(multipleVariadicMesage);
68
+ if (base.variadic) {
69
+ if (!base.variadic.equals(element)) {
70
+ // e.g. [...string[], ...number[]]
71
+ throwParseError(multipleVariadicMesage);
72
+ }
73
+ // e.g. [...string[], ...string[]]
74
+ // do nothing, second spread doesn't change the type
75
+ }
76
+ else {
77
+ // e.g. [string, ...number[]]
78
+ base.variadic = element.raw;
79
+ }
80
+ return base;
81
+ }
82
+ };
83
+ const appendSpreadBranch = (base, branch) => {
84
+ const spread = branch.firstReferenceOfKind("sequence");
85
+ if (!spread) {
86
+ // the only array with no sequence reference is unknown[]
87
+ return appendElement(base, "variadic", tsKeywords.unknown);
59
88
  }
60
- // props , ctx
61
- return schema(Array);
89
+ spread.prefix.forEach(node => appendElement(base, "required", node));
90
+ spread.optionals.forEach(node => appendElement(base, "optional", node));
91
+ spread.variadic && appendElement(base, "variadic", spread.variadic);
92
+ spread.postfix.forEach(node => appendElement(base, "required", node));
93
+ return base;
62
94
  };
63
- export const maybeParseTupleExpression = (def, ctx) => {
64
- const tupleExpressionResult = isIndexOneExpression(def)
65
- ? indexOneParsers[def[1]](def, ctx)
66
- : isIndexZeroExpression(def)
67
- ? prefixParsers[def[0]](def, ctx)
95
+ const maybeParseTupleExpression = (def, ctx) => {
96
+ const tupleExpressionResult = isIndexZeroExpression(def) ? prefixParsers[def[0]](def, ctx)
97
+ : isIndexOneExpression(def) ? indexOneParsers[def[1]](def, ctx)
68
98
  : undefined;
69
- if (tupleExpressionResult) {
70
- return tupleExpressionResult.isNever()
71
- ? throwParseError(writeUnsatisfiableExpressionError(def
72
- .map((def) => (typeof def === "string" ? def : printable(def)))
73
- .join(" ")))
74
- : tupleExpressionResult;
75
- }
99
+ return tupleExpressionResult;
100
+ // TODO: remove
101
+ // return tupleExpressionResult.isNever()
102
+ // ? throwParseError(
103
+ // writeUnsatisfiableExpressionError(
104
+ // def
105
+ // .map((def) =>
106
+ // typeof def === "string" ? def : printable(def)
107
+ // )
108
+ // .join(" ")
109
+ // )
110
+ // )
111
+ // : tupleExpressionResult
76
112
  };
77
- export const writeNonArrayRestMessage = (operand) => `Rest element ${typeof operand === "string" ? `'${operand}'` : ""} must be an array`;
78
- export const prematureRestMessage = `Rest elements are only allowed at the end of a tuple`;
79
- export const parseKeyOfTuple = (def, ctx) => ctx.scope.parse(def[1], ctx).keyof();
113
+ export const writeNonArraySpreadMessage = (operand) => `Spread element must be an array (was ${operand})`;
114
+ export const multipleVariadicMesage = "A tuple may have at most one variadic element";
115
+ export const requiredPostOptionalMessage = "A required element may not follow an optional element";
116
+ export const optionalPostVariadicMessage = "An optional element may not follow a variadic element";
117
+ export const spreadOptionalMessage = "A spread element cannot be optional";
118
+ export const parseKeyOfTuple = (def, ctx) => ctx.$.parse(def[1], ctx).keyof();
80
119
  const parseBranchTuple = (def, ctx) => {
81
- if (def[2] === undefined) {
120
+ if (def[2] === undefined)
82
121
  return throwParseError(writeMissingRightOperandMessage(def[1], ""));
83
- }
84
- const l = ctx.scope.parse(def[0], ctx);
85
- const r = ctx.scope.parse(def[2], ctx);
122
+ const l = ctx.$.parse(def[0], ctx);
123
+ const r = ctx.$.parse(def[2], ctx);
86
124
  return def[1] === "&" ? l.and(r) : l.or(r);
87
125
  };
88
- const parseArrayTuple = (def, ctx) => ctx.scope.parse(def[0], ctx).array();
126
+ const parseArrayTuple = (def, ctx) => ctx.$.parse(def[0], ctx).array();
89
127
  const isIndexOneExpression = (def) => indexOneParsers[def[1]] !== undefined;
90
128
  export const parseMorphTuple = (def, ctx) => {
91
129
  if (typeof def[2] !== "function") {
92
130
  return throwParseError(writeMalformedFunctionalExpressionMessage("=>", def[2]));
93
131
  }
94
132
  // TODO: nested morphs?
95
- return schema({
96
- in: ctx.scope.parse(def[0], ctx),
97
- morph: def[2]
98
- });
133
+ return ctx.$.parse(def[0], ctx).pipe(def[2]);
99
134
  };
100
135
  export const writeMalformedFunctionalExpressionMessage = (operator, value) => `${operator === ":" ? "Narrow" : "Morph"} expression requires a function following '${operator}' (was ${typeof value})`;
101
136
  export const parseNarrowTuple = (def, ctx) => {
102
137
  if (typeof def[2] !== "function") {
103
138
  return throwParseError(writeMalformedFunctionalExpressionMessage(":", def[2]));
104
139
  }
105
- return ctx.scope
106
- .parse(def[0], ctx)
107
- .constrain("predicate", def[2]);
108
- };
109
- const parseAttributeTuple = (def, ctx) => {
110
- return ctx.scope.parse(def[0], ctx);
140
+ return ctx.$.parse(def[0], ctx).constrain("predicate", def[2]);
111
141
  };
142
+ const parseAttributeTuple = (def, ctx) => ctx.$.parse(def[0], ctx).configureShallowDescendants(def[2]);
112
143
  const indexOneParsers = {
113
144
  "|": parseBranchTuple,
114
145
  "&": parseBranchTuple,
@@ -119,19 +150,20 @@ const indexOneParsers = {
119
150
  };
120
151
  const prefixParsers = {
121
152
  keyof: parseKeyOfTuple,
122
- instanceof: (def) => {
153
+ instanceof: (def, ctx) => {
123
154
  if (typeof def[1] !== "function") {
124
155
  return throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(def[1])));
125
156
  }
126
157
  const branches = def
127
158
  .slice(1)
128
- .map((ctor) => typeof ctor === "function"
129
- ? { proto: ctor }
159
+ .map(ctor => typeof ctor === "function" ?
160
+ ctx.$.node("proto", { proto: ctor })
130
161
  : throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(ctor))));
131
- return schema(...branches);
162
+ return branches.length === 1 ?
163
+ branches[0]
164
+ : ctx.$.node("union", { branches });
132
165
  },
133
- "===": (def) => schema.units(...def.slice(1))
166
+ "===": (def, ctx) => ctx.$.units(def.slice(1))
134
167
  };
135
168
  const isIndexZeroExpression = (def) => prefixParsers[def[0]] !== undefined;
136
169
  export const writeInvalidConstructorMessage = (actual) => `Expected a constructor following 'instanceof' operator (was ${actual})`;
137
- //# sourceMappingURL=tuple.js.map
package/out/scope.d.ts CHANGED
@@ -1,35 +1,15 @@
1
- import { type ArkErrorCode, type KeyCheckKind, type TypeNode, type extractIn, type extractOut } from "@arktype/schema";
2
- import { type Dict, type evaluate, type isAny, type nominal } from "@arktype/util";
1
+ import { RawRootScope, type ArkConfig, type BaseRoot, type GenericProps, type PreparsedNodeResolution, type PrivateDeclaration, type RawRootResolutions, type RootScope, type UnknownRoot, type ambient, type arkKind, type destructuredExportContext, type destructuredImportContext, type exportedNameOf, type writeDuplicateAliasError } from "@arktype/schema";
2
+ import { type anyOrNever, type keyError, type nominal, type show } from "@arktype/util";
3
3
  import type { type } from "./ark.js";
4
+ import { Generic } from "./generic.js";
4
5
  import { type MatchParser } from "./match.js";
6
+ import type { Module } from "./module.js";
5
7
  import { type inferDefinition, type validateDefinition } from "./parser/definition.js";
6
8
  import { parseGenericParams, type GenericDeclaration, type GenericParamsParseError } from "./parser/generic.js";
7
- import { Type, type DeclarationParser, type DefinitionParser, type Generic, type GenericProps, type TypeConfig, type TypeParser } from "./type.js";
8
- import { type arkKind } from "./util.js";
9
- export type ScopeParser<parent, ambient> = {
10
- <const def>(def: validateScope<def, parent & ambient>): Scope<{
11
- exports: inferBootstrapped<{
12
- exports: bootstrapExports<def>;
13
- locals: bootstrapLocals<def> & parent;
14
- ambient: ambient;
15
- }>;
16
- locals: inferBootstrapped<{
17
- exports: bootstrapLocals<def>;
18
- locals: bootstrapExports<def> & parent;
19
- ambient: ambient;
20
- }>;
21
- ambient: ambient;
22
- }>;
23
- };
24
- export type ScopeConfig = {
25
- ambient?: Scope | null;
26
- codes?: Record<ArkErrorCode, {
27
- mustBe?: string;
28
- }>;
29
- keys?: KeyCheckKind;
30
- };
31
- type validateScope<def, $> = {
32
- [k in keyof def]: parseScopeKey<k>["params"] extends [] ? def[k] extends Type | PreparsedResolution ? def[k] : validateDefinition<def[k], $ & bootstrap<def>, {}> : parseScopeKey<k>["params"] extends GenericParamsParseError ? parseScopeKey<k>["params"][0] : validateDefinition<def[k], $ & bootstrap<def>, {
9
+ import { RawTypeParser, type DeclarationParser, type DefinitionParser, type Type, type TypeParser } from "./type.js";
10
+ export type ScopeParser = <const def>(def: validateScope<def>, config?: ArkConfig) => Scope<inferBootstrapped<bootstrapAliases<def>>>;
11
+ type validateScope<def> = {
12
+ [k in keyof def]: k extends symbol ? unknown : parseScopeKey<k>["params"] extends [] ? def[k] extends Type | PreparsedResolution ? def[k] : k extends PrivateDeclaration<infer name extends keyof def & string> ? keyError<writeDuplicateAliasError<name>> : validateDefinition<def[k], ambient & bootstrapAliases<def>, {}> : parseScopeKey<k>["params"] extends GenericParamsParseError ? parseScopeKey<k>["params"][0] : validateDefinition<def[k], ambient & bootstrapAliases<def>, {
33
13
  [param in parseScopeKey<k>["params"][number]]: unknown;
34
14
  }>;
35
15
  };
@@ -40,120 +20,65 @@ export type bindThis<def> = {
40
20
  type Def<def = {}> = nominal<def, "unparsed">;
41
21
  /** sentinel indicating a scope that will be associated with a generic has not yet been parsed */
42
22
  export type UnparsedScope = "$";
43
- type bootstrap<def> = bootstrapLocals<def> & bootstrapExports<def>;
44
- type bootstrapLocals<def> = bootstrapAliases<{
45
- [k in keyof def & PrivateDeclaration as extractPrivateKey<k>]: def[k];
46
- }>;
47
- type bootstrapExports<def> = bootstrapAliases<{
48
- [k in Exclude<keyof def, PrivateDeclaration>]: def[k];
49
- }>;
50
23
  /** These are legal as values of a scope but not as definitions in other contexts */
51
- type PreparsedResolution = Module | GenericProps;
24
+ type PreparsedResolution = PreparsedNodeResolution;
52
25
  type bootstrapAliases<def> = {
53
26
  [k in Exclude<keyof def, GenericDeclaration | symbol>]: def[k] extends PreparsedResolution ? def[k] : def[k] extends (() => infer thunkReturn extends PreparsedResolution) ? thunkReturn : Def<def[k]>;
54
27
  } & {
55
- [k in keyof def & GenericDeclaration as extractGenericName<k>]: Generic<parseGenericParams<extractGenericParameters<k>>, def[k], UnparsedScope>;
28
+ [k in keyof def & GenericDeclaration as extractGenericName<k>]: GenericProps<parseGenericParams<extractGenericParameters<k>>, def[k], UnparsedScope>;
56
29
  };
57
- type inferBootstrapped<r extends Resolutions> = evaluate<{
58
- [name in keyof r["exports"]]: r["exports"][name] extends Def<infer def> ? inferDefinition<def, $<r>, {}> : r["exports"][name] extends GenericProps<infer params, infer def> ? Generic<params, def, $<r>> : r["exports"][name];
30
+ type inferBootstrapped<$> = show<{
31
+ [name in keyof $]: $[name] extends Def<infer def> ? inferDefinition<def, $ & ambient, {}> : $[name] extends GenericProps<infer params, infer def> ? Generic<params, def, $> : $[name];
59
32
  }>;
60
33
  type extractGenericName<k> = k extends GenericDeclaration<infer name> ? name : never;
61
34
  type extractGenericParameters<k> = k extends GenericDeclaration<string, infer params> ? params : never;
62
- type extractPrivateKey<k> = k extends PrivateDeclaration<infer key> ? key : never;
63
- type PrivateDeclaration<key extends string = string> = `#${key}`;
64
- export type resolve<reference extends keyof $ | keyof args, $, args> = (reference extends keyof args ? args[reference] : $[reference & keyof $]) extends infer resolution ? [resolution] extends [never] ? never : isAny<resolution> extends true ? any : resolution extends Def<infer def> ? inferDefinition<def, $, args> : resolution : never;
35
+ export type resolve<reference extends keyof $ | keyof args, $, args> = (reference extends keyof args ? args[reference] : $[reference & keyof $]) extends infer resolution ? [
36
+ resolution
37
+ ] extends [anyOrNever] ? resolution : resolution extends Def<infer def> ? inferDefinition<def, $, args> : resolution : never;
65
38
  export type moduleKeyOf<$> = {
66
- [k in keyof $]: $[k] extends Module ? k & string : never;
39
+ [k in keyof $]: $[k] extends {
40
+ [arkKind]: "module";
41
+ } ? k & string : never;
67
42
  }[keyof $];
68
- export type tryInferSubmoduleReference<$, token> = token extends `${infer submodule extends moduleKeyOf<$>}.${infer subalias}` ? subalias extends keyof $[submodule] ? $[submodule][subalias] extends Type<infer t> ? t : never : never : never;
69
- type $<r extends Resolutions> = r["exports"] & r["locals"] & r["ambient"];
70
- type exportedName<r extends Resolutions> = keyof r["exports"] & string;
71
- export type Module<r extends Resolutions = any> = {
72
- [k in exportedName<r> | arkKind]: k extends string ? [r["exports"][k]] extends [never] ? Type<never, $<r>> : isAny<r["exports"][k]> extends true ? Type<any, $<r>> : r["exports"][k] extends PreparsedResolution ? r["exports"][k] : Type<r["exports"][k], $<r>> : type.cast<"module">;
73
- };
74
- export type Resolutions = {
75
- exports: unknown;
76
- locals: unknown;
77
- ambient: unknown;
78
- };
79
- export type ParseContext = {
80
- baseName: string;
81
- path: string[];
82
- scope: Scope;
83
- args: Record<string, TypeNode> | undefined;
84
- };
85
- type ParseContextInput = Pick<ParseContext, "baseName" | "args">;
86
- export declare class Scope<r extends Resolutions = any> {
87
- infer: extractOut<r["exports"]>;
88
- inferIn: extractIn<r["exports"]>;
89
- config: TypeConfig;
43
+ export type tryInferSubmoduleReference<$, token> = token extends `${infer submodule extends moduleKeyOf<$>}.${infer subalias}` ? subalias extends keyof $[submodule] ? $[submodule][subalias] extends type.cast<infer t> ? t : never : never : never;
44
+ export interface ParseContext {
45
+ $: RawScope;
46
+ args?: Record<string, UnknownRoot>;
47
+ }
48
+ export declare const scope: ScopeParser;
49
+ export interface Scope<$ = any> extends RootScope<$> {
50
+ type: TypeParser<$>;
51
+ match: MatchParser<$>;
52
+ declare: DeclarationParser<$>;
53
+ define: DefinitionParser<$>;
54
+ import<names extends exportedNameOf<$>[]>(...names: names): Module<show<destructuredImportContext<$, names>>>;
55
+ export<names extends exportedNameOf<$>[]>(...names: names): Module<show<destructuredExportContext<$, names>>>;
56
+ }
57
+ export declare class RawScope<$ extends RawRootResolutions = RawRootResolutions> extends RawRootScope<$> {
90
58
  private parseCache;
91
- private resolutions;
92
- /** The set of names defined at the root-level of the scope mapped to their
93
- * corresponding definitions.**/
94
- aliases: Record<string, unknown>;
95
- private exportedNames;
96
- private ambient;
97
- constructor(def: Dict, config: ScopeConfig);
98
- static root: ScopeParser<{}, {}>;
99
- type: TypeParser<$<r>>;
100
- match: MatchParser<$<r>>;
101
- declare: DeclarationParser<$<r>>;
102
- scope: ScopeParser<r["exports"], r["ambient"]>;
103
- define: DefinitionParser<$<r>>;
104
- toAmbient(): Scope<{
105
- exports: r["exports"];
106
- locals: r["locals"];
107
- ambient: r["exports"];
108
- }>;
109
- get<name extends keyof r["exports"] & string>(name: name): Type<r["exports"][name], $<r>>;
110
- private createRootContext;
111
- parseDefinition(def: unknown, input: ParseContextInput): TypeNode;
112
- parse(def: unknown, ctx: ParseContext): TypeNode;
113
- parseString(def: string, ctx: ParseContext): TypeNode;
114
- maybeResolve(name: string): TypeNode | Generic | undefined;
115
- /** If name is a valid reference to a submodule alias, return its resolution */
116
- private maybeResolveSubalias;
117
- maybeResolveNode(name: string): TypeNode | undefined;
118
- import<names extends exportedName<r>[]>(...names: names): destructuredImportContext<r, names extends [] ? keyof r["exports"] & string : names[number]>;
119
- compile(): string;
120
- bindThis(): {
121
- this: import("@arktype/schema").IntersectionNode<unknown>;
59
+ constructor(def: Record<string, unknown>, config?: ArkConfig);
60
+ type: RawTypeParser;
61
+ match: MatchParser<$>;
62
+ declare: () => {
63
+ type: RawTypeParser;
122
64
  };
123
- private exportedResolutions;
124
- private exportCache;
125
- export<names extends exportedName<r>[]>(...names: names): Module<names extends [] ? r : destructuredExportContext<r, names[number]>>;
65
+ define: (def: unknown) => unknown;
66
+ preparseRoot(def: unknown): unknown;
67
+ parseRoot(def: unknown): BaseRoot;
68
+ parse(def: unknown, ctx: ParseContext): BaseRoot;
69
+ parseString(def: string, ctx: ParseContext): BaseRoot;
126
70
  }
127
- type destructuredExportContext<r extends Resolutions, name extends exportedName<r>> = {
128
- exports: {
129
- [k in name]: r["exports"][k];
130
- };
131
- locals: r["locals"] & {
132
- [k in Exclude<keyof r["exports"], name>]: r["exports"][k];
133
- };
134
- ambient: r["ambient"];
135
- };
136
- type destructuredImportContext<r extends Resolutions, name extends exportedName<r>> = {
137
- [k in name as `#${k & string}`]: type.cast<r["exports"][k]>;
138
- };
139
71
  export declare const writeShallowCycleErrorMessage: (name: string, seen: string[]) => string;
140
- export declare const writeDuplicateNameMessage: <name extends string>(name: name) => `Duplicate name '${name}'`;
141
- type writeDuplicateNameMessage<name extends string> = `Duplicate name '${name}'`;
142
72
  export type ParsedScopeKey = {
143
- isLocal: boolean;
144
73
  name: string;
145
74
  params: string[];
146
75
  };
147
76
  export declare const parseScopeKey: (k: string) => ParsedScopeKey;
148
- type parseScopeKey<k> = k extends PrivateDeclaration<infer inner> ? parsePossibleGenericDeclaration<inner, true> : parsePossibleGenericDeclaration<k, false>;
149
- type parsePossibleGenericDeclaration<k, isLocal extends boolean> = k extends GenericDeclaration<infer name, infer paramString> ? {
150
- isLocal: isLocal;
77
+ export type parseScopeKey<k> = k extends GenericDeclaration<infer name, infer paramString> ? {
151
78
  name: name;
152
79
  params: parseGenericParams<paramString>;
153
80
  } : {
154
- isLocal: isLocal;
155
81
  name: k;
156
82
  params: [];
157
83
  };
158
84
  export {};
159
- //# sourceMappingURL=scope.d.ts.map