arktype 1.1.0-dev-2 → 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/LICENSE +7 -0
  2. package/out/ark.d.ts +24 -0
  3. package/out/ark.js +8 -0
  4. package/out/config.d.ts +1 -0
  5. package/out/config.js +2 -0
  6. package/out/generic.d.ts +54 -0
  7. package/out/generic.js +39 -0
  8. package/out/index.d.ts +6 -0
  9. package/out/index.js +5 -0
  10. package/out/match.d.ts +71 -0
  11. package/out/match.js +50 -0
  12. package/out/module.d.ts +11 -0
  13. package/out/module.js +2 -0
  14. package/{dist → out}/parser/definition.d.ts +16 -16
  15. package/{dist → out}/parser/definition.js +12 -12
  16. package/out/parser/objectLiteral.d.ts +79 -0
  17. package/out/parser/objectLiteral.js +100 -0
  18. package/out/parser/semantic/bounds.d.ts +15 -0
  19. package/{dist → out}/parser/semantic/bounds.js +0 -1
  20. package/out/parser/semantic/default.d.ts +8 -0
  21. package/out/parser/semantic/default.js +1 -0
  22. package/out/parser/semantic/divisor.d.ts +7 -0
  23. package/out/parser/semantic/divisor.js +1 -0
  24. package/out/parser/semantic/infer.d.ts +25 -0
  25. package/out/parser/semantic/infer.js +1 -0
  26. package/out/parser/semantic/utils.d.ts +4 -0
  27. package/out/parser/semantic/utils.js +1 -0
  28. package/out/parser/semantic/validate.d.ts +30 -0
  29. package/out/parser/semantic/validate.js +2 -0
  30. package/out/parser/string/reduce/dynamic.d.ts +43 -0
  31. package/{dist → out}/parser/string/reduce/dynamic.js +50 -33
  32. package/out/parser/string/reduce/shared.d.ts +42 -0
  33. package/{dist → out}/parser/string/reduce/shared.js +22 -2
  34. package/{dist → out}/parser/string/reduce/static.d.ts +29 -27
  35. package/out/parser/string/reduce/static.js +1 -0
  36. package/out/parser/string/shift/operand/date.d.ts +9 -0
  37. package/{dist → out}/parser/string/shift/operand/date.js +5 -8
  38. package/{dist → out}/parser/string/shift/operand/enclosed.d.ts +5 -16
  39. package/{dist → out}/parser/string/shift/operand/enclosed.js +15 -15
  40. package/out/parser/string/shift/operand/genericArgs.d.ts +28 -0
  41. package/out/parser/string/shift/operand/genericArgs.js +16 -0
  42. package/out/parser/string/shift/operand/operand.d.ts +9 -0
  43. package/out/parser/string/shift/operand/operand.js +12 -0
  44. package/out/parser/string/shift/operand/unenclosed.d.ts +30 -0
  45. package/out/parser/string/shift/operand/unenclosed.js +53 -0
  46. package/out/parser/string/shift/operator/bounds.d.ts +27 -0
  47. package/out/parser/string/shift/operator/bounds.js +94 -0
  48. package/out/parser/string/shift/operator/default.d.ts +24 -0
  49. package/out/parser/string/shift/operator/default.js +23 -0
  50. package/{dist → out}/parser/string/shift/operator/divisor.d.ts +2 -4
  51. package/{dist → out}/parser/string/shift/operator/divisor.js +2 -4
  52. package/{dist → out}/parser/string/shift/operator/operator.d.ts +4 -4
  53. package/out/parser/string/shift/operator/operator.js +22 -0
  54. package/{dist → out}/parser/string/shift/scanner.d.ts +13 -17
  55. package/{dist → out}/parser/string/shift/scanner.js +27 -24
  56. package/out/parser/string/string.d.ts +28 -0
  57. package/out/parser/string/string.js +24 -0
  58. package/out/parser/tuple.d.ts +130 -0
  59. package/out/parser/tuple.js +157 -0
  60. package/out/scope.d.ts +84 -0
  61. package/out/scope.js +131 -0
  62. package/out/type.d.ts +79 -0
  63. package/out/type.js +37 -0
  64. package/package.json +37 -41
  65. package/dist/main.d.ts +0 -11
  66. package/dist/main.d.ts.map +0 -1
  67. package/dist/main.js +0 -8
  68. package/dist/main.js.map +0 -1
  69. package/dist/match.d.ts +0 -46
  70. package/dist/match.d.ts.map +0 -1
  71. package/dist/match.js +0 -23
  72. package/dist/match.js.map +0 -1
  73. package/dist/parser/definition.d.ts.map +0 -1
  74. package/dist/parser/definition.js.map +0 -1
  75. package/dist/parser/generic.d.ts +0 -44
  76. package/dist/parser/generic.d.ts.map +0 -1
  77. package/dist/parser/generic.js +0 -46
  78. package/dist/parser/generic.js.map +0 -1
  79. package/dist/parser/objectLiteral.d.ts +0 -24
  80. package/dist/parser/objectLiteral.d.ts.map +0 -1
  81. package/dist/parser/objectLiteral.js +0 -38
  82. package/dist/parser/objectLiteral.js.map +0 -1
  83. package/dist/parser/semantic/bounds.d.ts +0 -13
  84. package/dist/parser/semantic/bounds.d.ts.map +0 -1
  85. package/dist/parser/semantic/bounds.js.map +0 -1
  86. package/dist/parser/semantic/divisor.d.ts +0 -9
  87. package/dist/parser/semantic/divisor.d.ts.map +0 -1
  88. package/dist/parser/semantic/divisor.js +0 -2
  89. package/dist/parser/semantic/divisor.js.map +0 -1
  90. package/dist/parser/semantic/intersections.d.ts +0 -15
  91. package/dist/parser/semantic/intersections.d.ts.map +0 -1
  92. package/dist/parser/semantic/intersections.js +0 -2
  93. package/dist/parser/semantic/intersections.js.map +0 -1
  94. package/dist/parser/semantic/semantic.d.ts +0 -22
  95. package/dist/parser/semantic/semantic.d.ts.map +0 -1
  96. package/dist/parser/semantic/semantic.js +0 -2
  97. package/dist/parser/semantic/semantic.js.map +0 -1
  98. package/dist/parser/semantic/utils.d.ts +0 -8
  99. package/dist/parser/semantic/utils.d.ts.map +0 -1
  100. package/dist/parser/semantic/utils.js +0 -2
  101. package/dist/parser/semantic/utils.js.map +0 -1
  102. package/dist/parser/semantic/validate.d.ts +0 -24
  103. package/dist/parser/semantic/validate.d.ts.map +0 -1
  104. package/dist/parser/semantic/validate.js +0 -2
  105. package/dist/parser/semantic/validate.js.map +0 -1
  106. package/dist/parser/shared.d.ts +0 -48
  107. package/dist/parser/shared.d.ts.map +0 -1
  108. package/dist/parser/shared.js +0 -41
  109. package/dist/parser/shared.js.map +0 -1
  110. package/dist/parser/string/reduce/dynamic.d.ts +0 -40
  111. package/dist/parser/string/reduce/dynamic.d.ts.map +0 -1
  112. package/dist/parser/string/reduce/dynamic.js.map +0 -1
  113. package/dist/parser/string/reduce/shared.d.ts +0 -29
  114. package/dist/parser/string/reduce/shared.d.ts.map +0 -1
  115. package/dist/parser/string/reduce/shared.js.map +0 -1
  116. package/dist/parser/string/reduce/static.d.ts.map +0 -1
  117. package/dist/parser/string/reduce/static.js +0 -2
  118. package/dist/parser/string/reduce/static.js.map +0 -1
  119. package/dist/parser/string/shift/operand/date.d.ts +0 -11
  120. package/dist/parser/string/shift/operand/date.d.ts.map +0 -1
  121. package/dist/parser/string/shift/operand/date.js.map +0 -1
  122. package/dist/parser/string/shift/operand/enclosed.d.ts.map +0 -1
  123. package/dist/parser/string/shift/operand/enclosed.js.map +0 -1
  124. package/dist/parser/string/shift/operand/operand.d.ts +0 -9
  125. package/dist/parser/string/shift/operand/operand.d.ts.map +0 -1
  126. package/dist/parser/string/shift/operand/operand.js +0 -17
  127. package/dist/parser/string/shift/operand/operand.js.map +0 -1
  128. package/dist/parser/string/shift/operand/unenclosed.d.ts +0 -36
  129. package/dist/parser/string/shift/operand/unenclosed.d.ts.map +0 -1
  130. package/dist/parser/string/shift/operand/unenclosed.js +0 -68
  131. package/dist/parser/string/shift/operand/unenclosed.js.map +0 -1
  132. package/dist/parser/string/shift/operator/bounds.d.ts +0 -55
  133. package/dist/parser/string/shift/operator/bounds.d.ts.map +0 -1
  134. package/dist/parser/string/shift/operator/bounds.js +0 -95
  135. package/dist/parser/string/shift/operator/bounds.js.map +0 -1
  136. package/dist/parser/string/shift/operator/divisor.d.ts.map +0 -1
  137. package/dist/parser/string/shift/operator/divisor.js.map +0 -1
  138. package/dist/parser/string/shift/operator/operator.d.ts.map +0 -1
  139. package/dist/parser/string/shift/operator/operator.js +0 -29
  140. package/dist/parser/string/shift/operator/operator.js.map +0 -1
  141. package/dist/parser/string/shift/scanner.d.ts.map +0 -1
  142. package/dist/parser/string/shift/scanner.js.map +0 -1
  143. package/dist/parser/string/string.d.ts +0 -26
  144. package/dist/parser/string/string.d.ts.map +0 -1
  145. package/dist/parser/string/string.js +0 -31
  146. package/dist/parser/string/string.js.map +0 -1
  147. package/dist/parser/tuple.d.ts +0 -73
  148. package/dist/parser/tuple.d.ts.map +0 -1
  149. package/dist/parser/tuple.js +0 -134
  150. package/dist/parser/tuple.js.map +0 -1
  151. package/dist/scope.d.ts +0 -159
  152. package/dist/scope.d.ts.map +0 -1
  153. package/dist/scope.js +0 -248
  154. package/dist/scope.js.map +0 -1
  155. package/dist/scopes/ark.d.ts +0 -38
  156. package/dist/scopes/ark.d.ts.map +0 -1
  157. package/dist/scopes/ark.js +0 -24
  158. package/dist/scopes/ark.js.map +0 -1
  159. package/dist/scopes/jsObjects.d.ts +0 -19
  160. package/dist/scopes/jsObjects.d.ts.map +0 -1
  161. package/dist/scopes/jsObjects.js +0 -15
  162. package/dist/scopes/jsObjects.js.map +0 -1
  163. package/dist/scopes/parsing.d.ts +0 -18
  164. package/dist/scopes/parsing.d.ts.map +0 -1
  165. package/dist/scopes/parsing.js +0 -61
  166. package/dist/scopes/parsing.js.map +0 -1
  167. package/dist/scopes/tsGenerics.d.ts +0 -17
  168. package/dist/scopes/tsGenerics.d.ts.map +0 -1
  169. package/dist/scopes/tsGenerics.js +0 -13
  170. package/dist/scopes/tsGenerics.js.map +0 -1
  171. package/dist/scopes/tsKeywords.d.ts +0 -24
  172. package/dist/scopes/tsKeywords.d.ts.map +0 -1
  173. package/dist/scopes/tsKeywords.js +0 -20
  174. package/dist/scopes/tsKeywords.js.map +0 -1
  175. package/dist/scopes/utils/creditCard.d.ts +0 -3
  176. package/dist/scopes/utils/creditCard.d.ts.map +0 -1
  177. package/dist/scopes/utils/creditCard.js +0 -36
  178. package/dist/scopes/utils/creditCard.js.map +0 -1
  179. package/dist/scopes/utils/date.d.ts +0 -24
  180. package/dist/scopes/utils/date.d.ts.map +0 -1
  181. package/dist/scopes/utils/date.js +0 -53
  182. package/dist/scopes/utils/date.js.map +0 -1
  183. package/dist/scopes/validation.d.ts +0 -20
  184. package/dist/scopes/validation.d.ts.map +0 -1
  185. package/dist/scopes/validation.js +0 -57
  186. package/dist/scopes/validation.js.map +0 -1
  187. package/dist/type.d.ts +0 -101
  188. package/dist/type.d.ts.map +0 -1
  189. package/dist/type.js +0 -138
  190. package/dist/type.js.map +0 -1
  191. package/main.ts +0 -20
  192. package/match.ts +0 -137
  193. package/parser/definition.ts +0 -156
  194. package/parser/generic.ts +0 -208
  195. package/parser/objectLiteral.ts +0 -120
  196. package/parser/semantic/bounds.ts +0 -63
  197. package/parser/semantic/divisor.ts +0 -13
  198. package/parser/semantic/intersections.ts +0 -47
  199. package/parser/semantic/semantic.ts +0 -107
  200. package/parser/semantic/utils.ts +0 -26
  201. package/parser/semantic/validate.ts +0 -105
  202. package/parser/shared.ts +0 -141
  203. package/parser/string/reduce/dynamic.ts +0 -181
  204. package/parser/string/reduce/shared.ts +0 -73
  205. package/parser/string/reduce/static.ts +0 -300
  206. package/parser/string/shift/operand/date.ts +0 -57
  207. package/parser/string/shift/operand/enclosed.ts +0 -119
  208. package/parser/string/shift/operand/operand.ts +0 -48
  209. package/parser/string/shift/operand/unenclosed.ts +0 -282
  210. package/parser/string/shift/operator/bounds.ts +0 -229
  211. package/parser/string/shift/operator/divisor.ts +0 -36
  212. package/parser/string/shift/operator/operator.ts +0 -82
  213. package/parser/string/shift/scanner.ts +0 -209
  214. package/parser/string/string.ts +0 -93
  215. package/parser/tuple.ts +0 -475
  216. package/scope.ts +0 -573
  217. package/scopes/ark.ts +0 -64
  218. package/scopes/jsObjects.ts +0 -29
  219. package/scopes/parsing.ts +0 -81
  220. package/scopes/tsGenerics.ts +0 -28
  221. package/scopes/tsKeywords.ts +0 -39
  222. package/scopes/utils/creditCard.ts +0 -37
  223. package/scopes/utils/date.ts +0 -108
  224. package/scopes/validation.ts +0 -81
  225. package/type.ts +0 -403
@@ -1,4 +1,4 @@
1
- import { isKeyOf } from "@arktype/util";
1
+ import { escapeToken, isKeyOf, whiteSpaceTokens } from "@ark/util";
2
2
  export class Scanner {
3
3
  chars;
4
4
  i;
@@ -13,6 +13,9 @@ export class Scanner {
13
13
  get lookahead() {
14
14
  return (this.chars[this.i] ?? "");
15
15
  }
16
+ get nextLookahead() {
17
+ return this.chars[this.i + 1] ?? "";
18
+ }
16
19
  get length() {
17
20
  return this.chars.length;
18
21
  }
@@ -20,12 +23,10 @@ export class Scanner {
20
23
  let shifted = "";
21
24
  while (this.lookahead) {
22
25
  if (condition(this, shifted)) {
23
- if (shifted[shifted.length - 1] === Scanner.escapeToken) {
26
+ if (shifted[shifted.length - 1] === escapeToken)
24
27
  shifted = shifted.slice(0, -1);
25
- }
26
- else {
28
+ else
27
29
  break;
28
- }
29
30
  }
30
31
  shifted += this.shift();
31
32
  }
@@ -41,6 +42,9 @@ export class Scanner {
41
42
  jumpToIndex(i) {
42
43
  this.i = i < 0 ? this.length + i : i;
43
44
  }
45
+ jumpForward(count) {
46
+ this.i += count;
47
+ }
44
48
  get location() {
45
49
  return this.i;
46
50
  }
@@ -62,7 +66,7 @@ export class Scanner {
62
66
  }
63
67
  (function (Scanner) {
64
68
  Scanner.lookaheadIsTerminator = (scanner) => scanner.lookahead in Scanner.terminatingChars;
65
- Scanner.lookaheadIsNotWhitespace = (scanner) => !(scanner.lookahead in Scanner.whiteSpaceTokens);
69
+ Scanner.lookaheadIsNotWhitespace = (scanner) => !(scanner.lookahead in whiteSpaceTokens);
66
70
  Scanner.terminatingChars = {
67
71
  "<": true,
68
72
  ">": true,
@@ -73,27 +77,26 @@ export class Scanner {
73
77
  "[": true,
74
78
  "%": true,
75
79
  " ": true,
76
- ",": true
80
+ ",": true,
81
+ ":": true
77
82
  };
78
83
  Scanner.finalizingLookaheads = {
79
84
  ">": true,
80
85
  ",": true,
81
- "": true
82
- };
83
- Scanner.escapeToken = "\\";
84
- Scanner.whiteSpaceTokens = {
85
- " ": true,
86
- "\n": true
86
+ "": true,
87
+ "=": true
87
88
  };
88
- Scanner.lookaheadIsFinalizing = (lookahead, unscanned) => lookahead === ">"
89
- ? unscanned[0] === "="
90
- ? // >== would only occur in an expression like Array<number>==5
91
- // otherwise, >= would only occur as part of a bound like number>=5
92
- unscanned[1] === "="
93
- : // if > is the end of a generic instantiation, the next token will be an operator or the end of the string
94
- unscanned.trimStart() === "" ||
95
- isKeyOf(unscanned.trimStart()[0], Scanner.terminatingChars)
96
- : // if the lookahead is a finalizing token but not >, it's unambiguously a finalizer (currently just ",")
97
- lookahead === ",";
89
+ Scanner.lookaheadIsFinalizing = (lookahead, unscanned) => lookahead === ">" ?
90
+ unscanned[0] === "=" ?
91
+ // >== would only occur in an expression like Array<number>==5
92
+ // otherwise, >= would only occur as part of a bound like number>=5
93
+ unscanned[1] === "="
94
+ // if > is the end of a generic instantiation, the next token will be an operator or the end of the string
95
+ : unscanned.trimStart() === "" ||
96
+ isKeyOf(unscanned.trimStart()[0], Scanner.terminatingChars)
97
+ // "=" is a finalizer on its own (representing a default value),
98
+ // but not with a second "=" (an equality comparator)
99
+ : lookahead === "=" ? unscanned[0] !== "="
100
+ // ","" is unambiguously a finalizer
101
+ : lookahead === ",";
98
102
  })(Scanner || (Scanner = {}));
99
- //# sourceMappingURL=scanner.js.map
@@ -0,0 +1,28 @@
1
+ import type { BaseRoot, resolvableReferenceIn } from "@ark/schema";
2
+ import { type ErrorMessage } from "@ark/util";
3
+ import type { inferAstRoot } from "../semantic/infer.js";
4
+ import type { DynamicState, DynamicStateWithRoot } from "./reduce/dynamic.js";
5
+ import type { StringifiablePrefixOperator } from "./reduce/shared.js";
6
+ import type { state, StaticState } from "./reduce/static.js";
7
+ import type { parseOperand } from "./shift/operand/operand.js";
8
+ import { parseDefault, type ParsedDefault } from "./shift/operator/default.js";
9
+ import { writeUnexpectedCharacterMessage, type parseOperator } from "./shift/operator/operator.js";
10
+ /**
11
+ * Try to parse the definition from right to left using the most common syntax.
12
+ * This can be much more efficient for simple definitions.
13
+ */
14
+ export type parseString<def extends string, $, args> = def extends keyof $ ? def : def extends `${infer child}[]` ? child extends keyof $ ? [
15
+ child,
16
+ "[]"
17
+ ] : fullStringParse<state.initialize<def>, $, args> : fullStringParse<state.initialize<def>, $, args>;
18
+ export type inferString<def extends string, $, args> = inferAstRoot<parseString<def, $, args>, $, args>;
19
+ export type BaseCompletions<$, args, otherSuggestions extends string = never> = resolvableReferenceIn<$> | resolvableReferenceIn<ArkEnv.$> | (keyof args & string) | StringifiablePrefixOperator | otherSuggestions;
20
+ export type StringParseResult = BaseRoot | ParsedDefault;
21
+ export declare const fullStringParse: (s: DynamicState) => StringParseResult;
22
+ type fullStringParse<s extends StaticState, $, args> = extractFinalizedResult<parseUntilFinalizer<s, $, args>>;
23
+ export declare const parseUntilFinalizer: (s: DynamicState) => DynamicStateWithRoot;
24
+ export type parseUntilFinalizer<s extends StaticState, $, args> = s["finalizer"] extends undefined ? parseUntilFinalizer<next<s, $, args>, $, args> : s;
25
+ declare const next: (s: DynamicState) => void;
26
+ type next<s extends StaticState, $, args> = s["root"] extends undefined ? parseOperand<s, $, args> : parseOperator<s, $, args>;
27
+ export type extractFinalizedResult<s extends StaticState> = s["finalizer"] extends "" ? s["root"] : s["finalizer"] extends ErrorMessage ? s["finalizer"] : s["finalizer"] extends "=" ? parseDefault<s["root"], s["unscanned"]> : state.error<writeUnexpectedCharacterMessage<`${s["finalizer"]}`>>;
28
+ export {};
@@ -0,0 +1,24 @@
1
+ import { throwInternalError, throwParseError } from "@ark/util";
2
+ import { parseDefault } from "./shift/operator/default.js";
3
+ import { writeUnexpectedCharacterMessage } from "./shift/operator/operator.js";
4
+ export const fullStringParse = (s) => {
5
+ s.parseOperand();
6
+ let result = parseUntilFinalizer(s).root;
7
+ if (!result) {
8
+ return throwInternalError(`Root was unexpectedly unset after parsing string '${s.scanner.scanned}'`);
9
+ }
10
+ if (s.finalizer === "=")
11
+ result = parseDefault(s);
12
+ s.scanner.shiftUntilNonWhitespace();
13
+ if (s.scanner.lookahead) {
14
+ // throw a parse error if non-whitespace characters made it here without being parsed
15
+ throwParseError(writeUnexpectedCharacterMessage(s.scanner.lookahead));
16
+ }
17
+ return result;
18
+ };
19
+ export const parseUntilFinalizer = (s) => {
20
+ while (s.finalizer === undefined)
21
+ next(s);
22
+ return s;
23
+ };
24
+ const next = (s) => s.hasRoot() ? s.parseOperator() : s.parseOperand();
@@ -0,0 +1,130 @@
1
+ import { type BaseMeta, type BaseRoot, type Morph, type Out, type Predicate, type distillConstrainableIn, type distillOut, type inferIntersection, type inferMorphOut, type inferPredicate } from "@ark/schema";
2
+ import { type BuiltinObjectKind, type Constructor, type Domain, type ErrorMessage, type array, type conform, type show } from "@ark/util";
3
+ import type { ParseContext } from "../scope.js";
4
+ import type { inferDefinition, validateDefinition } from "./definition.js";
5
+ import type { InfixOperator, PostfixExpression } from "./semantic/infer.js";
6
+ import { writeMissingRightOperandMessage } from "./string/shift/operand/unenclosed.js";
7
+ import type { BaseCompletions } from "./string/string.js";
8
+ export declare const parseTuple: (def: array, ctx: ParseContext) => BaseRoot;
9
+ export declare const parseTupleLiteral: (def: array, ctx: ParseContext) => BaseRoot;
10
+ type InfixExpression = readonly [unknown, InfixOperator, ...unknown[]];
11
+ export type validateTuple<def extends array, $, args> = def extends IndexZeroExpression ? validatePrefixExpression<def, $, args> : def extends PostfixExpression ? validatePostfixExpression<def, $, args> : def extends InfixExpression ? validateInfixExpression<def, $, args> : def extends (readonly ["", ...unknown[]] | readonly [unknown, "", ...unknown[]]) ? readonly [
12
+ def[0] extends "" ? BaseCompletions<$, args, IndexZeroOperator | "..."> : def[0],
13
+ def[1] extends "" ? BaseCompletions<$, args, IndexOneOperator | "..." | "?"> : def[1]
14
+ ] : validateTupleLiteral<def, $, args>;
15
+ export type validateTupleLiteral<def extends array, $, args> = parseSequence<def, $, args> extends infer s extends SequenceParseState ? Readonly<s["validated"]> : never;
16
+ type inferTupleLiteral<def extends array, $, args> = parseSequence<def, $, args> extends infer s extends SequenceParseState ? s["inferred"] : never;
17
+ type SequenceParseState = {
18
+ unscanned: array;
19
+ inferred: array;
20
+ validated: array;
21
+ };
22
+ type parseSequence<def extends array, $, args> = parseNextElement<{
23
+ unscanned: def;
24
+ inferred: [];
25
+ validated: [];
26
+ }, $, args>;
27
+ type PreparsedElement = {
28
+ head: unknown;
29
+ tail: array;
30
+ optional: boolean;
31
+ spread: boolean;
32
+ };
33
+ declare namespace PreparsedElement {
34
+ type from<result extends PreparsedElement> = result;
35
+ }
36
+ type preparseNextElement<s extends SequenceParseState> = s["unscanned"] extends readonly ["...", infer head, ...infer tail] ? tail extends readonly ["?", ...infer postOptionalTail] ? PreparsedElement.from<{
37
+ head: head;
38
+ tail: postOptionalTail;
39
+ optional: true;
40
+ spread: true;
41
+ }> : PreparsedElement.from<{
42
+ head: head;
43
+ tail: tail;
44
+ optional: false;
45
+ spread: true;
46
+ }> : s["unscanned"] extends readonly [infer head, "?", ...infer tail] ? PreparsedElement.from<{
47
+ head: head;
48
+ tail: tail;
49
+ optional: true;
50
+ spread: false;
51
+ }> : s["unscanned"] extends readonly [infer head, ...infer tail] ? PreparsedElement.from<{
52
+ head: head;
53
+ tail: tail;
54
+ optional: false;
55
+ spread: false;
56
+ }> : null;
57
+ type parseNextElement<s extends SequenceParseState, $, args> = preparseNextElement<s> extends infer next extends PreparsedElement ? parseNextElement<{
58
+ unscanned: next["tail"];
59
+ inferred: next["spread"] extends true ? [
60
+ ...s["inferred"],
61
+ ...conform<inferDefinition<next["head"], $, args>, array>
62
+ ] : next["optional"] extends true ? [
63
+ ...s["inferred"],
64
+ inferDefinition<next["head"], $, args>?
65
+ ] : [...s["inferred"], inferDefinition<next["head"], $, args>];
66
+ validated: [
67
+ ...s["validated"],
68
+ ...(next["spread"] extends true ? [
69
+ inferDefinition<next["head"], $, args> extends (infer spreadOperand extends array) ? [
70
+ number,
71
+ number
72
+ ] extends ([
73
+ s["inferred"]["length"],
74
+ spreadOperand["length"]
75
+ ]) ? ErrorMessage<multipleVariadicMessage> : "..." : ErrorMessage<writeNonArraySpreadMessage<next["head"]>>
76
+ ] : []),
77
+ [
78
+ next["optional"] | next["spread"],
79
+ "?"
80
+ ] extends ([
81
+ false,
82
+ s["validated"][number]
83
+ ]) ? ErrorMessage<requiredPostOptionalMessage> : validateDefinition<next["head"], $, args>,
84
+ ...(next["optional"] extends true ? [
85
+ next["spread"] extends true ? ErrorMessage<spreadOptionalMessage> : number extends s["inferred"]["length"] ? ErrorMessage<optionalPostVariadicMessage> : "?"
86
+ ] : [])
87
+ ];
88
+ }, $, args> : s;
89
+ export declare const writeNonArraySpreadMessage: <operand extends string>(operand: operand) => writeNonArraySpreadMessage<operand>;
90
+ type writeNonArraySpreadMessage<operand> = `Spread element must be an array${operand extends string ? ` (was ${operand})` : ""}`;
91
+ export declare const multipleVariadicMesage = "A tuple may have at most one variadic element";
92
+ type multipleVariadicMessage = typeof multipleVariadicMesage;
93
+ export declare const requiredPostOptionalMessage = "A required element may not follow an optional element";
94
+ type requiredPostOptionalMessage = typeof requiredPostOptionalMessage;
95
+ export declare const optionalPostVariadicMessage = "An optional element may not follow a variadic element";
96
+ type optionalPostVariadicMessage = typeof optionalPostVariadicMessage;
97
+ export declare const spreadOptionalMessage = "A spread element cannot be optional";
98
+ type spreadOptionalMessage = typeof optionalPostVariadicMessage;
99
+ export type inferTuple<def extends array, $, args> = def extends TupleExpression ? inferTupleExpression<def, $, args> : inferTupleLiteral<def, $, args>;
100
+ export type inferTupleExpression<def extends TupleExpression, $, args> = def[1] extends "[]" ? inferDefinition<def[0], $, args>[] : def[1] extends "&" ? inferIntersection<inferDefinition<def[0], $, args>, inferDefinition<def[2], $, args>> : def[1] extends "|" ? inferDefinition<def[0], $, args> | inferDefinition<def[2], $, args> : def[1] extends ":" ? inferPredicate<inferDefinition<def[0], $, args>, def[2]> : def[1] extends "=>" ? parseMorph<def[0], def[2], $, args> : def[1] extends "@" ? inferDefinition<def[0], $, args> : def extends readonly ["===", ...infer values] ? values[number] : def extends (readonly ["instanceof", ...infer constructors extends Constructor[]]) ? InstanceType<constructors[number]> : def[0] extends "keyof" ? inferKeyOfExpression<def[1], $, args> : never;
101
+ export type validatePrefixExpression<def extends IndexZeroExpression, $, args> = def["length"] extends 1 ? readonly [writeMissingRightOperandMessage<def[0]>] : def[0] extends "keyof" ? readonly [def[0], validateDefinition<def[1], $, args>] : def[0] extends "===" ? readonly [def[0], ...unknown[]] : def[0] extends "instanceof" ? readonly [def[0], ...Constructor[]] : never;
102
+ export type validatePostfixExpression<def extends PostfixExpression, $, args> = conform<def, readonly [validateDefinition<def[0], $, args>, "[]"]>;
103
+ export type validateInfixExpression<def extends InfixExpression, $, args> = def["length"] extends 2 ? readonly [def[0], writeMissingRightOperandMessage<def[1]>] : readonly [
104
+ validateDefinition<def[0], $, args>,
105
+ def[1],
106
+ def[1] extends "|" ? validateDefinition<def[2], $, args> : def[1] extends "&" ? validateDefinition<def[2], $, args> : def[1] extends ":" ? Predicate<distillOut<inferDefinition<def[0], $, args>>> : def[1] extends "=>" ? Morph<distillOut<inferDefinition<def[0], $, args>>, unknown> : def[1] extends "@" ? BaseMeta | string : validateDefinition<def[2], $, args>
107
+ ];
108
+ export type UnparsedTupleExpressionInput = {
109
+ instanceof: Constructor;
110
+ "===": unknown;
111
+ };
112
+ export type UnparsedTupleOperator = show<keyof UnparsedTupleExpressionInput>;
113
+ export declare const parseKeyOfTuple: PrefixParser<"keyof">;
114
+ export type inferKeyOfExpression<operandDef, $, args> = show<keyof inferDefinition<operandDef, $, args>>;
115
+ export type PostfixParser<token extends IndexOneOperator> = (def: IndexOneExpression<token>, ctx: ParseContext) => BaseRoot;
116
+ export type PrefixParser<token extends IndexZeroOperator> = (def: IndexZeroExpression<token>, ctx: ParseContext) => BaseRoot;
117
+ export type TupleExpression = IndexZeroExpression | IndexOneExpression;
118
+ export type TupleExpressionOperator = IndexZeroOperator | IndexOneOperator;
119
+ export type IndexOneOperator = TuplePostfixOperator | TupleInfixOperator;
120
+ export type TuplePostfixOperator = "[]";
121
+ export type TupleInfixOperator = "&" | "|" | "=>" | ":" | "@";
122
+ export type IndexOneExpression<token extends IndexOneOperator = IndexOneOperator> = readonly [unknown, token, ...unknown[]];
123
+ export declare const parseMorphTuple: PostfixParser<"=>">;
124
+ export declare const writeMalformedFunctionalExpressionMessage: (operator: ":" | "=>", value: unknown) => string;
125
+ export type parseMorph<inDef, morph, $, args> = morph extends Morph ? inferMorphOut<morph> extends infer out ? (In: distillConstrainableIn<inferDefinition<inDef, $, args>>) => Out<out> : never : never;
126
+ export declare const parseNarrowTuple: PostfixParser<":">;
127
+ export type IndexZeroOperator = "keyof" | "instanceof" | "===";
128
+ export type IndexZeroExpression<token extends IndexZeroOperator = IndexZeroOperator> = readonly [token, ...unknown[]];
129
+ export declare const writeInvalidConstructorMessage: <actual extends Domain | BuiltinObjectKind>(actual: actual) => string;
130
+ export {};
@@ -0,0 +1,157 @@
1
+ import { jsObjects, makeRootAndArrayPropertiesMutable, tsKeywords } from "@ark/schema";
2
+ import { append, objectKindOrDomainOf, throwParseError } from "@ark/util";
3
+ import { writeMissingRightOperandMessage } from "./string/shift/operand/unenclosed.js";
4
+ export const parseTuple = (def, ctx) => maybeParseTupleExpression(def, ctx) ?? parseTupleLiteral(def, ctx);
5
+ export const parseTupleLiteral = (def, ctx) => {
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++;
14
+ }
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
+ }
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)));
32
+ }
33
+ else {
34
+ sequences = sequences.map(base => appendElement(base, optional ? "optional" : "required", element));
35
+ }
36
+ }
37
+ return ctx.$.internal.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.internal;
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.internal);
88
+ }
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;
94
+ };
95
+ const maybeParseTupleExpression = (def, ctx) => {
96
+ const tupleExpressionResult = isIndexZeroExpression(def) ? prefixParsers[def[0]](def, ctx)
97
+ : isIndexOneExpression(def) ? indexOneParsers[def[1]](def, ctx)
98
+ : undefined;
99
+ return tupleExpressionResult;
100
+ };
101
+ export const writeNonArraySpreadMessage = (operand) => `Spread element must be an array (was ${operand})`;
102
+ export const multipleVariadicMesage = "A tuple may have at most one variadic element";
103
+ export const requiredPostOptionalMessage = "A required element may not follow an optional element";
104
+ export const optionalPostVariadicMessage = "An optional element may not follow a variadic element";
105
+ export const spreadOptionalMessage = "A spread element cannot be optional";
106
+ export const parseKeyOfTuple = (def, ctx) => ctx.$.parse(def[1], ctx).keyof();
107
+ const parseBranchTuple = (def, ctx) => {
108
+ if (def[2] === undefined)
109
+ return throwParseError(writeMissingRightOperandMessage(def[1], ""));
110
+ const l = ctx.$.parse(def[0], ctx);
111
+ const r = ctx.$.parse(def[2], ctx);
112
+ return def[1] === "&" ? l.and(r) : l.or(r);
113
+ };
114
+ const parseArrayTuple = (def, ctx) => ctx.$.parse(def[0], ctx).array();
115
+ const isIndexOneExpression = (def) => indexOneParsers[def[1]] !== undefined;
116
+ export const parseMorphTuple = (def, ctx) => {
117
+ if (typeof def[2] !== "function") {
118
+ return throwParseError(writeMalformedFunctionalExpressionMessage("=>", def[2]));
119
+ }
120
+ // TODO: nested morphs?
121
+ return ctx.$.parse(def[0], ctx).pipe(def[2]);
122
+ };
123
+ export const writeMalformedFunctionalExpressionMessage = (operator, value) => `${operator === ":" ? "Narrow" : "Morph"} expression requires a function following '${operator}' (was ${typeof value})`;
124
+ export const parseNarrowTuple = (def, ctx) => {
125
+ if (typeof def[2] !== "function") {
126
+ return throwParseError(writeMalformedFunctionalExpressionMessage(":", def[2]));
127
+ }
128
+ return ctx.$.parse(def[0], ctx).constrain("predicate", def[2]);
129
+ };
130
+ const parseAttributeTuple = (def, ctx) => ctx.$.parse(def[0], ctx).configureShallowDescendants(def[2]);
131
+ const indexOneParsers = {
132
+ "|": parseBranchTuple,
133
+ "&": parseBranchTuple,
134
+ "[]": parseArrayTuple,
135
+ ":": parseNarrowTuple,
136
+ "=>": parseMorphTuple,
137
+ "@": parseAttributeTuple
138
+ };
139
+ const prefixParsers = {
140
+ keyof: parseKeyOfTuple,
141
+ instanceof: (def, ctx) => {
142
+ if (typeof def[1] !== "function") {
143
+ return throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(def[1])));
144
+ }
145
+ const branches = def
146
+ .slice(1)
147
+ .map(ctor => typeof ctor === "function" ?
148
+ ctx.$.node("proto", { proto: ctor })
149
+ : throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(ctor))));
150
+ return branches.length === 1 ?
151
+ branches[0]
152
+ : ctx.$.node("union", { branches });
153
+ },
154
+ "===": (def, ctx) => ctx.$.units(def.slice(1))
155
+ };
156
+ const isIndexZeroExpression = (def) => prefixParsers[def[0]] !== undefined;
157
+ export const writeInvalidConstructorMessage = (actual) => `Expected a constructor following 'instanceof' operator (was ${actual})`;
package/out/scope.d.ts ADDED
@@ -0,0 +1,84 @@
1
+ import { RawRootScope, type AliasDefEntry, type ArkConfig, type BaseRoot, type GenericArgResolutions, type GenericParamAst, type GenericParamDef, type GenericProps, type PreparsedNodeResolution, type PrivateDeclaration, type RawRootResolutions, type RootScope, type arkKind, type destructuredExportContext, type destructuredImportContext, type exportedNameOf, type writeDuplicateAliasError } from "@ark/schema";
2
+ import { type anyOrNever, type array, type keyError, type nominal, type show } from "@ark/util";
3
+ import { parseGenericParams, type Generic, type GenericDeclaration, type ParameterString, type baseGenericArgs, type parseValidGenericParams } from "./generic.js";
4
+ import { type MatchParser } from "./match.js";
5
+ import type { Module } from "./module.js";
6
+ import { type inferDefinition, type validateDefinition } from "./parser/definition.js";
7
+ import type { ParsedDefault } from "./parser/string/shift/operator/default.js";
8
+ import { RawTypeParser, type DeclarationParser, type DefinitionParser, type Type, type TypeParser } from "./type.js";
9
+ export type ScopeParser = <const def>(def: validateScope<def>, config?: ArkConfig) => Scope<inferScope<def>>;
10
+ export type validateScope<def> = {
11
+ [k in keyof def]: k extends symbol ? unknown : parseScopeKey<k, def>["params"] extends infer params ? params extends array<GenericParamAst> ? params["length"] extends 0 ? def[k] extends Type | PreparsedResolution ? def[k] : k extends PrivateDeclaration<infer name extends keyof def & string> ? keyError<writeDuplicateAliasError<name>> : validateDefinition<def[k], bootstrapAliases<def>, {}> : validateDefinition<def[k], bootstrapAliases<def>, baseGenericArgs<params>> : params : never;
12
+ };
13
+ export type inferScope<def> = inferBootstrapped<bootstrapAliases<def>>;
14
+ export type bindThis<def> = {
15
+ this: Def<def>;
16
+ };
17
+ /** nominal type for an unparsed definition used during scope bootstrapping */
18
+ type Def<def = {}> = nominal<def, "unparsed">;
19
+ /** sentinel indicating a scope that will be associated with a generic has not yet been parsed */
20
+ export type UnparsedScope = "$";
21
+ /** These are legal as values of a scope but not as definitions in other contexts */
22
+ type PreparsedResolution = PreparsedNodeResolution;
23
+ type bootstrapAliases<def> = {
24
+ [k in Exclude<keyof def, GenericDeclaration | symbol>]: def[k] extends PreparsedResolution ? def[k] : def[k] extends (() => infer thunkReturn extends PreparsedResolution) ? thunkReturn : Def<def[k]>;
25
+ } & {
26
+ [k in keyof def & GenericDeclaration as extractGenericName<k>]: GenericProps<parseValidGenericParams<extractGenericParameters<k>, bootstrapAliases<def>>, def[k], UnparsedScope>;
27
+ };
28
+ type inferBootstrapped<$> = show<{
29
+ [name in keyof $]: $[name] extends Def<infer def> ? inferDefinition<def, $, {}> : $[name] extends (Generic<infer params, infer def> | GenericProps<infer params, infer def>) ? Generic<params, def, $> : $[name];
30
+ }>;
31
+ type extractGenericName<k> = k extends GenericDeclaration<infer name> ? name : never;
32
+ type extractGenericParameters<k> = k extends `${string}<${infer params}>` ? ParameterString<params> : never;
33
+ export type resolve<reference extends keyof $ | keyof args, $, args> = (reference extends keyof args ? args[reference] : $[reference & keyof $]) extends infer resolution ? [
34
+ resolution
35
+ ] extends [anyOrNever] ? resolution : resolution extends Def<infer def> ? inferDefinition<def, $, args> : resolution : never;
36
+ export type moduleKeyOf<$> = {
37
+ [k in keyof $]: $[k] extends {
38
+ [arkKind]: "module";
39
+ } ? k & string : never;
40
+ }[keyof $];
41
+ export type tryInferSubmoduleReference<$, token> = token extends `${infer submodule extends moduleKeyOf<$>}.${infer subalias}` ? subalias extends keyof $[submodule] ? $[submodule][subalias] : never : token extends `${infer submodule}.${infer subalias}` ? submodule extends moduleKeyOf<ArkEnv.$> ? subalias extends keyof ArkEnv.$[submodule] ? ArkEnv.$[submodule][subalias] : never : never : never;
42
+ export interface ParseContext extends TypeParseOptions {
43
+ $: RawScope;
44
+ }
45
+ export interface TypeParseOptions {
46
+ args?: GenericArgResolutions;
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<$> {
58
+ private parseCache;
59
+ constructor(def: Record<string, unknown>, config?: ArkConfig);
60
+ type: RawTypeParser;
61
+ match: MatchParser<$>;
62
+ declare: () => {
63
+ type: RawTypeParser;
64
+ };
65
+ define: (def: unknown) => unknown;
66
+ preparseAlias(k: string, v: unknown): AliasDefEntry;
67
+ preparseRoot(def: unknown): unknown;
68
+ parseRoot(def: unknown, opts?: TypeParseOptions): BaseRoot;
69
+ parse<defaultable extends boolean = false>(def: unknown, ctx: ParseContext, defaultable?: defaultable): BaseRoot | (defaultable extends false ? never : ParsedDefault);
70
+ parseString<defaultable extends boolean>(def: string, ctx: ParseContext, defaultable: defaultable): BaseRoot | (defaultable extends false ? never : ParsedDefault);
71
+ }
72
+ export declare const writeShallowCycleErrorMessage: (name: string, seen: string[]) => string;
73
+ export type ParsedScopeKey = {
74
+ name: string;
75
+ params: array<GenericParamDef>;
76
+ };
77
+ export type parseScopeKey<k, def> = k extends `${infer name}<${infer params}>` ? {
78
+ name: name;
79
+ params: parseGenericParams<params, bootstrapAliases<def>>;
80
+ } : {
81
+ name: k;
82
+ params: [];
83
+ };
84
+ export {};
package/out/scope.js ADDED
@@ -0,0 +1,131 @@
1
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
2
+ var useValue = arguments.length > 2;
3
+ for (var i = 0; i < initializers.length; i++) {
4
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
5
+ }
6
+ return useValue ? value : void 0;
7
+ };
8
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
9
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
10
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
11
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
12
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
13
+ var _, done = false;
14
+ for (var i = decorators.length - 1; i >= 0; i--) {
15
+ var context = {};
16
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
17
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
18
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
19
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
20
+ if (kind === "accessor") {
21
+ if (result === void 0) continue;
22
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
23
+ if (_ = accept(result.get)) descriptor.get = _;
24
+ if (_ = accept(result.set)) descriptor.set = _;
25
+ if (_ = accept(result.init)) initializers.unshift(_);
26
+ }
27
+ else if (_ = accept(result)) {
28
+ if (kind === "field") initializers.unshift(_);
29
+ else descriptor[key] = _;
30
+ }
31
+ }
32
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
+ done = true;
34
+ };
35
+ import { RawRootScope, hasArkKind, parseGeneric } from "@ark/schema";
36
+ import { bound, domainOf, hasDomain, isThunk, throwParseError } from "@ark/util";
37
+ import { parseGenericParams } from "./generic.js";
38
+ import { createMatchParser } from "./match.js";
39
+ import { parseObject, writeBadDefinitionTypeMessage } from "./parser/definition.js";
40
+ import { DynamicState } from "./parser/string/reduce/dynamic.js";
41
+ import { writeUnexpectedCharacterMessage } from "./parser/string/shift/operator/operator.js";
42
+ import { Scanner } from "./parser/string/shift/scanner.js";
43
+ import { fullStringParse } from "./parser/string/string.js";
44
+ import { RawTypeParser } from "./type.js";
45
+ export const scope = ((def, config = {}) => new RawScope(def, config));
46
+ let RawScope = (() => {
47
+ let _classSuper = RawRootScope;
48
+ let _instanceExtraInitializers = [];
49
+ let _parseRoot_decorators;
50
+ return class RawScope extends _classSuper {
51
+ static {
52
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
53
+ _parseRoot_decorators = [bound];
54
+ __esDecorate(this, null, _parseRoot_decorators, { kind: "method", name: "parseRoot", static: false, private: false, access: { has: obj => "parseRoot" in obj, get: obj => obj.parseRoot }, metadata: _metadata }, null, _instanceExtraInitializers);
55
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
56
+ }
57
+ parseCache = (__runInitializers(this, _instanceExtraInitializers), {});
58
+ constructor(def, config) {
59
+ super(def, config);
60
+ }
61
+ type = new RawTypeParser(this);
62
+ match = createMatchParser(this);
63
+ declare = (() => ({
64
+ type: this.type
65
+ })).bind(this);
66
+ define = ((def) => def).bind(this);
67
+ preparseAlias(k, v) {
68
+ const firstParamIndex = k.indexOf("<");
69
+ if (firstParamIndex === -1)
70
+ return [k, v];
71
+ if (k.at(-1) !== ">") {
72
+ throwParseError(`'>' must be the last character of a generic declaration in a scope`);
73
+ }
74
+ const name = k.slice(0, firstParamIndex);
75
+ const paramString = k.slice(firstParamIndex + 1, -1);
76
+ return [
77
+ name,
78
+ // use a thunk definition for the generic so that we can parse
79
+ // constraints within the current scope
80
+ () => {
81
+ const params = parseGenericParams(paramString, {
82
+ $: this,
83
+ args: {}
84
+ });
85
+ const generic = parseGeneric(params, v, this);
86
+ return generic;
87
+ }
88
+ ];
89
+ }
90
+ preparseRoot(def) {
91
+ if (isThunk(def) && !hasArkKind(def, "generic"))
92
+ return def();
93
+ return def;
94
+ }
95
+ parseRoot(def, opts = {}) {
96
+ const node = this.parse(def, Object.assign(this.finalizeRootArgs(opts, () => node), { $: this })).bindScope(this);
97
+ return node;
98
+ }
99
+ parse(def, ctx, defaultable = false) {
100
+ if (typeof def === "string") {
101
+ if (ctx.args && Object.keys(ctx.args).some(k => def.includes(k))) {
102
+ // we can only rely on the cache if there are no contextual
103
+ // resolutions like "this" or generic args
104
+ return this.parseString(def, ctx, defaultable);
105
+ }
106
+ const contextKey = `${def}${defaultable}`;
107
+ return (this.parseCache[contextKey] ??= this.parseString(def, ctx, defaultable));
108
+ }
109
+ return hasDomain(def, "object") ?
110
+ parseObject(def, ctx)
111
+ : throwParseError(writeBadDefinitionTypeMessage(domainOf(def)));
112
+ }
113
+ parseString(def, ctx, defaultable) {
114
+ const aliasResolution = this.maybeResolveRoot(def);
115
+ if (aliasResolution)
116
+ return aliasResolution;
117
+ const aliasArrayResolution = def.endsWith("[]") ?
118
+ this.maybeResolveRoot(def.slice(0, -2))?.array()
119
+ : undefined;
120
+ if (aliasArrayResolution)
121
+ return aliasArrayResolution;
122
+ const s = new DynamicState(new Scanner(def), ctx, defaultable);
123
+ const node = fullStringParse(s);
124
+ if (s.finalizer === ">")
125
+ throwParseError(writeUnexpectedCharacterMessage(">"));
126
+ return node;
127
+ }
128
+ };
129
+ })();
130
+ export { RawScope };
131
+ export const writeShallowCycleErrorMessage = (name, seen) => `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join(":")}`;