arktype 1.1.0-dev-1 → 2.0.0-dev.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 (213) hide show
  1. package/__tests__/array.test.ts +272 -0
  2. package/__tests__/astUtils.test.ts +17 -0
  3. package/__tests__/badDefinitionType.test.ts +51 -0
  4. package/__tests__/basis.test.ts +46 -0
  5. package/__tests__/bounds.test.ts +388 -0
  6. package/__tests__/cast.test.ts +32 -0
  7. package/__tests__/completions.test.ts +46 -0
  8. package/__tests__/config.test.ts +168 -0
  9. package/__tests__/cyclic.test.ts +144 -0
  10. package/__tests__/dateLiteral.test.ts +32 -0
  11. package/__tests__/declared.test.ts +123 -0
  12. package/__tests__/discrimination.test.ts +74 -0
  13. package/__tests__/divisor.test.ts +90 -0
  14. package/__tests__/enclosed.test.ts +93 -0
  15. package/__tests__/examples.test.ts +56 -0
  16. package/__tests__/expressions.test.ts +138 -0
  17. package/__tests__/generateBenchData.ts +89 -0
  18. package/__tests__/generated/cyclic.ts +3058 -0
  19. package/__tests__/generic.test.ts +294 -0
  20. package/__tests__/group.test.ts +72 -0
  21. package/__tests__/hkt.test.ts +22 -0
  22. package/__tests__/imports.test.ts +113 -0
  23. package/__tests__/instanceof.test.ts +102 -0
  24. package/__tests__/intersection.test.ts +104 -0
  25. package/__tests__/jsdoc.test.ts +64 -0
  26. package/__tests__/keyTraversal.test.ts +73 -0
  27. package/__tests__/keyof.test.ts +134 -0
  28. package/__tests__/keywords.test.ts +188 -0
  29. package/__tests__/literal.test.ts +51 -0
  30. package/__tests__/match.test.ts +34 -0
  31. package/__tests__/methods.bench.ts +22 -0
  32. package/__tests__/morph.test.ts +409 -0
  33. package/__tests__/narrow.test.ts +102 -0
  34. package/__tests__/nodeDefinitions.test.ts +190 -0
  35. package/__tests__/object.bench.ts +28 -0
  36. package/__tests__/objectLiteral.test.ts +300 -0
  37. package/__tests__/operand.bench.ts +45 -0
  38. package/__tests__/operator.bench.ts +130 -0
  39. package/__tests__/regex.test.ts +58 -0
  40. package/__tests__/scope.bench.ts +39 -0
  41. package/__tests__/scope.test.ts +140 -0
  42. package/__tests__/string.test.ts +48 -0
  43. package/__tests__/submodule.test.ts +99 -0
  44. package/__tests__/this.test.ts +57 -0
  45. package/__tests__/thunk.test.ts +80 -0
  46. package/__tests__/traverse.test.ts +119 -0
  47. package/__tests__/tsGenerics.test.ts +12 -0
  48. package/__tests__/typeMethods.test.ts +69 -0
  49. package/__tests__/typeReference.test.ts +39 -0
  50. package/__tests__/unenclosed.test.ts +120 -0
  51. package/__tests__/union.test.ts +147 -0
  52. package/ark.ts +91 -0
  53. package/main.ts +18 -0
  54. package/match.ts +116 -0
  55. package/out/ark.d.ts +52 -0
  56. package/out/ark.d.ts.map +1 -0
  57. package/out/ark.js +19 -0
  58. package/out/ark.js.map +1 -0
  59. package/out/arkConfig.d.ts +2 -0
  60. package/out/arkConfig.d.ts.map +1 -0
  61. package/out/arkConfig.js +10 -0
  62. package/out/arkConfig.js.map +1 -0
  63. package/out/main.d.ts +7 -0
  64. package/out/main.d.ts.map +1 -0
  65. package/out/main.js +4 -0
  66. package/out/main.js.map +1 -0
  67. package/out/match.d.ts +48 -0
  68. package/out/match.d.ts.map +1 -0
  69. package/out/match.js +18 -0
  70. package/out/match.js.map +1 -0
  71. package/out/parser/definition.d.ts +32 -0
  72. package/out/parser/definition.d.ts.map +1 -0
  73. package/out/parser/definition.js +32 -0
  74. package/out/parser/definition.js.map +1 -0
  75. package/out/parser/generic.d.ts +18 -0
  76. package/out/parser/generic.d.ts.map +1 -0
  77. package/out/parser/generic.js +19 -0
  78. package/out/parser/generic.js.map +1 -0
  79. package/out/parser/objectLiteral.d.ts +33 -0
  80. package/out/parser/objectLiteral.d.ts.map +1 -0
  81. package/out/parser/objectLiteral.js +66 -0
  82. package/out/parser/objectLiteral.js.map +1 -0
  83. package/out/parser/semantic/bounds.d.ts +13 -0
  84. package/out/parser/semantic/bounds.d.ts.map +1 -0
  85. package/out/parser/semantic/bounds.js +2 -0
  86. package/out/parser/semantic/bounds.js.map +1 -0
  87. package/out/parser/semantic/divisor.d.ts +9 -0
  88. package/out/parser/semantic/divisor.d.ts.map +1 -0
  89. package/out/parser/semantic/divisor.js +2 -0
  90. package/out/parser/semantic/divisor.js.map +1 -0
  91. package/out/parser/semantic/intersections.d.ts +14 -0
  92. package/out/parser/semantic/intersections.d.ts.map +1 -0
  93. package/out/parser/semantic/intersections.js +2 -0
  94. package/out/parser/semantic/intersections.js.map +1 -0
  95. package/out/parser/semantic/semantic.d.ts +33 -0
  96. package/out/parser/semantic/semantic.d.ts.map +1 -0
  97. package/out/parser/semantic/semantic.js +2 -0
  98. package/out/parser/semantic/semantic.js.map +1 -0
  99. package/out/parser/semantic/utils.d.ts +8 -0
  100. package/out/parser/semantic/utils.d.ts.map +1 -0
  101. package/out/parser/semantic/utils.js +2 -0
  102. package/out/parser/semantic/utils.js.map +1 -0
  103. package/out/parser/semantic/validate.d.ts +24 -0
  104. package/out/parser/semantic/validate.d.ts.map +1 -0
  105. package/out/parser/semantic/validate.js +2 -0
  106. package/out/parser/semantic/validate.js.map +1 -0
  107. package/out/parser/shared.d.ts +54 -0
  108. package/out/parser/shared.d.ts.map +1 -0
  109. package/out/parser/shared.js +47 -0
  110. package/out/parser/shared.js.map +1 -0
  111. package/out/parser/string/reduce/dynamic.d.ts +42 -0
  112. package/out/parser/string/reduce/dynamic.d.ts.map +1 -0
  113. package/out/parser/string/reduce/dynamic.js +133 -0
  114. package/out/parser/string/reduce/dynamic.js.map +1 -0
  115. package/out/parser/string/reduce/shared.d.ts +56 -0
  116. package/out/parser/string/reduce/shared.d.ts.map +1 -0
  117. package/out/parser/string/reduce/shared.js +26 -0
  118. package/out/parser/string/reduce/shared.js.map +1 -0
  119. package/out/parser/string/reduce/static.d.ts +176 -0
  120. package/out/parser/string/reduce/static.d.ts.map +1 -0
  121. package/out/parser/string/reduce/static.js +2 -0
  122. package/out/parser/string/reduce/static.js.map +1 -0
  123. package/out/parser/string/shift/operand/date.d.ts +11 -0
  124. package/out/parser/string/shift/operand/date.d.ts.map +1 -0
  125. package/out/parser/string/shift/operand/date.js +26 -0
  126. package/out/parser/string/shift/operand/date.js.map +1 -0
  127. package/out/parser/string/shift/operand/enclosed.d.ts +49 -0
  128. package/out/parser/string/shift/operand/enclosed.d.ts.map +1 -0
  129. package/out/parser/string/shift/operand/enclosed.js +50 -0
  130. package/out/parser/string/shift/operand/enclosed.js.map +1 -0
  131. package/out/parser/string/shift/operand/genericArgs.d.ts +29 -0
  132. package/out/parser/string/shift/operand/genericArgs.d.ts.map +1 -0
  133. package/out/parser/string/shift/operand/genericArgs.js +25 -0
  134. package/out/parser/string/shift/operand/genericArgs.js.map +1 -0
  135. package/out/parser/string/shift/operand/operand.d.ts +9 -0
  136. package/out/parser/string/shift/operand/operand.d.ts.map +1 -0
  137. package/out/parser/string/shift/operand/operand.js +17 -0
  138. package/out/parser/string/shift/operand/operand.js.map +1 -0
  139. package/out/parser/string/shift/operand/unenclosed.d.ts +34 -0
  140. package/out/parser/string/shift/operand/unenclosed.d.ts.map +1 -0
  141. package/out/parser/string/shift/operand/unenclosed.js +68 -0
  142. package/out/parser/string/shift/operand/unenclosed.js.map +1 -0
  143. package/out/parser/string/shift/operator/bounds.d.ts +33 -0
  144. package/out/parser/string/shift/operator/bounds.d.ts.map +1 -0
  145. package/out/parser/string/shift/operator/bounds.js +106 -0
  146. package/out/parser/string/shift/operator/bounds.js.map +1 -0
  147. package/out/parser/string/shift/operator/divisor.d.ts +9 -0
  148. package/out/parser/string/shift/operator/divisor.d.ts.map +1 -0
  149. package/out/parser/string/shift/operator/divisor.js +13 -0
  150. package/out/parser/string/shift/operator/divisor.js.map +1 -0
  151. package/out/parser/string/shift/operator/operator.d.ts +13 -0
  152. package/out/parser/string/shift/operator/operator.d.ts.map +1 -0
  153. package/out/parser/string/shift/operator/operator.js +29 -0
  154. package/out/parser/string/shift/operator/operator.js.map +1 -0
  155. package/out/parser/string/shift/scanner.d.ts +71 -0
  156. package/out/parser/string/shift/scanner.d.ts.map +1 -0
  157. package/out/parser/string/shift/scanner.js +99 -0
  158. package/out/parser/string/shift/scanner.js.map +1 -0
  159. package/out/parser/string/string.d.ts +24 -0
  160. package/out/parser/string/string.d.ts.map +1 -0
  161. package/out/parser/string/string.js +23 -0
  162. package/out/parser/string/string.js.map +1 -0
  163. package/out/parser/tuple.d.ts +71 -0
  164. package/out/parser/tuple.d.ts.map +1 -0
  165. package/out/parser/tuple.js +137 -0
  166. package/out/parser/tuple.js.map +1 -0
  167. package/out/scope.d.ts +159 -0
  168. package/out/scope.d.ts.map +1 -0
  169. package/out/scope.js +253 -0
  170. package/out/scope.js.map +1 -0
  171. package/out/test.d.ts +2 -0
  172. package/out/test.d.ts.map +1 -0
  173. package/out/test.js +7 -0
  174. package/out/test.js.map +1 -0
  175. package/out/tsconfig.build.tsbuildinfo +1 -0
  176. package/out/type.d.ts +77 -0
  177. package/out/type.d.ts.map +1 -0
  178. package/out/type.js +134 -0
  179. package/out/type.js.map +1 -0
  180. package/out/util.d.ts +19 -0
  181. package/out/util.d.ts.map +1 -0
  182. package/out/util.js +7 -0
  183. package/out/util.js.map +1 -0
  184. package/package.json +13 -10
  185. package/parser/definition.ts +159 -0
  186. package/parser/generic.ts +68 -0
  187. package/parser/objectLiteral.ts +197 -0
  188. package/parser/semantic/bounds.ts +61 -0
  189. package/parser/semantic/divisor.ts +13 -0
  190. package/parser/semantic/intersections.ts +46 -0
  191. package/parser/semantic/semantic.ts +144 -0
  192. package/parser/semantic/utils.ts +26 -0
  193. package/parser/semantic/validate.ts +109 -0
  194. package/parser/shared.ts +152 -0
  195. package/parser/string/reduce/dynamic.ts +196 -0
  196. package/parser/string/reduce/shared.ts +101 -0
  197. package/parser/string/reduce/static.ts +298 -0
  198. package/parser/string/shift/operand/date.ts +54 -0
  199. package/parser/string/shift/operand/enclosed.ts +118 -0
  200. package/parser/string/shift/operand/genericArgs.ts +127 -0
  201. package/parser/string/shift/operand/operand.ts +48 -0
  202. package/parser/string/shift/operand/unenclosed.ts +268 -0
  203. package/parser/string/shift/operator/bounds.ts +264 -0
  204. package/parser/string/shift/operator/divisor.ts +36 -0
  205. package/parser/string/shift/operator/operator.ts +82 -0
  206. package/parser/string/shift/scanner.ts +209 -0
  207. package/parser/string/string.ts +90 -0
  208. package/parser/tuple.ts +474 -0
  209. package/scope.ts +574 -0
  210. package/type.ts +347 -0
  211. package/util.ts +36 -0
  212. package/dist/main.d.ts +0 -1018
  213. package/dist/main.js +0 -1450
@@ -0,0 +1,26 @@
1
+ import type { List, Stringifiable } from "@arktype/util"
2
+ import type { Comparator } from "../string/reduce/shared.js"
3
+ import type { InfixExpression, PostfixExpression } from "./semantic.js"
4
+
5
+ export type astToString<ast> = `'${astToStringRecurse<ast>}'`
6
+
7
+ type astToStringRecurse<ast> = ast extends PostfixExpression<
8
+ infer operator,
9
+ infer operand
10
+ >
11
+ ? operator extends "[]"
12
+ ? `${groupAst<operand>}[]`
13
+ : never
14
+ : ast extends InfixExpression<infer operator, infer l, infer r>
15
+ ? operator extends "&" | "|" | "%" | Comparator
16
+ ? `${groupAst<l>}${operator}${groupAst<r>}`
17
+ : never
18
+ : ast extends Stringifiable
19
+ ? `${ast extends bigint ? `${ast}n` : ast}`
20
+ : "..."
21
+
22
+ type groupAst<ast> = ast extends List
23
+ ? ast[1] extends "[]"
24
+ ? astToStringRecurse<ast>
25
+ : `(${astToStringRecurse<ast>})`
26
+ : astToStringRecurse<ast>
@@ -0,0 +1,109 @@
1
+ import type { Refinements } from "@arktype/schema"
2
+ import type {
3
+ BigintLiteral,
4
+ Completion,
5
+ ErrorMessage,
6
+ NumberLiteral,
7
+ writeMalformedNumericLiteralMessage
8
+ } from "@arktype/util"
9
+ import type { Module } from "../../scope.js"
10
+ import type { GenericProps } from "../../type.js"
11
+ import type { Comparator } from "../string/reduce/shared.js"
12
+ import type { writeInvalidGenericArgsMessage } from "../string/shift/operand/genericArgs.js"
13
+ import type { writeMissingSubmoduleAccessMessage } from "../string/shift/operand/unenclosed.js"
14
+ import type { parseString } from "../string/string.js"
15
+ import type { validateRange } from "./bounds.js"
16
+ import type { validateDivisor } from "./divisor.js"
17
+ import type {
18
+ GenericInstantiationAst,
19
+ InfixExpression,
20
+ PostfixExpression
21
+ } from "./semantic.js"
22
+ import type { astToString } from "./utils.js"
23
+
24
+ export type validateAst<ast, $, args> = ast extends string
25
+ ? validateStringAst<ast, $>
26
+ : ast extends PostfixExpression<infer operator, infer operand>
27
+ ? operator extends "[]"
28
+ ? validateAst<operand, $, args>
29
+ : never
30
+ : ast extends InfixExpression<infer operator, infer l, infer r>
31
+ ? operator extends "&" | "|"
32
+ ? validateInfix<ast, $, args>
33
+ : operator extends Comparator
34
+ ? validateRange<l, operator, r, $, args>
35
+ : operator extends "%"
36
+ ? validateDivisor<l, $, args>
37
+ : undefined
38
+ : ast extends readonly ["keyof", infer operand]
39
+ ? validateAst<operand, $, args>
40
+ : ast extends GenericInstantiationAst
41
+ ? validateGenericArgs<ast["2"], $, args>
42
+ : ErrorMessage<writeUnexpectedExpressionMessage<astToString<ast>>>
43
+
44
+ type writeUnexpectedExpressionMessage<expression extends string> =
45
+ `Unexpectedly failed to parse the expression resulting from ${expression}`
46
+
47
+ type validateGenericArgs<argAsts extends unknown[], $, args> = argAsts extends [
48
+ infer head,
49
+ ...infer tail
50
+ ]
51
+ ? validateAst<head, $, args> extends ErrorMessage<infer message>
52
+ ? ErrorMessage<message>
53
+ : validateGenericArgs<tail, $, args>
54
+ : undefined
55
+
56
+ export const writeUnsatisfiableExpressionError = <expression extends string>(
57
+ expression: expression
58
+ ): writeUnsatisfiableExpressionError<expression> =>
59
+ `${expression} results in an unsatisfiable type`
60
+
61
+ export type writeUnsatisfiableExpressionError<expression extends string> =
62
+ `${expression} results in an unsatisfiable type`
63
+
64
+ type validateStringAst<def extends string, $> = def extends NumberLiteral<
65
+ infer value
66
+ >
67
+ ? number extends value
68
+ ? ErrorMessage<writeMalformedNumericLiteralMessage<def, "number">>
69
+ : undefined
70
+ : def extends BigintLiteral<infer value>
71
+ ? bigint extends value
72
+ ? ErrorMessage<writeMalformedNumericLiteralMessage<def, "bigint">>
73
+ : undefined
74
+ : def extends keyof $
75
+ ? $[def] extends null
76
+ ? // handle any/never
77
+ def
78
+ : // these problems would've been caught during a fullStringParse, but it's most
79
+ // efficient to check for them here in case the string was naively parsed
80
+ $[def] extends GenericProps
81
+ ? ErrorMessage<
82
+ writeInvalidGenericArgsMessage<def, $[def]["parameters"], []>
83
+ >
84
+ : $[def] extends Module
85
+ ? ErrorMessage<writeMissingSubmoduleAccessMessage<def>>
86
+ : undefined
87
+ : def extends ErrorMessage
88
+ ? def
89
+ : undefined
90
+
91
+ export type validateString<def extends string, $, args> = validateAst<
92
+ parseString<def, $, args>,
93
+ $,
94
+ args
95
+ > extends infer result extends ErrorMessage
96
+ ? result extends Completion<infer text>
97
+ ? text
98
+ : result
99
+ : def
100
+
101
+ type validateInfix<ast extends InfixExpression, $, args> = validateAst<
102
+ ast[0],
103
+ $,
104
+ args
105
+ > extends ErrorMessage<infer message>
106
+ ? ErrorMessage<message>
107
+ : validateAst<ast[2], $, args> extends ErrorMessage<infer message>
108
+ ? ErrorMessage<message>
109
+ : undefined
@@ -0,0 +1,152 @@
1
+ import type { extend } from "@arktype/util"
2
+ import type { validateDefinition } from "./definition.js"
3
+ import { Scanner } from "./string/shift/scanner.js"
4
+
5
+ type parsedKey<result extends KeyParseResult> = result
6
+
7
+ type OptionalTuple<value> = readonly [value, "?"]
8
+
9
+ type KeyParseResult<kind extends ParsedKeyKind = ParsedKeyKind> = {
10
+ kind: kind
11
+ innerKey: string | symbol
12
+ }
13
+
14
+ type ValueParseResult<kind extends ParsedValueKind = ParsedValueKind> = {
15
+ kind: kind
16
+ innerValue: unknown
17
+ }
18
+
19
+ export type EntryParseResult<kind extends ParsedKeyKind = ParsedKeyKind> =
20
+ extend<
21
+ KeyParseResult<kind>,
22
+ {
23
+ innerValue: unknown
24
+ }
25
+ >
26
+
27
+ type ParsedValueKind = "required" | "optional"
28
+
29
+ type ParsedKeyKind = "required" | "optional" | "indexed" | "spread"
30
+
31
+ type parsedEntry<result extends EntryParseResult> = result
32
+
33
+ export type OptionalValue<value> =
34
+ | OptionalStringDefinition<value & string>
35
+ | OptionalTuple<value>
36
+
37
+ export type OptionalStringDefinition<name extends string = string> = `${name}?`
38
+
39
+ export type IndexedKey<def extends string = string> = `[${def}]`
40
+
41
+ export type validateObjectValue<def, $, args> = def extends OptionalTuple<
42
+ infer value
43
+ >
44
+ ? readonly [validateObjectValueString<value, $, args>, "?"]
45
+ : validateObjectValueString<def, $, args>
46
+
47
+ type validateObjectValueString<def, $, args> =
48
+ def extends OptionalStringDefinition<infer innerValue>
49
+ ? `${validateDefinition<innerValue, $, args>}?`
50
+ : validateDefinition<def, $, args>
51
+
52
+ type DefinitionEntry = readonly [string | symbol, unknown]
53
+
54
+ const getInnerValue = (value: unknown): ValueParseResult => {
55
+ if (typeof value === "string") {
56
+ if (value[value.length - 1] === "?") {
57
+ return {
58
+ kind: "optional",
59
+ innerValue: value.slice(0, -1)
60
+ }
61
+ }
62
+ } else if (Array.isArray(value)) {
63
+ if (value.length === 2 && value[1] === "?") {
64
+ return {
65
+ kind: "optional",
66
+ innerValue: getInnerValue(value[0]).innerValue
67
+ }
68
+ }
69
+ }
70
+ return {
71
+ kind: "required",
72
+ innerValue: value
73
+ }
74
+ }
75
+
76
+ // these methods are also used in tuple parsing, however the keys of a tuple will always be 0, 1,
77
+ // 2, etc and never be `...`, meaning `"spread"` as a kind will never occur in tuples
78
+
79
+ export const parseEntry = ([key, value]: DefinitionEntry): EntryParseResult => {
80
+ const keyParseResult: KeyParseResult =
81
+ typeof key === "string" && key.at(-1) === "?"
82
+ ? key.at(-2) === Scanner.escapeToken
83
+ ? { innerKey: `${key.slice(0, -2)}?`, kind: "required" }
84
+ : { innerKey: key.slice(0, -1), kind: "optional" }
85
+ : key === "..."
86
+ ? { innerKey: "...", kind: "spread" }
87
+ : key === "\\..."
88
+ ? { innerKey: "...", kind: "required" }
89
+ : { innerKey: key, kind: "required" }
90
+ const valueParseResult = getInnerValue(value)
91
+ return {
92
+ innerKey: keyParseResult.innerKey,
93
+ innerValue: valueParseResult.innerValue,
94
+ kind:
95
+ keyParseResult.kind === "indexed"
96
+ ? "indexed"
97
+ : valueParseResult.kind === "optional"
98
+ ? "optional"
99
+ : keyParseResult.kind
100
+ }
101
+ }
102
+
103
+ export type parseEntry<
104
+ keyDef extends PropertyKey,
105
+ valueDef
106
+ > = parseKey<keyDef> extends infer keyParseResult extends KeyParseResult
107
+ ? valueDef extends OptionalValue<infer innerValue>
108
+ ? parsedEntry<{
109
+ kind: "optional"
110
+ innerKey: keyParseResult["innerKey"]
111
+ innerValue: innerValue extends OptionalStringDefinition<
112
+ infer innerStringValue
113
+ >
114
+ ? innerStringValue
115
+ : innerValue
116
+ }>
117
+ : parsedEntry<{
118
+ kind: keyParseResult["kind"]
119
+ innerKey: keyParseResult["innerKey"]
120
+ innerValue: valueDef
121
+ }>
122
+ : never
123
+
124
+ type parseKey<k> = k extends OptionalStringDefinition<infer inner>
125
+ ? inner extends `${infer baseName}${Scanner.EscapeToken}`
126
+ ? parsedKey<{
127
+ kind: "required"
128
+ innerKey: OptionalStringDefinition<baseName>
129
+ }>
130
+ : parsedKey<{
131
+ kind: "optional"
132
+ innerKey: inner
133
+ }>
134
+ : k extends "..."
135
+ ? parsedKey<{ kind: "spread"; innerKey: "..." }>
136
+ : k extends "\\..."
137
+ ? parsedKey<{ kind: "required"; innerKey: "..." }>
138
+ : k extends IndexedKey<infer def>
139
+ ? parsedKey<{
140
+ kind: "indexed"
141
+ innerKey: def
142
+ }>
143
+ : k extends `${Scanner.EscapeToken}${infer escapedIndexKey extends
144
+ IndexedKey}`
145
+ ? parsedKey<{
146
+ kind: "required"
147
+ innerKey: escapedIndexKey
148
+ }>
149
+ : parsedKey<{
150
+ kind: "required"
151
+ innerKey: k & (string | symbol)
152
+ }>
@@ -0,0 +1,196 @@
1
+ import type { TypeNode } from "@arktype/schema"
2
+ import {
3
+ isKeyOf,
4
+ throwInternalError,
5
+ throwParseError,
6
+ type requireKeys
7
+ } from "@arktype/util"
8
+ import type { ParseContext } from "../../../scope.js"
9
+ import { parseOperand } from "../shift/operand/operand.js"
10
+ import { parseOperator } from "../shift/operator/operator.js"
11
+ import { Scanner } from "../shift/scanner.js"
12
+ import { parseUntilFinalizer } from "../string.js"
13
+ import {
14
+ invertedComparators,
15
+ minComparators,
16
+ writeMultipleLeftBoundsMessage,
17
+ writeOpenRangeMessage,
18
+ writeUnclosedGroupMessage,
19
+ writeUnmatchedGroupCloseMessage,
20
+ writeUnpairableComparatorMessage,
21
+ type Comparator,
22
+ type LimitLiteral,
23
+ type OpenLeftBound,
24
+ type StringifiablePrefixOperator
25
+ } from "./shared.js"
26
+
27
+ type BranchState = {
28
+ prefixes: StringifiablePrefixOperator[]
29
+ leftBound?: OpenLeftBound
30
+ "&"?: TypeNode
31
+ "|"?: TypeNode
32
+ }
33
+
34
+ export type DynamicStateWithRoot = requireKeys<DynamicState, "root">
35
+
36
+ export class DynamicState {
37
+ readonly scanner: Scanner
38
+ root: TypeNode | undefined
39
+ branches: BranchState = {
40
+ prefixes: []
41
+ }
42
+ finalizer: Scanner.FinalizingLookahead | undefined
43
+ groups: BranchState[] = []
44
+
45
+ constructor(
46
+ def: string,
47
+ public readonly ctx: ParseContext
48
+ ) {
49
+ this.scanner = new Scanner(def)
50
+ }
51
+
52
+ error(message: string) {
53
+ return throwParseError(message)
54
+ }
55
+
56
+ hasRoot(): this is DynamicStateWithRoot {
57
+ return this.root !== undefined
58
+ }
59
+
60
+ unsetRoot(): this["root"] {
61
+ const value = this.root
62
+ this.root = undefined
63
+ return value
64
+ }
65
+
66
+ constrainRoot(...args: Parameters<TypeNode["constrain"]>) {
67
+ this.root = this.root!.constrain(...args)
68
+ }
69
+
70
+ setRoot(root: TypeNode) {
71
+ this.root = root
72
+ }
73
+
74
+ finalize(finalizer: Scanner.FinalizingLookahead) {
75
+ if (this.groups.length) {
76
+ return this.error(writeUnclosedGroupMessage(")"))
77
+ }
78
+ this.finalizeBranches()
79
+ this.finalizer = finalizer
80
+ }
81
+
82
+ reduceLeftBound(limit: LimitLiteral, comparator: Comparator) {
83
+ const invertedComparator = invertedComparators[comparator]
84
+ if (!isKeyOf(invertedComparator, minComparators)) {
85
+ return this.error(writeUnpairableComparatorMessage(comparator))
86
+ }
87
+ if (this.branches.leftBound) {
88
+ return this.error(
89
+ writeMultipleLeftBoundsMessage(
90
+ this.branches.leftBound.limit,
91
+ this.branches.leftBound.comparator,
92
+ limit,
93
+ invertedComparator
94
+ )
95
+ )
96
+ }
97
+ this.branches.leftBound = {
98
+ comparator: invertedComparator,
99
+ limit
100
+ }
101
+ }
102
+
103
+ finalizeBranches() {
104
+ this.assertRangeUnset()
105
+ if (this.branches["|"]) {
106
+ this.pushRootToBranch("|")
107
+ this.root = this.branches["|"]
108
+ } else if (this.branches["&"]) {
109
+ this.pushRootToBranch("&")
110
+ this.root = this.branches["&"]
111
+ } else {
112
+ this.applyPrefixes()
113
+ }
114
+ }
115
+
116
+ finalizeGroup() {
117
+ this.finalizeBranches()
118
+ const topBranchState = this.groups.pop()
119
+ if (!topBranchState) {
120
+ return this.error(writeUnmatchedGroupCloseMessage(this.scanner.unscanned))
121
+ }
122
+ this.branches = topBranchState
123
+ }
124
+
125
+ addPrefix(prefix: StringifiablePrefixOperator) {
126
+ this.branches.prefixes.push(prefix)
127
+ }
128
+
129
+ applyPrefixes() {
130
+ while (this.branches.prefixes.length) {
131
+ const lastPrefix = this.branches.prefixes.pop()!
132
+ this.root =
133
+ lastPrefix === "keyof"
134
+ ? this.root!.keyof()
135
+ : throwInternalError(`Unexpected prefix '${lastPrefix}'`)
136
+ }
137
+ }
138
+
139
+ pushRootToBranch(token: "|" | "&") {
140
+ this.assertRangeUnset()
141
+ this.applyPrefixes()
142
+ const root = this.root!
143
+ this.branches["&"] = this.branches["&"]?.and(root) ?? root
144
+ if (token === "|") {
145
+ this.branches["|"] =
146
+ this.branches["|"]?.or(this.branches["&"]) ?? this.branches["&"]
147
+ delete this.branches["&"]
148
+ }
149
+ this.root = undefined
150
+ }
151
+
152
+ parseUntilFinalizer() {
153
+ return parseUntilFinalizer(
154
+ new DynamicState(this.scanner.unscanned, this.ctx)
155
+ )
156
+ }
157
+
158
+ parseOperator(this: DynamicStateWithRoot) {
159
+ return parseOperator(this)
160
+ }
161
+
162
+ parseOperand() {
163
+ return parseOperand(this)
164
+ }
165
+
166
+ private assertRangeUnset() {
167
+ if (this.branches.leftBound) {
168
+ return this.error(
169
+ writeOpenRangeMessage(
170
+ this.branches.leftBound.limit,
171
+ this.branches.leftBound.comparator
172
+ )
173
+ )
174
+ }
175
+ }
176
+
177
+ reduceGroupOpen() {
178
+ this.groups.push(this.branches)
179
+ this.branches = {
180
+ prefixes: []
181
+ }
182
+ }
183
+
184
+ previousOperator() {
185
+ return (
186
+ this.branches.leftBound?.comparator ??
187
+ this.branches.prefixes.at(-1) ??
188
+ (this.branches["&"] ? "&" : this.branches["|"] ? "|" : undefined)
189
+ )
190
+ }
191
+
192
+ shiftedByOne() {
193
+ this.scanner.shift()
194
+ return this
195
+ }
196
+ }
@@ -0,0 +1,101 @@
1
+ import type { DateLiteral } from "@arktype/schema"
2
+
3
+ export type StringifiablePrefixOperator = "keyof"
4
+
5
+ export const minComparators = {
6
+ ">": true,
7
+ ">=": true
8
+ } as const
9
+
10
+ export type MinComparator = keyof typeof minComparators
11
+
12
+ export const maxComparators = {
13
+ "<": true,
14
+ "<=": true
15
+ } as const
16
+
17
+ export type MaxComparator = keyof typeof maxComparators
18
+
19
+ export const comparators = {
20
+ ...minComparators,
21
+ ...maxComparators,
22
+ "==": true
23
+ }
24
+
25
+ export type Comparator = keyof typeof comparators
26
+
27
+ export const invertedComparators = {
28
+ "<": ">",
29
+ ">": "<",
30
+ "<=": ">=",
31
+ ">=": "<=",
32
+ "==": "=="
33
+ } as const satisfies Record<Comparator, Comparator>
34
+
35
+ export type InvertedComparators = typeof invertedComparators
36
+
37
+ export type LimitLiteral = number | DateLiteral
38
+
39
+ export type OpenLeftBound = { limit: LimitLiteral; comparator: MinComparator }
40
+
41
+ export const writeUnmatchedGroupCloseMessage = <unscanned extends string>(
42
+ unscanned: unscanned
43
+ ): writeUnmatchedGroupCloseMessage<unscanned> =>
44
+ `Unmatched )${(unscanned === "" ? "" : ` before ${unscanned}`) as any}`
45
+
46
+ export type writeUnmatchedGroupCloseMessage<unscanned extends string> =
47
+ `Unmatched )${unscanned extends "" ? "" : ` before ${unscanned}`}`
48
+
49
+ export const writeUnclosedGroupMessage = <missingChar extends string>(
50
+ missingChar: missingChar
51
+ ): writeUnclosedGroupMessage<missingChar> => `Missing ${missingChar}`
52
+
53
+ export type writeUnclosedGroupMessage<missingChar extends string> =
54
+ `Missing ${missingChar}`
55
+
56
+ export const writeOpenRangeMessage = <
57
+ min extends LimitLiteral,
58
+ comparator extends MinComparator
59
+ >(
60
+ min: min,
61
+ comparator: comparator
62
+ ): writeOpenRangeMessage<min, comparator> =>
63
+ `Left bounds are only valid when paired with right bounds (try ...${comparator}${min})`
64
+
65
+ export type writeOpenRangeMessage<
66
+ min extends LimitLiteral,
67
+ comparator extends MinComparator
68
+ > = `Left bounds are only valid when paired with right bounds (try ...${comparator}${min})`
69
+
70
+ export type writeUnpairableComparatorMessage<comparator extends Comparator> =
71
+ `Left-bounded expressions must specify their limits using < or <= (was ${comparator})`
72
+
73
+ export const writeUnpairableComparatorMessage = <comparator extends Comparator>(
74
+ comparator: comparator
75
+ ): writeUnpairableComparatorMessage<comparator> =>
76
+ `Left-bounded expressions must specify their limits using < or <= (was ${comparator})`
77
+
78
+ export const writeMultipleLeftBoundsMessage = <
79
+ openLimit extends LimitLiteral,
80
+ openComparator extends MinComparator,
81
+ limit extends LimitLiteral,
82
+ comparator extends MinComparator
83
+ >(
84
+ openLimit: openLimit,
85
+ openComparator: openComparator,
86
+ limit: limit,
87
+ comparator: comparator
88
+ ): writeMultipleLeftBoundsMessage<
89
+ openLimit,
90
+ openComparator,
91
+ limit,
92
+ comparator
93
+ > =>
94
+ `An expression may have at most one left bound (parsed ${openLimit}${invertedComparators[openComparator]}, ${limit}${invertedComparators[comparator]})`
95
+
96
+ export type writeMultipleLeftBoundsMessage<
97
+ openLimit extends LimitLiteral,
98
+ openComparator extends MinComparator,
99
+ limit extends LimitLiteral,
100
+ comparator extends MinComparator
101
+ > = `An expression may have at most one left bound (parsed ${openLimit}${InvertedComparators[openComparator]}, ${limit}${InvertedComparators[comparator]})`