arktype 2.0.0-dev.5 → 2.0.0-dev.6

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 (376) hide show
  1. package/__tests__/array.test.ts +70 -38
  2. package/__tests__/badDefinitionType.test.ts +9 -2
  3. package/__tests__/basis.test.ts +6 -2
  4. package/__tests__/bounds.test.ts +49 -218
  5. package/__tests__/cast.test.ts +7 -2
  6. package/__tests__/completions.test.ts +8 -3
  7. package/__tests__/config.test.ts +8 -2
  8. package/__tests__/cyclic.test.ts +141 -137
  9. package/__tests__/dateLiteral.test.ts +6 -2
  10. package/__tests__/declared.test.ts +2 -2
  11. package/__tests__/divisor.test.ts +28 -12
  12. package/__tests__/enclosed.test.ts +32 -23
  13. package/__tests__/examples.test.ts +56 -56
  14. package/__tests__/expressions.test.ts +184 -106
  15. package/__tests__/generic.test.ts +307 -287
  16. package/__tests__/group.test.ts +59 -51
  17. package/__tests__/imports.test.ts +44 -37
  18. package/__tests__/instanceof.test.ts +14 -12
  19. package/__tests__/intersection.test.ts +16 -36
  20. package/__tests__/keyTraversal.test.ts +6 -1
  21. package/__tests__/keyof.test.ts +57 -43
  22. package/__tests__/keywords.test.ts +144 -135
  23. package/__tests__/literal.test.ts +12 -7
  24. package/__tests__/match.test.ts +234 -236
  25. package/__tests__/morph.test.ts +169 -153
  26. package/__tests__/narrow.test.ts +14 -9
  27. package/__tests__/objectLiteral.test.ts +172 -184
  28. package/__tests__/realWorld.test.ts +60 -59
  29. package/__tests__/regex.test.ts +17 -7
  30. package/__tests__/scope.test.ts +59 -14
  31. package/__tests__/serialization.test.ts +19 -0
  32. package/__tests__/string.test.ts +11 -7
  33. package/__tests__/submodule.test.ts +24 -37
  34. package/__tests__/this.test.ts +83 -57
  35. package/__tests__/thunk.test.ts +13 -7
  36. package/__tests__/traverse.test.ts +22 -12
  37. package/__tests__/tsGenerics.test.ts +12 -12
  38. package/__tests__/type.test.ts +38 -0
  39. package/__tests__/typeReference.test.ts +5 -5
  40. package/__tests__/unenclosed.test.ts +106 -96
  41. package/__tests__/union.test.ts +207 -212
  42. package/ark.ts +44 -0
  43. package/generic.ts +67 -0
  44. package/main.ts +6 -17
  45. package/match.ts +41 -51
  46. package/module.ts +15 -0
  47. package/out/ark.d.ts +12 -40
  48. package/out/ark.d.ts.map +1 -1
  49. package/out/ark.js +9 -20
  50. package/out/ark.js.map +1 -1
  51. package/out/base.d.ts +198 -122
  52. package/out/base.d.ts.map +1 -1
  53. package/out/base.js +317 -271
  54. package/out/base.js.map +1 -1
  55. package/out/builtins/builtins.d.ts +21 -17
  56. package/out/builtins/builtins.js +15 -12
  57. package/out/builtins/jsObjects.d.ts +17 -17
  58. package/out/builtins/jsObjects.js +18 -15
  59. package/out/builtins/parsing.d.ts +13 -13
  60. package/out/builtins/parsing.js +57 -54
  61. package/out/builtins/tsGenerics.d.ts +2 -2
  62. package/out/builtins/tsGenerics.js +2 -2
  63. package/out/builtins/tsKeywords.d.ts +21 -21
  64. package/out/builtins/tsKeywords.js +23 -20
  65. package/out/builtins/utils/creditCard.d.ts +3 -3
  66. package/out/builtins/utils/creditCard.js +31 -32
  67. package/out/builtins/utils/date.d.ts +39 -20
  68. package/out/builtins/utils/date.js +51 -48
  69. package/out/builtins/validation.d.ts +17 -17
  70. package/out/builtins/validation.js +66 -62
  71. package/out/config.d.ts +9 -6
  72. package/out/config.js +17 -16
  73. package/out/constraints/ast.d.ts +263 -152
  74. package/out/constraints/ast.js +2 -2
  75. package/out/constraints/constraint.d.ts +196 -66
  76. package/out/constraints/constraint.js +21 -17
  77. package/out/constraints/predicate.d.ts +60 -42
  78. package/out/constraints/predicate.js +48 -43
  79. package/out/constraints/props/index.d.ts +35 -29
  80. package/out/constraints/props/index.js +54 -46
  81. package/out/constraints/props/optional.d.ts +31 -28
  82. package/out/constraints/props/optional.js +54 -53
  83. package/out/constraints/props/prop.d.ts +42 -39
  84. package/out/constraints/props/prop.js +104 -102
  85. package/out/constraints/props/props.d.ts +35 -32
  86. package/out/constraints/props/props.js +117 -102
  87. package/out/constraints/props/props.js.map +1 -1
  88. package/out/constraints/props/required.d.ts +40 -37
  89. package/out/constraints/props/required.js +78 -73
  90. package/out/constraints/props/sequence.d.ts +74 -56
  91. package/out/constraints/props/sequence.js +371 -322
  92. package/out/constraints/props/shared.d.ts +3 -3
  93. package/out/constraints/props/shared.js +4 -4
  94. package/out/constraints/refinements/after.d.ts +26 -18
  95. package/out/constraints/refinements/after.js +34 -33
  96. package/out/constraints/refinements/before.d.ts +26 -18
  97. package/out/constraints/refinements/before.js +41 -39
  98. package/out/constraints/refinements/divisor.d.ts +47 -37
  99. package/out/constraints/refinements/divisor.js +48 -37
  100. package/out/constraints/refinements/exactLength.d.ts +40 -36
  101. package/out/constraints/refinements/exactLength.js +50 -42
  102. package/out/constraints/refinements/kinds.d.ts +25 -25
  103. package/out/constraints/refinements/kinds.js +16 -16
  104. package/out/constraints/refinements/length.d.ts +45 -39
  105. package/out/constraints/refinements/length.js +51 -43
  106. package/out/constraints/refinements/max.d.ts +24 -17
  107. package/out/constraints/refinements/max.js +33 -29
  108. package/out/constraints/refinements/maxLength.d.ts +25 -17
  109. package/out/constraints/refinements/maxLength.js +34 -32
  110. package/out/constraints/refinements/min.d.ts +24 -17
  111. package/out/constraints/refinements/min.js +26 -23
  112. package/out/constraints/refinements/minLength.d.ts +25 -17
  113. package/out/constraints/refinements/minLength.js +31 -30
  114. package/out/constraints/refinements/range.d.ts +107 -78
  115. package/out/constraints/refinements/range.js +83 -66
  116. package/out/constraints/refinements/regex.d.ts +42 -38
  117. package/out/constraints/refinements/regex.js +35 -34
  118. package/out/constraints/refinements/shared.d.ts +20 -5
  119. package/out/constraints/refinements/shared.js +9 -9
  120. package/out/generic.d.ts +22 -0
  121. package/out/generic.d.ts.map +1 -0
  122. package/out/generic.js +23 -0
  123. package/out/generic.js.map +1 -0
  124. package/out/inference.d.ts +132 -35
  125. package/out/inference.js +2 -2
  126. package/out/keywords/ark.d.ts +60 -50
  127. package/out/keywords/ark.js +25 -25
  128. package/out/keywords/internal.d.ts +11 -11
  129. package/out/keywords/internal.js +13 -10
  130. package/out/keywords/jsObject.d.ts +18 -18
  131. package/out/keywords/jsObject.js +18 -15
  132. package/out/keywords/parsing.d.ts +14 -14
  133. package/out/keywords/parsing.js +53 -50
  134. package/out/keywords/root.d.ts +6 -6
  135. package/out/keywords/root.js +4 -4
  136. package/out/keywords/tsGenerics.d.ts +2 -2
  137. package/out/keywords/tsGenerics.js +2 -2
  138. package/out/keywords/tsPrimitive.d.ts +22 -22
  139. package/out/keywords/tsPrimitive.js +25 -22
  140. package/out/keywords/utils/creditCard.d.ts +11 -8
  141. package/out/keywords/utils/creditCard.js +31 -32
  142. package/out/keywords/utils/date.d.ts +43 -23
  143. package/out/keywords/utils/date.js +51 -48
  144. package/out/keywords/validation.d.ts +18 -18
  145. package/out/keywords/validation.js +67 -63
  146. package/out/kinds.d.ts +97 -67
  147. package/out/kinds.js +28 -28
  148. package/out/main.d.ts +6 -7
  149. package/out/main.d.ts.map +1 -1
  150. package/out/main.js +4 -2
  151. package/out/main.js.map +1 -1
  152. package/out/match.d.ts +6 -10
  153. package/out/match.d.ts.map +1 -1
  154. package/out/match.js +1 -1
  155. package/out/match.js.map +1 -1
  156. package/out/module.d.ts +11 -0
  157. package/out/module.d.ts.map +1 -0
  158. package/out/module.js +4 -0
  159. package/out/module.js.map +1 -0
  160. package/out/parse.d.ts +28 -22
  161. package/out/parse.js +157 -144
  162. package/out/parser/definition.d.ts +8 -10
  163. package/out/parser/definition.d.ts.map +1 -1
  164. package/out/parser/definition.js +5 -6
  165. package/out/parser/definition.js.map +1 -1
  166. package/out/parser/generic.d.ts +3 -4
  167. package/out/parser/generic.d.ts.map +1 -1
  168. package/out/parser/generic.js +6 -8
  169. package/out/parser/generic.js.map +1 -1
  170. package/out/parser/objectLiteral.d.ts +5 -6
  171. package/out/parser/objectLiteral.d.ts.map +1 -1
  172. package/out/parser/objectLiteral.js +10 -15
  173. package/out/parser/objectLiteral.js.map +1 -1
  174. package/out/parser/semantic/bounds.d.ts +4 -3
  175. package/out/parser/semantic/bounds.d.ts.map +1 -1
  176. package/out/parser/semantic/bounds.js.map +1 -1
  177. package/out/parser/semantic/divisor.d.ts +4 -3
  178. package/out/parser/semantic/divisor.d.ts.map +1 -1
  179. package/out/parser/semantic/infer.d.ts +7 -10
  180. package/out/parser/semantic/infer.d.ts.map +1 -1
  181. package/out/parser/semantic/utils.d.ts.map +1 -1
  182. package/out/parser/semantic/validate.d.ts +13 -11
  183. package/out/parser/semantic/validate.d.ts.map +1 -1
  184. package/out/parser/semantic/validate.js +1 -0
  185. package/out/parser/semantic/validate.js.map +1 -1
  186. package/out/parser/string/reduce/dynamic.d.ts +7 -8
  187. package/out/parser/string/reduce/dynamic.d.ts.map +1 -1
  188. package/out/parser/string/reduce/dynamic.js +26 -22
  189. package/out/parser/string/reduce/dynamic.js.map +1 -1
  190. package/out/parser/string/reduce/shared.d.ts +2 -2
  191. package/out/parser/string/reduce/shared.d.ts.map +1 -1
  192. package/out/parser/string/reduce/static.d.ts +8 -5
  193. package/out/parser/string/reduce/static.d.ts.map +1 -1
  194. package/out/parser/string/shift/operand/date.d.ts +1 -1
  195. package/out/parser/string/shift/operand/date.d.ts.map +1 -1
  196. package/out/parser/string/shift/operand/date.js +2 -2
  197. package/out/parser/string/shift/operand/date.js.map +1 -1
  198. package/out/parser/string/shift/operand/enclosed.d.ts +1 -1
  199. package/out/parser/string/shift/operand/enclosed.d.ts.map +1 -1
  200. package/out/parser/string/shift/operand/enclosed.js +1 -1
  201. package/out/parser/string/shift/operand/enclosed.js.map +1 -1
  202. package/out/parser/string/shift/operand/genericArgs.d.ts +8 -8
  203. package/out/parser/string/shift/operand/genericArgs.d.ts.map +1 -1
  204. package/out/parser/string/shift/operand/genericArgs.js +6 -8
  205. package/out/parser/string/shift/operand/genericArgs.js.map +1 -1
  206. package/out/parser/string/shift/operand/operand.d.ts +3 -3
  207. package/out/parser/string/shift/operand/operand.d.ts.map +1 -1
  208. package/out/parser/string/shift/operand/operand.js +8 -11
  209. package/out/parser/string/shift/operand/operand.js.map +1 -1
  210. package/out/parser/string/shift/operand/unenclosed.d.ts +10 -16
  211. package/out/parser/string/shift/operand/unenclosed.d.ts.map +1 -1
  212. package/out/parser/string/shift/operand/unenclosed.js +19 -24
  213. package/out/parser/string/shift/operand/unenclosed.js.map +1 -1
  214. package/out/parser/string/shift/operator/bounds.d.ts +6 -8
  215. package/out/parser/string/shift/operator/bounds.d.ts.map +1 -1
  216. package/out/parser/string/shift/operator/bounds.js +20 -29
  217. package/out/parser/string/shift/operator/bounds.js.map +1 -1
  218. package/out/parser/string/shift/operator/divisor.d.ts +1 -2
  219. package/out/parser/string/shift/operator/divisor.d.ts.map +1 -1
  220. package/out/parser/string/shift/operator/divisor.js.map +1 -1
  221. package/out/parser/string/shift/operator/operator.d.ts +1 -1
  222. package/out/parser/string/shift/operator/operator.d.ts.map +1 -1
  223. package/out/parser/string/shift/operator/operator.js +12 -18
  224. package/out/parser/string/shift/operator/operator.js.map +1 -1
  225. package/out/parser/string/shift/scanner.d.ts +2 -1
  226. package/out/parser/string/shift/scanner.d.ts.map +1 -1
  227. package/out/parser/string/shift/scanner.js +12 -11
  228. package/out/parser/string/shift/scanner.js.map +1 -1
  229. package/out/parser/string/string.d.ts +7 -4
  230. package/out/parser/string/string.d.ts.map +1 -1
  231. package/out/parser/string/string.js.map +1 -1
  232. package/out/parser/tuple.d.ts +27 -30
  233. package/out/parser/tuple.d.ts.map +1 -1
  234. package/out/parser/tuple.js +33 -35
  235. package/out/parser/tuple.js.map +1 -1
  236. package/out/schema.d.ts +171 -40
  237. package/out/schema.js +2 -2
  238. package/out/schemaScope.d.ts +170 -100
  239. package/out/schemaScope.js +231 -208
  240. package/out/scope.d.ts +43 -187
  241. package/out/scope.d.ts.map +1 -1
  242. package/out/scope.js +56 -326
  243. package/out/scope.js.map +1 -1
  244. package/out/shared/compile.d.ts +19 -19
  245. package/out/shared/compile.js +77 -65
  246. package/out/shared/context.d.ts +51 -26
  247. package/out/shared/context.js +50 -45
  248. package/out/shared/declare.d.ts +61 -45
  249. package/out/shared/declare.js +2 -2
  250. package/out/shared/disjoint.d.ts +85 -73
  251. package/out/shared/disjoint.js +108 -80
  252. package/out/shared/disjoint.js.map +1 -1
  253. package/out/shared/errors.d.ts +85 -45
  254. package/out/shared/errors.js +101 -101
  255. package/out/shared/implement.d.ts +351 -158
  256. package/out/shared/implement.js +61 -62
  257. package/out/shared/implement.js.map +1 -1
  258. package/out/shared/inference.d.ts +5 -5
  259. package/out/shared/inference.js +2 -2
  260. package/out/shared/intersections.d.ts +57 -12
  261. package/out/shared/intersections.js +2 -2
  262. package/out/shared/traversal.d.ts +57 -39
  263. package/out/shared/traversal.js +95 -95
  264. package/out/shared/utils.d.ts +23 -7
  265. package/out/shared/utils.d.ts.map +1 -1
  266. package/out/shared/utils.js +14 -9
  267. package/out/shared/utils.js.map +1 -1
  268. package/out/type.d.ts +24 -32
  269. package/out/type.d.ts.map +1 -1
  270. package/out/type.js +2 -51
  271. package/out/type.js.map +1 -1
  272. package/out/types/basis.d.ts +44 -21
  273. package/out/types/basis.js +13 -13
  274. package/out/types/discriminate.d.ts +33 -19
  275. package/out/types/discriminate.js +116 -110
  276. package/out/types/domain.d.ts +54 -37
  277. package/out/types/domain.js +39 -36
  278. package/out/types/intersection.d.ts +121 -61
  279. package/out/types/intersection.js +355 -326
  280. package/out/types/morph.d.ts +148 -70
  281. package/out/types/morph.js +97 -93
  282. package/out/types/proto.d.ts +48 -39
  283. package/out/types/proto.js +58 -46
  284. package/out/types/type.d.ts +137 -55
  285. package/out/types/type.d.ts.map +1 -1
  286. package/out/types/type.js +121 -109
  287. package/out/types/type.js.map +1 -1
  288. package/out/types/union.d.ts +66 -43
  289. package/out/types/union.js +299 -257
  290. package/out/types/unit.d.ts +41 -36
  291. package/out/types/unit.js +53 -45
  292. package/out/util.d.ts +30 -21
  293. package/out/util.js +8 -7
  294. package/package.json +3 -2
  295. package/parser/definition.ts +64 -81
  296. package/parser/generic.ts +35 -36
  297. package/parser/objectLiteral.ts +78 -92
  298. package/parser/semantic/bounds.ts +25 -33
  299. package/parser/semantic/divisor.ts +7 -11
  300. package/parser/semantic/infer.ts +69 -80
  301. package/parser/semantic/utils.ts +10 -13
  302. package/parser/semantic/validate.ts +81 -71
  303. package/parser/string/reduce/dynamic.ts +42 -39
  304. package/parser/string/reduce/shared.ts +1 -1
  305. package/parser/string/reduce/static.ts +50 -52
  306. package/parser/string/shift/operand/date.ts +5 -5
  307. package/parser/string/shift/operand/enclosed.ts +12 -13
  308. package/parser/string/shift/operand/genericArgs.ts +45 -44
  309. package/parser/string/shift/operand/operand.ts +32 -37
  310. package/parser/string/shift/operand/unenclosed.ts +99 -134
  311. package/parser/string/shift/operator/bounds.ts +78 -75
  312. package/parser/string/shift/operator/divisor.ts +11 -13
  313. package/parser/string/shift/operator/operator.ts +35 -46
  314. package/parser/string/shift/scanner.ts +39 -36
  315. package/parser/string/string.ts +26 -30
  316. package/parser/tuple.ts +206 -248
  317. package/scope.ts +185 -704
  318. package/type.ts +101 -140
  319. package/__tests__/errors.test.ts +0 -115
  320. package/__tests__/schema.bench.ts +0 -14
  321. package/__tests__/schema.test.ts +0 -60
  322. package/__tests__/typeMethods.test.ts +0 -68
  323. package/__tests__/unit.test.ts +0 -61
  324. package/base.ts +0 -520
  325. package/config.ts +0 -25
  326. package/constraints/ast.ts +0 -288
  327. package/constraints/constraint.ts +0 -91
  328. package/constraints/predicate.ts +0 -102
  329. package/constraints/props/index.ts +0 -93
  330. package/constraints/props/prop.ts +0 -146
  331. package/constraints/props/props.ts +0 -148
  332. package/constraints/props/sequence.ts +0 -473
  333. package/constraints/props/shared.ts +0 -5
  334. package/constraints/refinements/after.ts +0 -68
  335. package/constraints/refinements/before.ts +0 -75
  336. package/constraints/refinements/divisor.ts +0 -76
  337. package/constraints/refinements/exactLength.ts +0 -75
  338. package/constraints/refinements/kinds.ts +0 -31
  339. package/constraints/refinements/max.ts +0 -61
  340. package/constraints/refinements/maxLength.ts +0 -66
  341. package/constraints/refinements/min.ts +0 -54
  342. package/constraints/refinements/minLength.ts +0 -63
  343. package/constraints/refinements/range.ts +0 -181
  344. package/constraints/refinements/regex.ts +0 -59
  345. package/keywords/ark.ts +0 -101
  346. package/keywords/internal.ts +0 -29
  347. package/keywords/jsObject.ts +0 -39
  348. package/keywords/parsing.ts +0 -87
  349. package/keywords/root.ts +0 -9
  350. package/keywords/tsGenerics.ts +0 -28
  351. package/keywords/tsPrimitive.ts +0 -52
  352. package/keywords/utils/creditCard.ts +0 -37
  353. package/keywords/utils/date.ts +0 -112
  354. package/keywords/validation.ts +0 -115
  355. package/kinds.ts +0 -115
  356. package/parse.ts +0 -221
  357. package/schema.ts +0 -263
  358. package/shared/compile.ts +0 -92
  359. package/shared/declare.ts +0 -75
  360. package/shared/disjoint.ts +0 -203
  361. package/shared/errors.ts +0 -204
  362. package/shared/implement.ts +0 -327
  363. package/shared/inference.ts +0 -9
  364. package/shared/intersections.ts +0 -53
  365. package/shared/traversal.ts +0 -146
  366. package/shared/utils.ts +0 -30
  367. package/types/basis.ts +0 -62
  368. package/types/discriminate.ts +0 -168
  369. package/types/domain.ts +0 -79
  370. package/types/intersection.ts +0 -539
  371. package/types/morph.ts +0 -263
  372. package/types/proto.ts +0 -89
  373. package/types/type.ts +0 -319
  374. package/types/union.ts +0 -451
  375. package/types/unit.ts +0 -78
  376. package/util.ts +0 -39
package/scope.ts CHANGED
@@ -1,212 +1,79 @@
1
1
  import {
2
- CompiledFunction,
2
+ type ArkConfig,
3
+ type GenericProps,
4
+ type NodeParseOptions,
5
+ type PreparsedNodeResolution,
6
+ type RawSchema,
7
+ type RawSchemaResolutions,
8
+ RawSchemaScope,
9
+ type SchemaScope,
10
+ type ambient,
11
+ type arkKind,
12
+ type destructuredExportContext,
13
+ type destructuredImportContext,
14
+ type exportedNameOf,
15
+ hasArkKind
16
+ } from "@arktype/schema"
17
+ import {
18
+ type Dict,
3
19
  domainOf,
4
20
  hasDomain,
5
- isArray,
6
21
  isThunk,
7
- morph,
8
- throwInternalError,
9
- throwParseError,
10
- type Dict,
11
- type Json,
12
- type array,
13
- type evaluate,
14
- type isAny,
15
22
  type nominal,
16
- type requireKeys
23
+ type show,
24
+ throwParseError
17
25
  } from "@arktype/util"
18
- import { typeKindOfSchema, type UnknownNode } from "./base.js"
19
- import { globalConfig, mergeConfigs } from "./config.js"
20
- import type { type } from "./keywords/ark.js"
21
- import type { internalPrimitiveKeywords } from "./keywords/internal.js"
22
- import type { jsObjectKeywords } from "./keywords/jsObject.js"
23
- import type { tsPrimitiveKeywords } from "./keywords/tsPrimitive.js"
24
- import { nodesByKind } from "./kinds.js"
25
- import { createMatchParser, type MatchParser } from "./match.js"
26
- import { parseAttachments, type SchemaParseOptions } from "./parse.js"
26
+ import type { type } from "./ark.js"
27
+ import { Generic } from "./generic.js"
28
+ import { type MatchParser, createMatchParser } from "./match.js"
29
+ import type { Module } from "./module.js"
27
30
  import {
28
- parseObject,
29
- writeBadDefinitionTypeMessage,
30
31
  type inferDefinition,
31
- type validateDefinition
32
+ parseObject,
33
+ type validateDefinition,
34
+ writeBadDefinitionTypeMessage
32
35
  } from "./parser/definition.js"
33
36
  import {
34
- parseGenericParams,
35
37
  type GenericDeclaration,
36
- type GenericParamsParseError
38
+ type GenericParamsParseError,
39
+ parseGenericParams
37
40
  } from "./parser/generic.js"
38
41
  import { DynamicState } from "./parser/string/reduce/dynamic.js"
39
- import {
40
- writeMissingSubmoduleAccessMessage,
41
- writeNonSubmoduleDotMessage,
42
- writeUnresolvableMessage
43
- } from "./parser/string/shift/operand/unenclosed.js"
44
42
  import { fullStringParse } from "./parser/string/string.js"
45
- import type { NodeParser, SchemaParser } from "./schema.js"
46
- import { NodeCompiler } from "./shared/compile.js"
47
43
  import type {
48
- ActualWriter,
49
- ArkErrorCode,
50
- ExpectedWriter,
51
- MessageWriter,
52
- ProblemWriter
53
- } from "./shared/errors.js"
54
- import {
55
- isNodeKind,
56
- type DescriptionWriter,
57
- type NodeKind,
58
- type TypeKind
59
- } from "./shared/implement.js"
60
- import type { TraverseAllows, TraverseApply } from "./shared/traversal.js"
61
- import {
62
- createTypeParser,
63
- generic,
64
- validateUninstantiatedGeneric,
65
- type DeclarationParser,
66
- type DefinitionParser,
67
- type Generic,
68
- type GenericProps,
69
- type TypeParser
44
+ DeclarationParser,
45
+ DefinitionParser,
46
+ Type,
47
+ TypeParser
70
48
  } from "./type.js"
71
- import type {
72
- distillConstrainableIn,
73
- distillConstrainableOut
74
- } from "./types/morph.js"
75
- import { BaseType, type Type } from "./types/type.js"
76
- import type { UnionNode } from "./types/union.js"
77
- import type { UnitNode } from "./types/unit.js"
78
- import { addArkKind, hasArkKind, type arkKind } from "./util.js"
79
-
80
- export type nodeResolutions<keywords> = { [k in keyof keywords]: Type }
81
-
82
- export type BaseResolutions = Record<string, Type>
83
-
84
- declare global {
85
- export interface StaticArkConfig {
86
- preserve(): never
87
- }
88
- }
89
49
 
90
- type nodeConfigForKind<kind extends NodeKind> = Readonly<
91
- evaluate<
92
- {
93
- description?: DescriptionWriter<kind>
94
- } & (kind extends ArkErrorCode
95
- ? {
96
- expected?: ExpectedWriter<kind>
97
- actual?: ActualWriter<kind>
98
- problem?: ProblemWriter<kind>
99
- message?: MessageWriter<kind>
100
- }
101
- : {})
102
- >
103
- >
104
-
105
- type NodeConfigsByKind = {
106
- [kind in NodeKind]: nodeConfigForKind<kind>
107
- }
108
-
109
- export type NodeConfig<kind extends NodeKind = NodeKind> =
110
- NodeConfigsByKind[kind]
111
-
112
- type UnknownNodeConfig = {
113
- description?: DescriptionWriter
114
- expected?: ExpectedWriter
115
- actual?: ActualWriter
116
- problem?: ProblemWriter
117
- message?: MessageWriter
118
- }
119
-
120
- export type ParsedUnknownNodeConfig = requireKeys<
121
- UnknownNodeConfig,
122
- "description"
123
- >
124
-
125
- export type StaticArkOption<k extends keyof StaticArkConfig> = ReturnType<
126
- StaticArkConfig[k]
127
- >
128
-
129
- export interface ArkConfig extends Partial<Readonly<NodeConfigsByKind>> {
130
- readonly ambient?: Scope | null
131
- /** @internal */
132
- readonly prereducedAliases?: boolean
133
- /** @internal */
134
- readonly registerKeywords?: boolean
135
- }
136
-
137
- type resolveConfig<config extends ArkConfig> = {
138
- [k in keyof config]-?: k extends NodeKind ? Required<config[k]> : config[k]
139
- }
140
-
141
- export type ResolvedArkConfig = resolveConfig<ArkConfig>
142
-
143
- export const defaultConfig: ResolvedArkConfig = Object.assign(
144
- morph(nodesByKind, (kind, node) => [kind, node.implementation.defaults]),
145
- {
146
- prereducedAliases: false,
147
- ambient: null,
148
- registerKeywords: false
149
- } satisfies Omit<ResolvedArkConfig, NodeKind>
150
- ) as never
151
-
152
- const nonInheritedKeys = [
153
- "registerKeywords",
154
- "prereducedAliases"
155
- ] as const satisfies array<keyof ArkConfig>
156
-
157
- const extendConfig = (
158
- base: ArkConfig,
159
- extension: ArkConfig | undefined
160
- ): ArkConfig => {
161
- if (!extension) return base
162
- const result = mergeConfigs(base, extension)
163
- nonInheritedKeys.forEach((k) => {
164
- if (!(k in extension)) delete result[k]
165
- })
166
- return result
167
- }
168
-
169
- const resolveConfig = (scopeConfig: ArkConfig | undefined): ResolvedArkConfig =>
170
- extendConfig(defaultConfig, scopeConfig) as never
171
-
172
- export type ScopeParser<parent, ambient> = {
173
- <const def>(
174
- def: validateScope<def, parent & ambient>,
175
- config?: ArkConfig
176
- ): Scope<{
177
- exports: inferBootstrapped<{
178
- exports: bootstrapExports<def>
179
- locals: bootstrapLocals<def> & parent
180
- ambient: ambient
181
- }>
182
- locals: inferBootstrapped<{
183
- exports: bootstrapLocals<def>
184
- locals: bootstrapExports<def> & parent
185
- ambient: ambient
186
- }>
187
- ambient: ambient
188
- }>
189
- }
190
-
191
- type validateScope<def, $> = {
192
- [k in keyof def]: parseScopeKey<k>["params"] extends []
193
- ? // Not including Type here directly breaks inference
194
- def[k] extends Type | PreparsedResolution
195
- ? def[k]
196
- : validateDefinition<def[k], $ & bootstrap<def>, {}>
197
- : parseScopeKey<k>["params"] extends GenericParamsParseError
198
- ? // use the full nominal type here to avoid an overlap between the
199
- // error message and a possible value for the property
200
- parseScopeKey<k>["params"][0]
201
- : validateDefinition<
202
- def[k],
203
- $ & bootstrap<def>,
204
- {
205
- // once we support constraints on generic parameters, we'd use
206
- // the base type here: https://github.com/arktypeio/arktype/issues/796
207
- [param in parseScopeKey<k>["params"][number]]: unknown
208
- }
209
- >
50
+ export type ScopeParser = <const def>(
51
+ def: validateScope<def>,
52
+ config?: ArkConfig
53
+ ) => Scope<inferBootstrapped<bootstrapAliases<def>>>
54
+
55
+ type validateScope<def> = {
56
+ [k in keyof def]: k extends symbol ?
57
+ // this should only occur when importing/exporting modules, and those keys should be ignored
58
+ unknown
59
+ : parseScopeKey<k>["params"] extends [] ?
60
+ // Not including Type here directly breaks inference
61
+ def[k] extends Type | PreparsedResolution ?
62
+ def[k]
63
+ : validateDefinition<def[k], ambient & bootstrapAliases<def>, {}>
64
+ : parseScopeKey<k>["params"] extends GenericParamsParseError ?
65
+ // use the full nominal type here to avoid an overlap between the
66
+ // error message and a possible value for the property
67
+ parseScopeKey<k>["params"][0]
68
+ : validateDefinition<
69
+ def[k],
70
+ ambient & bootstrapAliases<def>,
71
+ {
72
+ // once we support constraints on generic parameters, we'd use
73
+ // the base type here: https://github.com/arktypeio/arktype/issues/796
74
+ [param in parseScopeKey<k>["params"][number]]: unknown
75
+ }
76
+ >
210
77
  }
211
78
 
212
79
  export type bindThis<def> = { this: Def<def> }
@@ -217,250 +84,165 @@ type Def<def = {}> = nominal<def, "unparsed">
217
84
  /** sentinel indicating a scope that will be associated with a generic has not yet been parsed */
218
85
  export type UnparsedScope = "$"
219
86
 
220
- type bootstrap<def> = bootstrapLocals<def> & bootstrapExports<def>
221
-
222
- type bootstrapLocals<def> = bootstrapAliases<{
223
- // intersection seems redundant but it is more efficient for TS to avoid
224
- // mapping all the keys
225
- [k in keyof def & PrivateDeclaration as extractPrivateKey<k>]: def[k]
226
- }>
227
-
228
- type bootstrapExports<def> = bootstrapAliases<{
229
- [k in Exclude<keyof def, PrivateDeclaration>]: def[k]
230
- }>
231
-
232
87
  /** These are legal as values of a scope but not as definitions in other contexts */
233
- type PreparsedResolution = Module | GenericProps
88
+ type PreparsedResolution = PreparsedNodeResolution
234
89
 
235
90
  type bootstrapAliases<def> = {
236
91
  [k in Exclude<
237
92
  keyof def,
238
93
  // avoid inferring nominal symbols, e.g. arkKind from Module
239
94
  GenericDeclaration | symbol
240
- >]: def[k] extends PreparsedResolution
241
- ? def[k]
242
- : def[k] extends (() => infer thunkReturn extends PreparsedResolution)
243
- ? thunkReturn
244
- : Def<def[k]>
95
+ >]: def[k] extends PreparsedResolution ? def[k]
96
+ : def[k] extends (() => infer thunkReturn extends PreparsedResolution) ?
97
+ thunkReturn
98
+ : Def<def[k]>
245
99
  } & {
246
- [k in keyof def & GenericDeclaration as extractGenericName<k>]: Generic<
100
+ [k in keyof def & GenericDeclaration as extractGenericName<k>]: GenericProps<
247
101
  parseGenericParams<extractGenericParameters<k>>,
248
102
  def[k],
249
103
  UnparsedScope
250
104
  >
251
105
  }
252
106
 
253
- type inferBootstrapped<r extends Resolutions> = evaluate<{
254
- [name in keyof r["exports"]]: r["exports"][name] extends Def<infer def>
255
- ? inferDefinition<def, $<r>, {}>
256
- : r["exports"][name] extends GenericProps<infer params, infer def>
257
- ? // add the scope in which the generic was defined here
258
- Generic<params, def, $<r>>
259
- : // otherwise should be a submodule
260
- r["exports"][name]
107
+ type inferBootstrapped<$> = show<{
108
+ [name in keyof $]: $[name] extends Def<infer def> ?
109
+ inferDefinition<def, $ & ambient, {}>
110
+ : $[name] extends GenericProps<infer params, infer def> ?
111
+ // add the scope in which the generic was defined here
112
+ Generic<params, def, $>
113
+ : // otherwise should be a submodule
114
+ $[name]
261
115
  }>
262
116
 
263
- type extractGenericName<k> = k extends GenericDeclaration<infer name>
264
- ? name
265
- : never
266
-
267
- type extractGenericParameters<k> = k extends GenericDeclaration<
268
- string,
269
- infer params
270
- >
271
- ? params
272
- : never
273
-
274
- type extractPrivateKey<k> = k extends PrivateDeclaration<infer key>
275
- ? key
276
- : never
277
-
278
- type PrivateDeclaration<key extends string = string> = `#${key}`
279
-
280
- export type resolve<reference extends keyof $ | keyof args, $, args> = (
281
- reference extends keyof args ? args[reference] : $[reference & keyof $]
282
- ) extends infer resolution
283
- ? [resolution] extends [never]
284
- ? never
285
- : isAny<resolution> extends true
286
- ? any
287
- : resolution extends Def<infer def>
288
- ? inferDefinition<def, $, args>
289
- : resolution
290
- : never
117
+ type extractGenericName<k> =
118
+ k extends GenericDeclaration<infer name> ? name : never
119
+
120
+ type extractGenericParameters<k> =
121
+ k extends GenericDeclaration<string, infer params> ? params : never
122
+
123
+ export type resolve<reference extends keyof $ | keyof args, $, args> =
124
+ (
125
+ reference extends keyof args ?
126
+ args[reference]
127
+ : $[reference & keyof $]
128
+ ) extends infer resolution ?
129
+ resolution extends Def<infer def> ?
130
+ def extends null ?
131
+ // handle resolution of any and never
132
+ resolution
133
+ : inferDefinition<def, $, args>
134
+ : resolution
135
+ : never
291
136
 
292
137
  export type moduleKeyOf<$> = {
293
- [k in keyof $]: $[k] extends Module ? k & string : never
138
+ // TODO: check against module directly?
139
+ [k in keyof $]: $[k] extends { [arkKind]: "module" } ? k & string : never
294
140
  }[keyof $]
295
141
 
296
142
  export type tryInferSubmoduleReference<$, token> =
297
- token extends `${infer submodule extends moduleKeyOf<$>}.${infer subalias}`
298
- ? subalias extends keyof $[submodule]
299
- ? $[submodule][subalias] extends Type<infer t>
300
- ? t
301
- : never
302
- : never
303
- : never
304
-
305
- type $<r extends Resolutions> = r["exports"] & r["locals"] & r["ambient"]
306
-
307
- type exportedName<r extends Resolutions> = keyof r["exports"] & string
308
-
309
- export type Module<r extends Resolutions = any> = {
310
- // just adding the nominal id this way and mapping it is cheaper than an intersection
311
- [k in exportedName<r> | arkKind]: k extends string
312
- ? [r["exports"][k]] extends [never]
313
- ? Type<never, $<r>>
314
- : isAny<r["exports"][k]> extends true
315
- ? Type<any, $<r>>
316
- : r["exports"][k] extends PreparsedResolution
317
- ? r["exports"][k]
318
- : Type<r["exports"][k], $<r>>
319
- : // set the nominal symbol's value to something validation won't care about
320
- // since the inferred type will be omitted anyways
321
- type.cast<"module">
143
+ token extends `${infer submodule extends moduleKeyOf<$>}.${infer subalias}` ?
144
+ subalias extends keyof $[submodule] ?
145
+ $[submodule][subalias] extends type.cast<infer t> ?
146
+ t
147
+ : never
148
+ : never
149
+ : never
150
+
151
+ export interface ParseContext extends NodeParseOptions {
152
+ $: RawScope
322
153
  }
323
154
 
324
- export type Resolutions = {
325
- exports: unknown
326
- locals: unknown
327
- ambient: unknown
328
- }
329
-
330
- export type rootResolutions<exports> = {
331
- exports: exports
332
- locals: {}
333
- ambient: {}
334
- }
335
-
336
- export type ParseContext = {
337
- baseName: string
338
- path: string[]
339
- $: Scope
340
- args: Record<string, Type> | undefined
341
- }
342
-
343
- type MergedResolutions = Record<string, Type | Generic>
344
-
345
- type ParseContextInput = Partial<ParseContext>
155
+ export const scope: ScopeParser = ((def: Dict, config: ArkConfig = {}) =>
156
+ new RawScope(def, config)) as never
346
157
 
347
- export type PrimitiveKeywords = typeof tsPrimitiveKeywords &
348
- typeof jsObjectKeywords &
349
- typeof internalPrimitiveKeywords
158
+ export interface Scope<$ = any> extends SchemaScope<$> {
159
+ type: TypeParser<$>
350
160
 
351
- export class Scope<r extends Resolutions = any> {
352
- declare infer: distillConstrainableOut<r["exports"]>
353
- declare inferIn: distillConstrainableIn<r["exports"]>
161
+ match: MatchParser<$>
354
162
 
355
- readonly config: ArkConfig
356
- readonly resolvedConfig: ResolvedArkConfig
163
+ declare: DeclarationParser<$>
357
164
 
358
- private parseCache: Record<string, Type> = {}
359
- private resolutions: MergedResolutions
360
- readonly nodeCache: { [innerId: string]: UnknownNode } = {}
361
- readonly referencesByName: { [name: string]: UnknownNode } = {}
362
- references: readonly UnknownNode[] = []
363
- json: Json = {}
364
- protected resolved = false
165
+ define: DefinitionParser<$>
365
166
 
366
- // these allow builtin types to be accessed during parsing without cyclic imports
367
- // they are populated as each scope is parsed with `registerKeywords` in its config
368
- /** @internal */
369
- static keywords = {} as PrimitiveKeywords
167
+ import<names extends exportedNameOf<$>[]>(
168
+ ...names: names
169
+ ): Module<show<destructuredImportContext<$, names>>>
370
170
 
371
- /** @internal */
372
- get keywords(): PrimitiveKeywords {
373
- return Scope.keywords
374
- }
171
+ export<names extends exportedNameOf<$>[]>(
172
+ ...names: names
173
+ ): Module<show<destructuredExportContext<$, names>>>
174
+ }
375
175
 
376
- /** The set of names defined at the root-level of the scope mapped to their
377
- * corresponding definitions.**/
378
- aliases: Record<string, unknown> = {}
379
- private exportedNames: exportedName<r>[] = []
176
+ export class RawScope<
177
+ $ extends RawSchemaResolutions = RawSchemaResolutions
178
+ > extends RawSchemaScope<$> {
179
+ private parseCache: Record<string, RawSchema> = {}
380
180
 
381
- constructor(def: Dict, config?: ArkConfig) {
382
- this.config = extendConfig(globalConfig, config)
383
- this.resolvedConfig = resolveConfig(this.config)
181
+ constructor(def: Record<string, unknown>, config?: ArkConfig) {
182
+ const aliases: Record<string, unknown> = {}
384
183
  for (const k in def) {
385
184
  const parsedKey = parseScopeKey(k)
386
- this.aliases[parsedKey.name] = parsedKey.params.length
387
- ? generic(parsedKey.params, def[k], this)
388
- : def[k]
389
- if (!parsedKey.isLocal) {
390
- this.exportedNames.push(parsedKey.name as never)
391
- }
185
+ aliases[parsedKey.name] =
186
+ parsedKey.params.length ?
187
+ // TODO: this
188
+ new Generic(parsedKey.params, def[k], {} as never)
189
+ : def[k]
392
190
  }
393
- if (this.config.ambient) {
394
- // ensure exportedResolutions is populated
395
- this.config.ambient.export()
396
- this.resolutions = { ...this.config.ambient.exportedResolutions! }
397
- } else {
398
- this.resolutions = {}
191
+ super(aliases, config)
192
+ }
193
+
194
+ type(...args: unknown[]): RawSchema | Generic {
195
+ if (args.length === 1) {
196
+ // treat as a simple definition
197
+ return this.parseRoot(args[0])
399
198
  }
400
- this.node(
401
- "union",
402
- {
403
- branches: [
404
- "string",
405
- "number",
406
- "object",
407
- "bigint",
408
- "symbol",
409
- { unit: true },
410
- { unit: false },
411
- { unit: null },
412
- { unit: undefined }
413
- ]
414
- },
415
- { reduceTo: this.node("intersection", {}, { prereduced: true }) }
416
- )
199
+ if (
200
+ args.length === 2 &&
201
+ typeof args[0] === "string" &&
202
+ args[0][0] === "<" &&
203
+ args[0].at(-1) === ">"
204
+ ) {
205
+ // if there are exactly two args, the first of which looks like <${string}>,
206
+ // treat as a generic
207
+ const params = parseGenericParams(args[0].slice(1, -1))
208
+ const def = args[1]
209
+ // TODO: validateUninstantiatedGeneric, remove this cast
210
+ return new Generic(params, def, this as never) as never
211
+ }
212
+ // otherwise, treat as a tuple expression. technically, this also allows
213
+ // non-expression tuple definitions to be parsed, but it's not a supported
214
+ // part of the API as specified by the associated types
215
+ return this.parseRoot(args)
417
216
  }
418
217
 
419
- type: TypeParser<$<r>> = createTypeParser(this as never) as never
218
+ match: MatchParser<$> = createMatchParser(this as never) as never
420
219
 
421
- schema: SchemaParser<$<r>> = this.rawSchema.bind(this) as never
422
- protected rawSchema(schema: unknown): ["schema", unknown] {
423
- return ["schema", schema] as const
220
+ declare(): { type: RawScope["type"] } {
221
+ return { type: this.type.bind(this) }
424
222
  }
425
223
 
426
- match: MatchParser<$<r>> = createMatchParser(this as never) as never
427
-
428
- declare: DeclarationParser<$<r>> = () => ({ type: this.type }) as never
429
-
430
- scope: ScopeParser<r["exports"], r["ambient"]> = ((
431
- def: Dict,
432
- config: ArkConfig = {}
433
- ) =>
434
- new Scope(
435
- { ...this.import(), ...def },
436
- extendConfig(this.config, config)
437
- )) as never
438
-
439
- define: DefinitionParser<$<r>> = (def) => def as never
440
-
441
- toAmbient(): Scope<{
442
- exports: r["exports"]
443
- locals: r["locals"]
444
- ambient: r["exports"]
445
- }> {
446
- ;(this as any).config = {
447
- ...this.config,
448
- ambient: this
449
- } satisfies ArkConfig
450
- return this as never
224
+ define(def: unknown): unknown {
225
+ return def
451
226
  }
452
227
 
453
- // TODO: name?
454
- get<name extends keyof r["exports"] & string>(
455
- name: name
456
- ): Type<r["exports"][name], $<r>> {
457
- return this.export()[name] as never
228
+ override preparseRoot(def: unknown): unknown {
229
+ if (isThunk(def) && !hasArkKind(def, "generic")) {
230
+ return def()
231
+ }
232
+ return def
233
+ }
234
+
235
+ override parseRoot(def: unknown, opts?: NodeParseOptions): RawSchema {
236
+ return this.parse(def, {
237
+ args: { this: {} as RawSchema },
238
+ $: this as never,
239
+ ...opts
240
+ }).bindScope(this)
458
241
  }
459
242
 
460
- parse(def: unknown, ctx: ParseContext): Type {
243
+ parse(def: unknown, ctx: ParseContext): RawSchema {
461
244
  if (typeof def === "string") {
462
- if (ctx.args !== undefined) {
463
- // TODO: allow caching with this by serializing it?
245
+ if (ctx.args && Object.keys(ctx.args).every((k) => !def.includes(k))) {
464
246
  // we can only rely on the cache if there are no contextual
465
247
  // resolutions like "this" or generic args
466
248
  return this.parseString(def, ctx)
@@ -470,24 +252,12 @@ export class Scope<r extends Resolutions = any> {
470
252
  }
471
253
  return this.parseCache[def]
472
254
  }
473
- return hasDomain(def, "object")
474
- ? parseObject(def, ctx)
475
- : throwParseError(writeBadDefinitionTypeMessage(domainOf(def)))
476
- }
477
-
478
- parseTypeRoot(def: unknown, input?: ParseContextInput): Type {
479
- const result = this.parse(def, {
480
- args: { this: {} as Type },
481
- baseName: "type",
482
- path: [],
483
- $: this,
484
- ...input
485
- }).bindScope(this)
486
- this.bindCompiledScope(result.contributesReferences)
487
- return result
255
+ return hasDomain(def, "object") ?
256
+ parseObject(def, ctx)
257
+ : throwParseError(writeBadDefinitionTypeMessage(domainOf(def)))
488
258
  }
489
259
 
490
- parseString(def: string, ctx: ParseContext): Type {
260
+ parseString(def: string, ctx: ParseContext): RawSchema {
491
261
  return (
492
262
  this.maybeResolveNode(def) ??
493
263
  ((def.endsWith("[]") &&
@@ -495,270 +265,6 @@ export class Scope<r extends Resolutions = any> {
495
265
  fullStringParse(new DynamicState(def, ctx)))
496
266
  )
497
267
  }
498
-
499
- maybeResolve(name: string): Type | Generic | undefined {
500
- const cached = this.resolutions[name]
501
- if (cached) {
502
- return cached
503
- }
504
- let def = this.aliases[name]
505
- if (!def) return this.maybeResolveSubalias(name)
506
- if (isThunk(def) && !hasArkKind(def, "generic")) {
507
- def = def()
508
- }
509
- // TODO: initialize here?
510
- const resolution = hasArkKind(def, "generic")
511
- ? validateUninstantiatedGeneric(def)
512
- : hasArkKind(def, "module")
513
- ? throwParseError(writeMissingSubmoduleAccessMessage(name))
514
- : this.parseTypeRoot(def, { baseName: name, args: {} })
515
- this.resolutions[name] = resolution
516
- return resolution
517
- }
518
-
519
- /** If name is a valid reference to a submodule alias, return its resolution */
520
- private maybeResolveSubalias(name: string) {
521
- const dotIndex = name.indexOf(".")
522
- if (dotIndex === -1) {
523
- return
524
- }
525
- const dotPrefix = name.slice(0, dotIndex)
526
- const prefixDef = this.aliases[dotPrefix]
527
- if (hasArkKind(prefixDef, "module")) {
528
- const resolution = prefixDef[name.slice(dotIndex + 1)]
529
- // if the first part of name is a submodule but the suffix is
530
- // unresolvable, we can throw immediately
531
- if (!resolution) {
532
- return throwParseError(writeUnresolvableMessage(name))
533
- }
534
- this.resolutions[name] = resolution
535
- return resolution
536
- }
537
- if (prefixDef !== undefined) {
538
- return throwParseError(writeNonSubmoduleDotMessage(dotPrefix))
539
- }
540
- // if the name includes ".", but the prefix is not an alias, it
541
- // might be something like a decimal literal, so just fall through to return
542
- }
543
-
544
- maybeResolveNode(name: string): Type | undefined {
545
- const result = this.maybeResolve(name)
546
- return result instanceof BaseType ? (result as never) : undefined
547
- }
548
-
549
- import<names extends exportedName<r>[]>(
550
- ...names: names
551
- ): destructuredImportContext<
552
- r,
553
- names extends [] ? keyof r["exports"] & string : names[number]
554
- > {
555
- return addArkKind(
556
- morph(this.export(...names) as Dict, (alias, value) => [
557
- `#${alias}`,
558
- value
559
- ]) as never,
560
- "module"
561
- ) as never
562
- }
563
-
564
- private exportedResolutions: MergedResolutions | undefined
565
- private exportCache: ExportCache | undefined
566
- export<names extends exportedName<r>[]>(
567
- ...names: names
568
- ): Module<
569
- names extends [] ? r : destructuredExportContext<r, names[number]>
570
- > {
571
- if (!this.exportCache) {
572
- this.exportCache = {}
573
- for (const name of this.exportedNames) {
574
- let def = this.aliases[name]
575
- if (hasArkKind(def, "generic")) {
576
- this.exportCache[name] = def
577
- continue
578
- }
579
- // TODO: thunk generics?
580
- // handle generics before invoking thunks, since they use
581
- // varargs they will incorrectly be considered thunks
582
- if (isThunk(def)) {
583
- def = def()
584
- }
585
- if (hasArkKind(def, "module")) {
586
- this.exportCache[name] = def
587
- } else {
588
- this.exportCache[name] = this.parseTypeRoot(def, {
589
- baseName: name,
590
- args: {}
591
- })
592
- }
593
- }
594
- this.exportedResolutions = resolutionsOfModule(this.exportCache)
595
- // TODO: add generic json
596
- this.json = morph(this.exportedResolutions, (k, v) =>
597
- hasArkKind(v, "node") ? [k, v.json] : []
598
- )
599
- Object.assign(this.resolutions, this.exportedResolutions)
600
- if (this.config.registerKeywords)
601
- Object.assign(Scope.keywords, this.exportedResolutions)
602
- this.references = Object.values(this.referencesByName)
603
- this.bindCompiledScope(this.references)
604
- this.resolved = true
605
- }
606
- const namesToExport = names.length ? names : this.exportedNames
607
- return addArkKind(
608
- morph(namesToExport, (_, name) => [
609
- name,
610
- this.exportCache![name]
611
- ]) as never,
612
- "module"
613
- ) as never
614
- }
615
-
616
- parseUnits<const branches extends array>(
617
- ...values: branches
618
- ): branches["length"] extends 1
619
- ? UnionNode<branches[0]>
620
- : UnionNode<branches[number]> | UnitNode<branches[number]> {
621
- const uniqueValues: unknown[] = []
622
- for (const value of values) {
623
- if (!uniqueValues.includes(value)) {
624
- uniqueValues.push(value)
625
- }
626
- }
627
- const branches = uniqueValues.map((unit) => this.node("unit", { unit }))
628
- return branches.length === 1
629
- ? (branches[0] as any)
630
- : this.node(branches, { root: true, prereduced: true })
631
- }
632
-
633
- node: NodeParser<$<r>> = this.internalNodeParser.bind(this)
634
- protected internalNodeParser(
635
- schemaOrKind: unknown,
636
- schemaOrOpts?: unknown,
637
- constraintOpts?: SchemaParseOptions
638
- ): UnknownNode {
639
- const kindArg = isNodeKind(schemaOrKind) ? schemaOrKind : undefined
640
-
641
- let schema = kindArg ? schemaOrOpts : schemaOrKind
642
- const opts: SchemaParseOptions | undefined = kindArg
643
- ? constraintOpts
644
- : (schemaOrOpts as never)
645
- if (opts?.alias && opts.alias in this.resolutions) {
646
- return throwInternalError(
647
- `Unexpected attempt to recreate existing alias ${opts.alias}`
648
- )
649
- }
650
- let kind = kindArg ?? typeKindOfSchema(schema)
651
- if (kind === "union" && isArray(schema) && schema.length === 1) {
652
- schema = schema[0]
653
- kind = typeKindOfSchema(schema)
654
- }
655
- if (opts?.allowedKinds && !opts.allowedKinds.includes(kind)) {
656
- return throwParseError(
657
- `Schema of kind ${kind} should be one of ${opts.allowedKinds}`
658
- )
659
- }
660
- const node = parseAttachments(kind, schema as never, {
661
- $: this,
662
- prereduced: opts?.prereduced ?? false,
663
- raw: schema,
664
- ...opts
665
- })
666
- if (opts?.root) {
667
- if (this.resolved) {
668
- // this node was not part of the original scope, so compile an anonymous scope
669
- // including only its references
670
- this.bindCompiledScope(node.contributesReferences)
671
- } else {
672
- // we're still parsing the scope itself, so defer compilation but
673
- // add the node as a reference
674
- Object.assign(this.referencesByName, node.contributesReferencesByName)
675
- }
676
- }
677
- return node as never
678
- }
679
-
680
- protected bindCompiledScope(references: readonly UnknownNode[]): void {
681
- const compiledTraversals = this.compileScope(references)
682
- for (const node of references) {
683
- if (node.jit) {
684
- // if node has already been bound to another scope or anonymous type, don't rebind it
685
- continue
686
- }
687
- node.jit = true
688
- node.traverseAllows =
689
- compiledTraversals[`${node.reference}Allows`].bind(compiledTraversals)
690
- if (node.isType() && !node.includesContextDependentPredicate) {
691
- // if the reference doesn't require context, we can assign over
692
- // it directly to avoid having to initialize it
693
- node.allows = node.traverseAllows as never
694
- }
695
- node.traverseApply =
696
- compiledTraversals[`${node.reference}Apply`].bind(compiledTraversals)
697
- }
698
- }
699
-
700
- protected compileScope(references: readonly UnknownNode[]): {
701
- [k: `${string}Allows`]: TraverseAllows
702
- [k: `${string}Apply`]: TraverseApply
703
- } {
704
- return new CompiledFunction()
705
- .block(`return`, (js) => {
706
- references.forEach((node) => {
707
- const allowsCompiler = new NodeCompiler("Allows").indent()
708
- node.compile(allowsCompiler)
709
- const applyCompiler = new NodeCompiler("Apply").indent()
710
- node.compile(applyCompiler)
711
- js.line(
712
- allowsCompiler.writeMethod(`${node.reference}Allows`) +
713
- ",\n" +
714
- applyCompiler.writeMethod(`${node.reference}Apply`) +
715
- ","
716
- )
717
- })
718
- return js
719
- })
720
- .compile()() as never
721
- }
722
- }
723
-
724
- type ExportCache = Record<string, Type | Generic | Module>
725
-
726
- const resolutionsOfModule = (typeSet: ExportCache) => {
727
- const result: MergedResolutions = {}
728
- for (const k in typeSet) {
729
- const v = typeSet[k]
730
- if (hasArkKind(v, "module")) {
731
- const innerResolutions = resolutionsOfModule(v as never)
732
- const prefixedResolutions = morph(innerResolutions, (innerK, innerV) => [
733
- `${k}.${innerK}`,
734
- innerV
735
- ])
736
- Object.assign(result, prefixedResolutions)
737
- } else if (hasArkKind(v, "generic")) {
738
- result[k] = v
739
- } else {
740
- result[k] = v as Type
741
- }
742
- }
743
- return result
744
- }
745
-
746
- type destructuredExportContext<
747
- r extends Resolutions,
748
- name extends exportedName<r>
749
- > = {
750
- exports: { [k in name]: r["exports"][k] }
751
- locals: r["locals"] & {
752
- [k in Exclude<keyof r["exports"], name>]: r["exports"][k]
753
- }
754
- ambient: r["ambient"]
755
- }
756
-
757
- type destructuredImportContext<
758
- r extends Resolutions,
759
- name extends exportedName<r>
760
- > = {
761
- [k in name as `#${k & string}`]: type.cast<r["exports"][k]>
762
268
  }
763
269
 
764
270
  export const writeShallowCycleErrorMessage = (
@@ -767,26 +273,16 @@ export const writeShallowCycleErrorMessage = (
767
273
  ): string =>
768
274
  `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join(":")}`
769
275
 
770
- export const writeDuplicateNameMessage = <name extends string>(
771
- name: name
772
- ): writeDuplicateNameMessage<name> => `Duplicate name '${name}'`
773
-
774
- type writeDuplicateNameMessage<name extends string> = `Duplicate name '${name}'`
775
-
776
276
  export type ParsedScopeKey = {
777
- isLocal: boolean
778
277
  name: string
779
278
  params: string[]
780
279
  }
781
280
 
782
281
  export const parseScopeKey = (k: string): ParsedScopeKey => {
783
- const isLocal = k[0] === "#"
784
- const name = isLocal ? k.slice(1) : k
785
282
  const firstParamIndex = k.indexOf("<")
786
283
  if (firstParamIndex === -1) {
787
284
  return {
788
- isLocal,
789
- name,
285
+ name: k,
790
286
  params: []
791
287
  }
792
288
  }
@@ -796,33 +292,18 @@ export const parseScopeKey = (k: string): ParsedScopeKey => {
796
292
  )
797
293
  }
798
294
  return {
799
- isLocal,
800
- name: name.slice(0, firstParamIndex),
295
+ name: k.slice(0, firstParamIndex),
801
296
  params: parseGenericParams(k.slice(firstParamIndex + 1, -1))
802
297
  }
803
298
  }
804
299
 
805
- type parseScopeKey<k> = k extends PrivateDeclaration<infer inner>
806
- ? parsePossibleGenericDeclaration<inner, true>
807
- : parsePossibleGenericDeclaration<k, false>
808
-
809
- type parsePossibleGenericDeclaration<
810
- k,
811
- isLocal extends boolean
812
- > = k extends GenericDeclaration<infer name, infer paramString>
813
- ? {
814
- isLocal: isLocal
300
+ export type parseScopeKey<k> =
301
+ k extends GenericDeclaration<infer name, infer paramString> ?
302
+ {
815
303
  name: name
816
304
  params: parseGenericParams<paramString>
817
- }
818
- : {
819
- isLocal: isLocal
305
+ }
306
+ : {
820
307
  name: k
821
308
  params: []
822
- }
823
-
824
- export interface TypeSchemaParseOptions<allowedKind extends TypeKind = TypeKind>
825
- extends SchemaParseOptions {
826
- root?: boolean
827
- allowedKinds?: readonly allowedKind[]
828
- }
309
+ }