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
package/scope.ts ADDED
@@ -0,0 +1,574 @@
1
+ import {
2
+ BaseType,
3
+ keywords,
4
+ type ArkErrorCode,
5
+ type KeyCheckKind,
6
+ type TypeNode,
7
+ type extractIn,
8
+ type extractOut
9
+ } from "@arktype/schema"
10
+ import {
11
+ domainOf,
12
+ hasDomain,
13
+ isThunk,
14
+ map,
15
+ throwParseError,
16
+ type Dict,
17
+ type evaluate,
18
+ type isAny,
19
+ type nominal
20
+ } from "@arktype/util"
21
+ import type { type } from "./ark.js"
22
+ import { createMatchParser, type MatchParser } from "./match.js"
23
+ import {
24
+ parseObject,
25
+ writeBadDefinitionTypeMessage,
26
+ type inferDefinition,
27
+ type validateDefinition
28
+ } from "./parser/definition.js"
29
+ import {
30
+ parseGenericParams,
31
+ type GenericDeclaration,
32
+ type GenericParamsParseError
33
+ } from "./parser/generic.js"
34
+ import { DynamicState } from "./parser/string/reduce/dynamic.js"
35
+ import {
36
+ writeMissingSubmoduleAccessMessage,
37
+ writeNonSubmoduleDotMessage,
38
+ writeUnresolvableMessage
39
+ } from "./parser/string/shift/operand/unenclosed.js"
40
+ import { fullStringParse } from "./parser/string/string.js"
41
+ import {
42
+ Type,
43
+ createTypeParser,
44
+ generic,
45
+ validateUninstantiatedGeneric,
46
+ type DeclarationParser,
47
+ type DefinitionParser,
48
+ type Generic,
49
+ type GenericProps,
50
+ type TypeConfig,
51
+ type TypeParser
52
+ } from "./type.js"
53
+ import { addArkKind, hasArkKind, type arkKind } from "./util.js"
54
+
55
+ export type ScopeParser<parent, ambient> = {
56
+ <const def>(def: validateScope<def, parent & ambient>): Scope<{
57
+ exports: inferBootstrapped<{
58
+ exports: bootstrapExports<def>
59
+ locals: bootstrapLocals<def> & parent
60
+ ambient: ambient
61
+ }>
62
+ locals: inferBootstrapped<{
63
+ exports: bootstrapLocals<def>
64
+ locals: bootstrapExports<def> & parent
65
+ ambient: ambient
66
+ }>
67
+ ambient: ambient
68
+ }>
69
+ }
70
+
71
+ export type ScopeConfig = {
72
+ ambient?: Scope | null
73
+ codes?: Record<ArkErrorCode, { mustBe?: string }>
74
+ keys?: KeyCheckKind
75
+ }
76
+
77
+ type validateScope<def, $> = {
78
+ [k in keyof def]: parseScopeKey<k>["params"] extends []
79
+ ? // Not including Type here directly breaks inference
80
+ def[k] extends Type | PreparsedResolution
81
+ ? def[k]
82
+ : validateDefinition<def[k], $ & bootstrap<def>, {}>
83
+ : parseScopeKey<k>["params"] extends GenericParamsParseError
84
+ ? // use the full nominal type here to avoid an overlap between the
85
+ // error message and a possible value for the property
86
+ parseScopeKey<k>["params"][0]
87
+ : validateDefinition<
88
+ def[k],
89
+ $ & bootstrap<def>,
90
+ {
91
+ // once we support constraints on generic parameters, we'd use
92
+ // the base type here: https://github.com/arktypeio/arktype/issues/796
93
+ [param in parseScopeKey<k>["params"][number]]: unknown
94
+ }
95
+ >
96
+ }
97
+
98
+ export type bindThis<def> = { this: Def<def> }
99
+
100
+ /** nominal type for an unparsed definition used during scope bootstrapping */
101
+ type Def<def = {}> = nominal<def, "unparsed">
102
+
103
+ /** sentinel indicating a scope that will be associated with a generic has not yet been parsed */
104
+ export type UnparsedScope = "$"
105
+
106
+ type bootstrap<def> = bootstrapLocals<def> & bootstrapExports<def>
107
+
108
+ type bootstrapLocals<def> = bootstrapAliases<{
109
+ // intersection seems redundant but it is more efficient for TS to avoid
110
+ // mapping all the keys
111
+ [k in keyof def & PrivateDeclaration as extractPrivateKey<k>]: def[k]
112
+ }>
113
+
114
+ type bootstrapExports<def> = bootstrapAliases<{
115
+ [k in Exclude<keyof def, PrivateDeclaration>]: def[k]
116
+ }>
117
+
118
+ /** These are legal as values of a scope but not as definitions in other contexts */
119
+ type PreparsedResolution = Module | GenericProps
120
+
121
+ type bootstrapAliases<def> = {
122
+ [k in Exclude<
123
+ keyof def,
124
+ // avoid inferring nominal symbols, e.g. arkKind from Module
125
+ GenericDeclaration | symbol
126
+ >]: def[k] extends PreparsedResolution
127
+ ? def[k]
128
+ : def[k] extends (() => infer thunkReturn extends PreparsedResolution)
129
+ ? thunkReturn
130
+ : Def<def[k]>
131
+ } & {
132
+ [k in keyof def & GenericDeclaration as extractGenericName<k>]: Generic<
133
+ parseGenericParams<extractGenericParameters<k>>,
134
+ def[k],
135
+ UnparsedScope
136
+ >
137
+ }
138
+
139
+ type inferBootstrapped<r extends Resolutions> = evaluate<{
140
+ [name in keyof r["exports"]]: r["exports"][name] extends Def<infer def>
141
+ ? inferDefinition<def, $<r>, {}>
142
+ : r["exports"][name] extends GenericProps<infer params, infer def>
143
+ ? // add the scope in which the generic was defined here
144
+ Generic<params, def, $<r>>
145
+ : // otherwise should be a submodule
146
+ r["exports"][name]
147
+ }>
148
+
149
+ type extractGenericName<k> = k extends GenericDeclaration<infer name>
150
+ ? name
151
+ : never
152
+
153
+ type extractGenericParameters<k> = k extends GenericDeclaration<
154
+ string,
155
+ infer params
156
+ >
157
+ ? params
158
+ : never
159
+
160
+ type extractPrivateKey<k> = k extends PrivateDeclaration<infer key>
161
+ ? key
162
+ : never
163
+
164
+ type PrivateDeclaration<key extends string = string> = `#${key}`
165
+
166
+ export type resolve<reference extends keyof $ | keyof args, $, args> = (
167
+ reference extends keyof args ? args[reference] : $[reference & keyof $]
168
+ ) extends infer resolution
169
+ ? [resolution] extends [never]
170
+ ? never
171
+ : isAny<resolution> extends true
172
+ ? any
173
+ : resolution extends Def<infer def>
174
+ ? inferDefinition<def, $, args>
175
+ : resolution
176
+ : never
177
+
178
+ export type moduleKeyOf<$> = {
179
+ [k in keyof $]: $[k] extends Module ? k & string : never
180
+ }[keyof $]
181
+
182
+ export type tryInferSubmoduleReference<$, token> =
183
+ token extends `${infer submodule extends moduleKeyOf<$>}.${infer subalias}`
184
+ ? subalias extends keyof $[submodule]
185
+ ? $[submodule][subalias] extends Type<infer t>
186
+ ? t
187
+ : never
188
+ : never
189
+ : never
190
+
191
+ type $<r extends Resolutions> = r["exports"] & r["locals"] & r["ambient"]
192
+
193
+ type exportedName<r extends Resolutions> = keyof r["exports"] & string
194
+
195
+ export type Module<r extends Resolutions = any> = {
196
+ // just adding the nominal id this way and mapping it is cheaper than an intersection
197
+ [k in exportedName<r> | arkKind]: k extends string
198
+ ? [r["exports"][k]] extends [never]
199
+ ? Type<never, $<r>>
200
+ : isAny<r["exports"][k]> extends true
201
+ ? Type<any, $<r>>
202
+ : r["exports"][k] extends PreparsedResolution
203
+ ? r["exports"][k]
204
+ : Type<r["exports"][k], $<r>>
205
+ : // set the nominal symbol's value to something validation won't care about
206
+ // since the inferred type will be omitted anyways
207
+ type.cast<"module">
208
+ }
209
+
210
+ export type Resolutions = {
211
+ exports: unknown
212
+ locals: unknown
213
+ ambient: unknown
214
+ }
215
+
216
+ export type ParseContext = {
217
+ baseName: string
218
+ path: string[]
219
+ scope: Scope
220
+ args: Record<string, TypeNode> | undefined
221
+ }
222
+
223
+ type MergedResolutions = Record<string, TypeNode | Generic>
224
+
225
+ type ParseContextInput = Pick<ParseContext, "baseName" | "args">
226
+
227
+ export class Scope<r extends Resolutions = any> {
228
+ declare infer: extractOut<r["exports"]>
229
+ declare inferIn: extractIn<r["exports"]>
230
+
231
+ config: TypeConfig
232
+
233
+ private parseCache: Record<string, TypeNode> = {}
234
+ private resolutions: MergedResolutions
235
+
236
+ /** The set of names defined at the root-level of the scope mapped to their
237
+ * corresponding definitions.**/
238
+ aliases: Record<string, unknown> = {}
239
+ private exportedNames: exportedName<r>[] = []
240
+ private ambient: Scope | null
241
+
242
+ constructor(def: Dict, config: ScopeConfig) {
243
+ for (const k in def) {
244
+ const parsedKey = parseScopeKey(k)
245
+ this.aliases[parsedKey.name] = parsedKey.params.length
246
+ ? generic(parsedKey.params, def[k], this)
247
+ : def[k]
248
+ if (!parsedKey.isLocal) {
249
+ this.exportedNames.push(parsedKey.name as never)
250
+ }
251
+ }
252
+ this.ambient = config.ambient ?? null
253
+ if (this.ambient) {
254
+ // ensure exportedResolutions is populated
255
+ this.ambient.export()
256
+ this.resolutions = { ...this.ambient.exportedResolutions! }
257
+ } else {
258
+ this.resolutions = {}
259
+ }
260
+ this.config = config
261
+ }
262
+
263
+ static root: ScopeParser<{}, {}> = (aliases) => {
264
+ return new Scope(aliases, {}) as never
265
+ }
266
+
267
+ type: TypeParser<$<r>> = createTypeParser(this as never) as never
268
+
269
+ match: MatchParser<$<r>> = createMatchParser(this as never) as never
270
+
271
+ // TODO: decide if this API will be used for non-validated types
272
+ declare: DeclarationParser<$<r>> = () => ({ type: this.type }) as never
273
+
274
+ scope: ScopeParser<r["exports"], r["ambient"]> = ((
275
+ def: Dict,
276
+ config: TypeConfig = {}
277
+ ) => {
278
+ return new Scope(def, {
279
+ ambient: this.ambient,
280
+ ...this.config,
281
+ ...config
282
+ })
283
+ }) as never
284
+
285
+ define: DefinitionParser<$<r>> = (def) => def as never
286
+
287
+ toAmbient(): Scope<{
288
+ exports: r["exports"]
289
+ locals: r["locals"]
290
+ ambient: r["exports"]
291
+ }> {
292
+ // TODO: private?
293
+ return new Scope(this.aliases, {
294
+ ambient: this,
295
+ ...this.config
296
+ })
297
+ }
298
+
299
+ // TODO: name?
300
+ get<name extends keyof r["exports"] & string>(
301
+ name: name
302
+ ): Type<r["exports"][name], $<r>> {
303
+ return this.export()[name] as never
304
+ }
305
+
306
+ private createRootContext(input: ParseContextInput): ParseContext {
307
+ return {
308
+ path: [],
309
+ scope: this,
310
+ ...input
311
+ }
312
+ }
313
+
314
+ parseDefinition(def: unknown, input: ParseContextInput) {
315
+ return this.parse(def, this.createRootContext(input))
316
+ }
317
+
318
+ parse(def: unknown, ctx: ParseContext): TypeNode {
319
+ if (typeof def === "string") {
320
+ if (ctx.args !== undefined) {
321
+ // we can only rely on the cache if there are no contextual
322
+ // resolutions like "this" or generic args
323
+ return this.parseString(def, ctx)
324
+ }
325
+ if (!this.parseCache[def]) {
326
+ this.parseCache[def] = this.parseString(def, ctx)
327
+ }
328
+ return this.parseCache[def]
329
+ }
330
+ return hasDomain(def, "object")
331
+ ? parseObject(def, ctx)
332
+ : throwParseError(writeBadDefinitionTypeMessage(domainOf(def)))
333
+ }
334
+
335
+ parseString(def: string, ctx: ParseContext): TypeNode {
336
+ return (
337
+ this.maybeResolveNode(def) ??
338
+ ((def.endsWith("[]") &&
339
+ this.maybeResolveNode(def.slice(0, -2))?.array()) ||
340
+ fullStringParse(new DynamicState(def, ctx)))
341
+ )
342
+ }
343
+
344
+ maybeResolve(name: string): TypeNode | Generic | undefined {
345
+ const cached = this.resolutions[name]
346
+ if (cached) {
347
+ return cached
348
+ }
349
+ let def = this.aliases[name]
350
+ if (!def) {
351
+ return this.maybeResolveSubalias(name)
352
+ }
353
+ if (isThunk(def) && !hasArkKind(def, "generic")) {
354
+ def = def()
355
+ }
356
+ // TODO: initialize here?
357
+ const resolution = hasArkKind(def, "generic")
358
+ ? validateUninstantiatedGeneric(def)
359
+ : hasArkKind(def, "module")
360
+ ? throwParseError(writeMissingSubmoduleAccessMessage(name))
361
+ : this.parseDefinition(
362
+ def,
363
+ this.createRootContext({ baseName: name, args: {} })
364
+ )
365
+ this.resolutions[name] = resolution
366
+ return resolution
367
+ }
368
+
369
+ /** If name is a valid reference to a submodule alias, return its resolution */
370
+ private maybeResolveSubalias(name: string) {
371
+ const dotIndex = name.indexOf(".")
372
+ if (dotIndex === -1) {
373
+ return
374
+ }
375
+ const dotPrefix = name.slice(0, dotIndex)
376
+ const prefixDef = this.aliases[dotPrefix]
377
+ if (hasArkKind(prefixDef, "module")) {
378
+ const resolution = prefixDef[name.slice(dotIndex + 1)]?.root
379
+ // if the first part of name is a submodule but the suffix is
380
+ // unresolvable, we can throw immediately
381
+ if (!resolution) {
382
+ return throwParseError(writeUnresolvableMessage(name))
383
+ }
384
+ this.resolutions[name] = resolution
385
+ return resolution
386
+ }
387
+ if (prefixDef !== undefined) {
388
+ return throwParseError(writeNonSubmoduleDotMessage(dotPrefix))
389
+ }
390
+ // if the name includes ".", but the prefix is not an alias, it
391
+ // might be something like a decimal literal, so just fall through to return
392
+ }
393
+
394
+ maybeResolveNode(name: string): TypeNode | undefined {
395
+ const result = this.maybeResolve(name)
396
+ return result instanceof BaseType ? (result as never) : undefined
397
+ }
398
+
399
+ import<names extends exportedName<r>[]>(
400
+ ...names: names
401
+ ): destructuredImportContext<
402
+ r,
403
+ names extends [] ? keyof r["exports"] & string : names[number]
404
+ > {
405
+ return addArkKind(
406
+ map(this.export(...names) as Dict, (alias, value) => [
407
+ `#${alias}`,
408
+ value
409
+ ]) as never,
410
+ "module"
411
+ ) as never
412
+ }
413
+
414
+ compile() {
415
+ return ""
416
+ // this.export()
417
+ // const references: Set<Root> = new Set()
418
+ // for (const k in this.exportedResolutions!) {
419
+ // const resolution = this.exportedResolutions[k]
420
+ // if (hasArkKind(resolution, "node") && !references.has(resolution)) {
421
+ // for (const reference of resolution.references) {
422
+ // references.add(reference)
423
+ // }
424
+ // }
425
+ // }
426
+ // return [...references]
427
+ // .map(
428
+ // (ref) => `const ${ref.alias} = (${In}) => {
429
+ // ${ref.condition}
430
+ // return true
431
+ // }`
432
+ // )
433
+ // .join("\n")
434
+ }
435
+
436
+ bindThis() {
437
+ // TODO: fix
438
+ return { this: keywords.unknown }
439
+ }
440
+
441
+ private exportedResolutions: MergedResolutions | undefined
442
+ private exportCache: ExportCache | undefined
443
+ export<names extends exportedName<r>[]>(
444
+ ...names: names
445
+ ): Module<
446
+ names extends [] ? r : destructuredExportContext<r, names[number]>
447
+ > {
448
+ if (!this.exportCache) {
449
+ this.exportCache = {}
450
+ for (const name of this.exportedNames) {
451
+ let def = this.aliases[name]
452
+ if (hasArkKind(def, "generic")) {
453
+ this.exportCache[name] = def
454
+ continue
455
+ }
456
+ // TODO: thunk generics?
457
+ // handle generics before invoking thunks, since they use
458
+ // varargs they will incorrectly be considered thunks
459
+ if (isThunk(def)) {
460
+ def = def()
461
+ }
462
+ if (hasArkKind(def, "module")) {
463
+ this.exportCache[name] = def
464
+ } else {
465
+ this.exportCache[name] = new Type(this.maybeResolve(name), this)
466
+ }
467
+ }
468
+ this.exportedResolutions = resolutionsOfModule(this.exportCache)
469
+ Object.assign(this.resolutions, this.exportedResolutions)
470
+ }
471
+ const namesToExport = names.length ? names : this.exportedNames
472
+ return addArkKind(
473
+ map(namesToExport, (_, name) => [name, this.exportCache![name]]) as never,
474
+ "module"
475
+ ) as never
476
+ }
477
+ }
478
+
479
+ type ExportCache = Record<string, Type | Generic | Module>
480
+
481
+ const resolutionsOfModule = (typeSet: ExportCache) => {
482
+ const result: MergedResolutions = {}
483
+ for (const k in typeSet) {
484
+ const v = typeSet[k]
485
+ if (hasArkKind(v, "module")) {
486
+ const innerResolutions = resolutionsOfModule(v as never)
487
+ const prefixedResolutions = map(innerResolutions, (innerK, innerV) => [
488
+ `${k}.${innerK}`,
489
+ innerV
490
+ ])
491
+ Object.assign(result, prefixedResolutions)
492
+ } else if (hasArkKind(v, "generic")) {
493
+ result[k] = v
494
+ } else {
495
+ result[k] = (v as Type).root
496
+ }
497
+ }
498
+ return result
499
+ }
500
+
501
+ type destructuredExportContext<
502
+ r extends Resolutions,
503
+ name extends exportedName<r>
504
+ > = {
505
+ exports: { [k in name]: r["exports"][k] }
506
+ locals: r["locals"] & {
507
+ [k in Exclude<keyof r["exports"], name>]: r["exports"][k]
508
+ }
509
+ ambient: r["ambient"]
510
+ }
511
+
512
+ type destructuredImportContext<
513
+ r extends Resolutions,
514
+ name extends exportedName<r>
515
+ > = {
516
+ [k in name as `#${k & string}`]: type.cast<r["exports"][k]>
517
+ }
518
+
519
+ export const writeShallowCycleErrorMessage = (name: string, seen: string[]) =>
520
+ `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join(":")}`
521
+
522
+ export const writeDuplicateNameMessage = <name extends string>(
523
+ name: name
524
+ ): writeDuplicateNameMessage<name> => `Duplicate name '${name}'`
525
+
526
+ type writeDuplicateNameMessage<name extends string> = `Duplicate name '${name}'`
527
+
528
+ export type ParsedScopeKey = {
529
+ isLocal: boolean
530
+ name: string
531
+ params: string[]
532
+ }
533
+
534
+ export const parseScopeKey = (k: string): ParsedScopeKey => {
535
+ const isLocal = k[0] === "#"
536
+ const name = isLocal ? k.slice(1) : k
537
+ const firstParamIndex = k.indexOf("<")
538
+ if (firstParamIndex === -1) {
539
+ return {
540
+ isLocal,
541
+ name,
542
+ params: []
543
+ }
544
+ }
545
+ if (k.at(-1) !== ">") {
546
+ throwParseError(
547
+ `'>' must be the last character of a generic declaration in a scope`
548
+ )
549
+ }
550
+ return {
551
+ isLocal,
552
+ name: name.slice(0, firstParamIndex),
553
+ params: parseGenericParams(k.slice(firstParamIndex + 1, -1))
554
+ }
555
+ }
556
+
557
+ type parseScopeKey<k> = k extends PrivateDeclaration<infer inner>
558
+ ? parsePossibleGenericDeclaration<inner, true>
559
+ : parsePossibleGenericDeclaration<k, false>
560
+
561
+ type parsePossibleGenericDeclaration<
562
+ k,
563
+ isLocal extends boolean
564
+ > = k extends GenericDeclaration<infer name, infer paramString>
565
+ ? {
566
+ isLocal: isLocal
567
+ name: name
568
+ params: parseGenericParams<paramString>
569
+ }
570
+ : {
571
+ isLocal: isLocal
572
+ name: k
573
+ params: []
574
+ }