arktype 3.0.0-beta.1 → 3.0.0-rc.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 (312) hide show
  1. package/README.md +48 -144
  2. package/out/_internal/regex/charset.d.ts +24 -0
  3. package/out/_internal/regex/escape.d.ts +29 -0
  4. package/out/_internal/regex/execArray.d.ts +24 -0
  5. package/out/_internal/regex/group.d.ts +34 -0
  6. package/out/_internal/regex/index.d.ts +2 -0
  7. package/out/_internal/regex/internal.d.ts +9 -0
  8. package/out/_internal/regex/parse.d.ts +10 -0
  9. package/out/_internal/regex/quantify.d.ts +59 -0
  10. package/out/_internal/regex/regex.d.ts +38 -0
  11. package/out/_internal/regex/state.d.ts +383 -0
  12. package/out/_internal/schema/codecs.d.ts +2 -0
  13. package/out/_internal/schema/config.d.ts +103 -0
  14. package/out/_internal/schema/constraint.d.ts +78 -0
  15. package/out/_internal/schema/errors.d.ts +1 -0
  16. package/out/_internal/schema/generic.d.ts +85 -0
  17. package/out/_internal/schema/i18n.d.ts +3 -0
  18. package/out/_internal/schema/index.d.ts +54 -0
  19. package/out/_internal/schema/internal.d.ts +15 -0
  20. package/out/_internal/schema/intrinsic.d.ts +28 -0
  21. package/out/_internal/schema/kinds.d.ts +76 -0
  22. package/out/_internal/schema/module.d.ts +23 -0
  23. package/out/_internal/schema/mutatesInput.d.ts +2 -0
  24. package/out/_internal/schema/node.d.ts +349 -0
  25. package/out/_internal/schema/parse.d.ts +77 -0
  26. package/out/_internal/schema/parseSchema.d.ts +116 -0
  27. package/out/_internal/schema/predicate.d.ts +46 -0
  28. package/out/_internal/schema/refinements/after.d.ts +32 -0
  29. package/out/_internal/schema/refinements/before.d.ts +32 -0
  30. package/out/_internal/schema/refinements/divisor.d.ts +41 -0
  31. package/out/_internal/schema/refinements/exactLength.d.ts +43 -0
  32. package/out/_internal/schema/refinements/kinds.d.ts +40 -0
  33. package/out/_internal/schema/refinements/max.d.ts +33 -0
  34. package/out/_internal/schema/refinements/maxLength.d.ts +32 -0
  35. package/out/_internal/schema/refinements/min.d.ts +33 -0
  36. package/out/_internal/schema/refinements/minLength.d.ts +32 -0
  37. package/out/_internal/schema/refinements/notEqual.d.ts +38 -0
  38. package/out/_internal/schema/refinements/notEqualLength.d.ts +38 -0
  39. package/out/_internal/schema/refinements/pattern.d.ts +43 -0
  40. package/out/_internal/schema/refinements/range.d.ts +101 -0
  41. package/out/_internal/schema/roots/alias.d.ts +49 -0
  42. package/out/_internal/schema/roots/basis.d.ts +12 -0
  43. package/out/_internal/schema/roots/domain.d.ts +45 -0
  44. package/out/_internal/schema/roots/intersection.d.ts +72 -0
  45. package/out/_internal/schema/roots/morph.d.ts +59 -0
  46. package/out/_internal/schema/roots/proto.d.ts +42 -0
  47. package/out/_internal/schema/roots/root.d.ts +163 -0
  48. package/out/_internal/schema/roots/union.d.ts +146 -0
  49. package/out/_internal/schema/roots/unit.d.ts +36 -0
  50. package/out/_internal/schema/runtime.d.ts +29 -0
  51. package/out/_internal/schema/runtimeLean.d.ts +2 -0
  52. package/out/_internal/schema/runtimeNone.d.ts +2 -0
  53. package/out/_internal/schema/runtimeNoneLean.d.ts +2 -0
  54. package/out/_internal/schema/scope.d.ts +203 -0
  55. package/out/_internal/schema/shared/codecs.d.ts +5 -0
  56. package/out/_internal/schema/shared/compile.d.ts +144 -0
  57. package/out/_internal/schema/shared/configured.d.ts +14 -0
  58. package/out/_internal/schema/shared/declare.d.ts +100 -0
  59. package/out/_internal/schema/shared/disjoint.d.ts +45 -0
  60. package/out/_internal/schema/shared/enWriters.d.ts +30 -0
  61. package/out/_internal/schema/shared/errorModes.d.ts +25 -0
  62. package/out/_internal/schema/shared/errorWriters.d.ts +34 -0
  63. package/out/_internal/schema/shared/errors.d.ts +264 -0
  64. package/out/_internal/schema/shared/implement.d.ts +154 -0
  65. package/out/_internal/schema/shared/inPlace.d.ts +8 -0
  66. package/out/_internal/schema/shared/issueFeatures.d.ts +38 -0
  67. package/out/_internal/schema/shared/issues.d.ts +261 -0
  68. package/out/_internal/schema/shared/issuesLean.d.ts +80 -0
  69. package/out/_internal/schema/shared/issuesNone.d.ts +22 -0
  70. package/out/_internal/schema/shared/issuesNoneLean.d.ts +20 -0
  71. package/out/_internal/schema/shared/issuesUndetailed.d.ts +25 -0
  72. package/out/_internal/schema/shared/jsonSchema.d.ts +153 -0
  73. package/out/_internal/schema/shared/listed.d.ts +15 -0
  74. package/out/_internal/schema/shared/locale.d.ts +149 -0
  75. package/out/_internal/schema/shared/registry.d.ts +16 -0
  76. package/out/_internal/schema/shared/render.d.ts +3 -0
  77. package/out/_internal/schema/shared/rootApply.d.ts +19 -0
  78. package/out/_internal/schema/shared/sets.d.ts +26 -0
  79. package/out/_internal/schema/shared/standardFailure.d.ts +22 -0
  80. package/out/_internal/schema/shared/standardSchema.d.ts +124 -0
  81. package/out/_internal/schema/shared/toJsonSchema.d.ts +229 -0
  82. package/out/_internal/schema/shared/transform.d.ts +35 -0
  83. package/out/_internal/schema/shared/traversal.d.ts +288 -0
  84. package/out/_internal/schema/shared/utils.d.ts +59 -0
  85. package/out/_internal/schema/structure/index.d.ts +43 -0
  86. package/out/_internal/schema/structure/optional.d.ts +61 -0
  87. package/out/_internal/schema/structure/prop.d.ts +45 -0
  88. package/out/_internal/schema/structure/required.d.ts +49 -0
  89. package/out/_internal/schema/structure/sequence.d.ts +127 -0
  90. package/out/_internal/schema/structure/shared.d.ts +3 -0
  91. package/out/_internal/schema/structure/structure.d.ts +178 -0
  92. package/out/_internal/schema/units.d.ts +123 -0
  93. package/out/_internal/sets/algebra.d.ts +26 -0
  94. package/out/_internal/sets/constraint.d.ts +19 -0
  95. package/out/_internal/sets/engine.d.ts +2 -0
  96. package/out/_internal/sets/formats.d.ts +23 -0
  97. package/out/_internal/sets/fromJsonSchema.d.ts +15 -0
  98. package/out/_internal/sets/implement.d.ts +16 -0
  99. package/out/_internal/sets/index.d.ts +2 -0
  100. package/out/_internal/sets/internal.d.ts +20 -0
  101. package/out/_internal/sets/intersections.d.ts +5 -0
  102. package/out/_internal/sets/kinds.d.ts +3 -0
  103. package/out/_internal/sets/refinements.d.ts +14 -0
  104. package/out/_internal/sets/roots/alias.d.ts +3 -0
  105. package/out/_internal/sets/roots/domain.d.ts +3 -0
  106. package/out/_internal/sets/roots/intersection.d.ts +4 -0
  107. package/out/_internal/sets/roots/morph.d.ts +4 -0
  108. package/out/_internal/sets/roots/proto.d.ts +3 -0
  109. package/out/_internal/sets/roots/union.d.ts +16 -0
  110. package/out/_internal/sets/roots/unit.d.ts +3 -0
  111. package/out/_internal/sets/structure/index.d.ts +3 -0
  112. package/out/_internal/sets/structure/prop.d.ts +8 -0
  113. package/out/_internal/sets/structure/sequence.d.ts +3 -0
  114. package/out/_internal/sets/structure/structure.d.ts +3 -0
  115. package/out/_internal/sets/toJsonSchema.d.ts +25 -0
  116. package/out/_internal/util/arrays.d.ts +130 -0
  117. package/out/_internal/util/clone.d.ts +4 -0
  118. package/out/_internal/util/describe.d.ts +25 -0
  119. package/out/_internal/util/domain.d.ts +49 -0
  120. package/out/_internal/util/errors.d.ts +29 -0
  121. package/out/_internal/util/facts.d.ts +22 -0
  122. package/out/_internal/util/flatMorph.d.ts +41 -0
  123. package/out/_internal/util/formats.d.ts +8 -0
  124. package/out/_internal/util/functions.d.ts +33 -0
  125. package/out/_internal/util/generics.d.ts +65 -0
  126. package/out/_internal/util/get.d.ts +9 -0
  127. package/out/_internal/util/hkt.d.ts +27 -0
  128. package/out/_internal/util/i18n.d.ts +12 -0
  129. package/out/_internal/util/index.d.ts +28 -0
  130. package/out/_internal/util/internal.d.ts +2 -0
  131. package/out/_internal/util/intersections.d.ts +50 -0
  132. package/out/_internal/util/isomorphic.d.ts +8 -0
  133. package/out/_internal/util/keys.d.ts +18 -0
  134. package/out/_internal/util/lazily.d.ts +7 -0
  135. package/out/_internal/util/numbers.d.ts +82 -0
  136. package/out/_internal/util/objectKinds.d.ts +157 -0
  137. package/out/_internal/util/path.d.ts +16 -0
  138. package/out/_internal/util/primitive.d.ts +16 -0
  139. package/out/_internal/util/records.d.ts +173 -0
  140. package/out/_internal/util/registry.d.ts +13 -0
  141. package/out/_internal/util/scanner.d.ts +110 -0
  142. package/out/_internal/util/serialize.d.ts +40 -0
  143. package/out/_internal/util/strings.d.ts +35 -0
  144. package/out/_internal/util/traits.d.ts +89 -0
  145. package/out/_internal/util/unionToTuple.d.ts +14 -0
  146. package/out/_internal/util/weak.d.ts +8 -0
  147. package/out/attributes.d.ts +15 -11
  148. package/out/checkers.d.ts +1 -1
  149. package/out/chunk-22RQSVV3.js +0 -0
  150. package/out/chunk-3HZC67MT.js +965 -0
  151. package/out/chunk-3KBOPH3J.js +1564 -0
  152. package/out/chunk-3SH2BQ4T.js +15 -0
  153. package/out/chunk-46PLKNON.js +126 -0
  154. package/out/{chunk-G45P2CLE.js → chunk-4FTHWK63.js} +6 -1
  155. package/out/{chunk-UK5UGFOX.js → chunk-4HREHNIV.js} +23 -11
  156. package/out/chunk-4NZCLVBD.js +14 -0
  157. package/out/chunk-6FMBO47M.js +7 -0
  158. package/out/chunk-7TALAWYX.js +10 -0
  159. package/out/{chunk-DLWCO4RV.js → chunk-BCYKO54Z.js} +11 -2
  160. package/out/chunk-BDJVONP7.js +168 -0
  161. package/out/{chunk-E3DZXEZK.js → chunk-C2JOL5M2.js} +4 -2
  162. package/out/{chunk-2U2AWCI3.js → chunk-C2V6QPE3.js} +126 -97
  163. package/out/chunk-C3B4IFQL.js +6408 -0
  164. package/out/chunk-CWSF57VM.js +10 -0
  165. package/out/chunk-F5BACUJS.js +7 -0
  166. package/out/{chunk-EVCML554.js → chunk-FWRSDUJ2.js} +14 -5
  167. package/out/chunk-GID3FSQA.js +161 -0
  168. package/out/chunk-I2KLQ2HA.js +22 -0
  169. package/out/chunk-K7SLP5D2.js +84 -0
  170. package/out/chunk-KQPSKGUI.js +9 -0
  171. package/out/chunk-KXOC3JEX.js +8234 -0
  172. package/out/chunk-KXOSUYRA.js +405 -0
  173. package/out/chunk-LHNEY6QW.js +0 -0
  174. package/out/chunk-MTWKGAGO.js +323 -0
  175. package/out/chunk-NU73GNCX.js +170 -0
  176. package/out/{chunk-RAZ3TXOE.js → chunk-P5W67FQH.js} +34 -19
  177. package/out/chunk-PDLTEX6Z.js +1118 -0
  178. package/out/{chunk-VV6YDN2D.js → chunk-QUS4IAXJ.js} +304 -263
  179. package/out/chunk-R7WXIH5P.js +94 -0
  180. package/out/chunk-TACLEIDM.js +95 -0
  181. package/out/chunk-UJJGG4VQ.js +71 -0
  182. package/out/chunk-US6BWOGJ.js +109 -0
  183. package/out/chunk-VMMMOO4R.js +945 -0
  184. package/out/chunk-VYMXHSFR.js +439 -0
  185. package/out/chunk-W2XOI5DY.js +141 -0
  186. package/out/chunk-WC5L5YRP.js +25 -0
  187. package/out/{chunk-NRIGTMPM.js → chunk-WKOSL2G6.js} +4 -1
  188. package/out/chunk-XLG66ZDF.js +0 -0
  189. package/out/{chunk-5U2ZMDNI.js → chunk-XNUAQSJ4.js} +52 -30
  190. package/out/chunk-ZRYEHGSG.js +79 -0
  191. package/out/cli.d.ts +28 -0
  192. package/out/cli.js +636 -0
  193. package/out/codecs.d.ts +6 -5
  194. package/out/codecs.js +23 -7
  195. package/out/config.d.ts +5 -17
  196. package/out/config.js +11 -2
  197. package/out/declare.d.ts +40 -12
  198. package/out/deferred.d.ts +2 -2
  199. package/out/errors.d.ts +1 -1
  200. package/out/errors.js +10 -2
  201. package/out/fn.d.ts +20 -13
  202. package/out/fromJsonSchema.d.ts +18 -0
  203. package/out/generic.d.ts +9 -6
  204. package/out/i18n.d.ts +2 -2
  205. package/out/i18n.js +9 -2
  206. package/out/index.d.ts +16 -7
  207. package/out/index.js +25 -8
  208. package/out/internal.d.ts +4 -0
  209. package/out/internal.js +41 -17
  210. package/out/island.js +22 -6
  211. package/out/islandDependency.js +42 -18
  212. package/out/jsonSchema/infer.d.ts +805 -0
  213. package/out/jsonSchema/validate.d.ts +416 -0
  214. package/out/keywords/Array.d.ts +2 -2
  215. package/out/keywords/builtins.d.ts +3 -3
  216. package/out/keywords/constructors.d.ts +1 -1
  217. package/out/keywords/functions.d.ts +5 -192
  218. package/out/keywords/keywords.d.ts +3 -3
  219. package/out/keywords/number.d.ts +2 -2
  220. package/out/keywords/phrases.d.ts +4 -191
  221. package/out/keywords/string.d.ts +3 -3
  222. package/out/keywords/ts.d.ts +18 -18
  223. package/out/keywords/ts.js +19 -4
  224. package/out/locale.d.ts +6 -2
  225. package/out/locales/de.js +9 -2
  226. package/out/locales/en.js +21 -5
  227. package/out/match.d.ts +13 -10
  228. package/out/module.d.ts +2 -2
  229. package/out/mutatesInput.js +18 -3
  230. package/out/nary.d.ts +220 -194
  231. package/out/parser/ast/bounds.d.ts +2 -2
  232. package/out/parser/ast/default.d.ts +2 -2
  233. package/out/parser/ast/divisor.d.ts +2 -2
  234. package/out/parser/ast/generic.d.ts +2 -2
  235. package/out/parser/ast/infer.d.ts +1 -1
  236. package/out/parser/ast/keyof.d.ts +2 -2
  237. package/out/parser/ast/utils.d.ts +1 -1
  238. package/out/parser/ast/validate.d.ts +2 -2
  239. package/out/parser/definition.d.ts +4 -4
  240. package/out/parser/objectLiteral.d.ts +2 -2
  241. package/out/parser/property.d.ts +2 -2
  242. package/out/parser/reduce/dynamic.d.ts +2 -2
  243. package/out/parser/reduce/shared.d.ts +1 -1
  244. package/out/parser/reduce/static.d.ts +1 -1
  245. package/out/parser/shift/operand/enclosed.d.ts +2 -2
  246. package/out/parser/shift/operand/genericArgs.d.ts +2 -2
  247. package/out/parser/shift/operand/operand.d.ts +1 -1
  248. package/out/parser/shift/operand/unenclosed.d.ts +2 -2
  249. package/out/parser/shift/operand/unresolvable.d.ts +2 -2
  250. package/out/parser/shift/operator/bounds.d.ts +2 -2
  251. package/out/parser/shift/operator/brand.d.ts +2 -2
  252. package/out/parser/shift/operator/default.d.ts +4 -4
  253. package/out/parser/shift/operator/divisor.d.ts +1 -1
  254. package/out/parser/shift/operator/operator.d.ts +1 -1
  255. package/out/parser/shift/tokens.d.ts +1 -1
  256. package/out/parser/string.d.ts +2 -2
  257. package/out/parser/tupleExpressions.d.ts +6 -8
  258. package/out/parser/tupleLiteral.d.ts +2 -2
  259. package/out/precompiled.d.ts +1 -1
  260. package/out/precompiled.js +16 -2
  261. package/out/regex.d.ts +1 -0
  262. package/out/regex.js +2 -0
  263. package/out/runtime.d.ts +10 -8
  264. package/out/runtime.js +6 -4
  265. package/out/runtimeDevelopment.js +70 -52
  266. package/out/schema.d.ts +1 -0
  267. package/out/schema.js +15 -0
  268. package/out/schemaInternal.d.ts +1 -0
  269. package/out/schemaInternal.js +1401 -0
  270. package/out/schemaIssueFeatures.d.ts +1 -0
  271. package/out/schemaRuntime.d.ts +1 -0
  272. package/out/schemaRuntime.js +7 -0
  273. package/out/schemaRuntimeLean.d.ts +1 -0
  274. package/out/schemaRuntimeLean.js +1870 -0
  275. package/out/schemaRuntimeNone.d.ts +1 -0
  276. package/out/schemaRuntimeNone.js +1774 -0
  277. package/out/schemaRuntimeNoneLean.d.ts +1 -0
  278. package/out/schemaRuntimeNoneLean.js +1767 -0
  279. package/out/scope.d.ts +3 -4
  280. package/out/shared/issueFeatures.d.ts +38 -0
  281. package/out/shared/issueFeatures.js +40 -0
  282. package/out/standalone/artifact.d.ts +6 -6
  283. package/out/standalone/baking.d.ts +2 -2
  284. package/out/standalone/combinators.d.ts +1 -1
  285. package/out/standalone/compilers.d.ts +1 -1
  286. package/out/standalone/fallbacks.d.ts +1 -1
  287. package/out/standalone/keys.d.ts +1 -1
  288. package/out/standalone/sites.d.ts +3 -3
  289. package/out/standalone/units.d.ts +1 -1
  290. package/out/standalone/values.d.ts +1 -1
  291. package/out/type.d.ts +6 -6
  292. package/out/util.d.ts +1 -0
  293. package/out/util.js +137 -0
  294. package/out/variants/array.d.ts +6 -6
  295. package/out/variants/base.d.ts +61 -10
  296. package/out/variants/date.d.ts +5 -5
  297. package/out/variants/instantiate.d.ts +1 -1
  298. package/out/variants/number.d.ts +6 -6
  299. package/out/variants/object.d.ts +25 -12
  300. package/out/variants/string.d.ts +8 -8
  301. package/package.json +183 -8
  302. package/skills/arktype/SKILL.md +93 -93
  303. package/skills/arktype/references/migrating.md +144 -158
  304. package/skills/arktype/references/precompile.md +7 -7
  305. package/out/chunk-4CUA5XIP.js +0 -7
  306. package/out/chunk-GPNK5353.js +0 -2529
  307. package/out/chunk-MLKGABMK.js +0 -9
  308. package/out/chunk-PRTMQCHS.js +0 -3
  309. package/out/chunk-R5G57XC7.js +0 -7
  310. package/out/chunk-SWOOCAHN.js +0 -4
  311. package/out/chunk-TAHPKDNM.js +0 -3
  312. package/out/chunk-UETB6YE2.js +0 -14
@@ -1,2529 +0,0 @@
1
- import {
2
- InternalFnParser
3
- } from "./chunk-G45P2CLE.js";
4
- import {
5
- emptyCollectionDefaults,
6
- stringifyJson
7
- } from "./chunk-UK5UGFOX.js";
8
-
9
- // out/keywords/ts.js
10
- import { genericNode, intrinsic as intrinsic4, isResolvable, node as node2 } from "@ark/schema";
11
- import { cached as cached2, Hkt as Hkt2, throwParseError as throwParseError13 } from "@ark/util";
12
-
13
- // out/scope.js
14
- import { $ark as $ark5, BaseScope, hasArkKind as hasArkKind4, LazyGenericRoot, parseGeneric, RootModule, isFinalResolution } from "@ark/schema";
15
- import { Scanner as Scanner2, defineLazily as defineLazily2, enumValues, flatMorph, hasOwn as hasOwn5, isArray as isArray5, isThunk as isThunk3, throwParseError as throwParseError12 } from "@ark/util";
16
- import { setEngine } from "arksets/internal";
17
-
18
- // out/generic.js
19
- import { GenericRoot } from "@ark/schema";
20
- import { throwParseError as throwParseError6 } from "@ark/util";
21
-
22
- // out/parser/reduce/dynamic.js
23
- import { isEmptyObject, isKeyOf as isKeyOf5, throwInternalError as throwInternalError2, throwParseError as throwParseError5, writeUnclosedGroupMessage as writeUnclosedGroupMessage2, writeUnmatchedGroupCloseMessage } from "@ark/util";
24
-
25
- // out/parser/shift/operand/operand.js
26
- import { whitespaceChars as whitespaceChars4 } from "@ark/util";
27
-
28
- // out/parser/shift/operand/enclosed.js
29
- import { execMorph, makeMorph, node } from "@ark/schema";
30
- import { Backslash, cached, isKeyOf, throwParseError, tryParseDate, writeInvalidDateMessage } from "@ark/util";
31
- var regexExecArray = cached(function () { return node("intersection", {
32
- proto: node("proto", { proto: Array }),
33
- structure: node("structure", {
34
- sequence: node("sequence", {
35
- variadic: node("domain", { domain: "string" })
36
- }),
37
- required: [
38
- node("required", {
39
- key: "groups",
40
- value: node("union", {
41
- branches: [
42
- node("domain", { domain: "object" }),
43
- node("unit", { unit: void 0 })
44
- ]
45
- })
46
- })
47
- ]
48
- })
49
- }) });
50
- var parseEnclosed = function (s, enclosing) {
51
- const enclosed = s.sc.shiftUntilEscapable(
52
- untilLookaheadIsClosing[enclosingTokens[enclosing]],
53
- // within a regex literal, `\\` is a literal backslash and must be
54
- // preserved verbatim in the pattern source; collapsing it to a single
55
- // backslash would corrupt the regex (e.g. `\\d` -> `\d` digit class)
56
- enclosing in enclosingRegexTokens ? Backslash : ""
57
- );
58
- if (s.sc.peek === "")
59
- return s.error(writeUnterminatedEnclosedMessage(enclosed, enclosing));
60
- s.sc.shift();
61
- if (enclosing in enclosingRegexTokens) {
62
- let regex;
63
- try {
64
- regex = new RegExp(enclosed);
65
- } catch (e) {
66
- throwParseError(String(e));
67
- }
68
- s.root = s.ctx.$.node("intersection", {
69
- domain: s.ctx.$.node("domain", { domain: "string" }),
70
- pattern: [s.ctx.$.node("pattern", { rule: enclosed })]
71
- }, { reduced: true });
72
- if (enclosing === "x/") {
73
- s.root = s.ctx.$.node("morph", {
74
- morphs: [s.root, makeMorph(execMorph, regex)],
75
- declaredOut: regexExecArray()
76
- });
77
- }
78
- } else if (isKeyOf(enclosing, enclosingQuote))
79
- s.root = s.ctx.$.node("unit", { unit: enclosed });
80
- else {
81
- const date = tryParseDate(enclosed, writeInvalidDateMessage(enclosed));
82
- s.root = s.ctx.$.node("unit", { meta: enclosed, unit: date });
83
- }
84
- };
85
- var enclosingQuote = {
86
- "'": 1,
87
- '"': 1
88
- };
89
- var enclosingChar = {
90
- "/": 1,
91
- "'": 1,
92
- '"': 1
93
- };
94
- var enclosingLiteralTokens = {
95
- "d'": "'",
96
- 'd"': '"',
97
- "'": "'",
98
- '"': '"'
99
- };
100
- var enclosingRegexTokens = {
101
- "/": "/",
102
- "x/": "/"
103
- };
104
- var enclosingTokens = {
105
- ...enclosingLiteralTokens,
106
- ...enclosingRegexTokens
107
- };
108
- var untilLookaheadIsClosing = {
109
- "'": (sc) => sc.peek === `'`,
110
- '"': (sc) => sc.peek === `"`,
111
- "/": (sc) => sc.peek === `/`
112
- };
113
- var enclosingCharDescriptions = {
114
- '"': "double-quote",
115
- "'": "single-quote",
116
- "/": "forward slash"
117
- };
118
- var writeUnterminatedEnclosedMessage = (fragment, enclosingStart) => `${enclosingStart}${fragment} requires a closing ${enclosingCharDescriptions[enclosingTokens[enclosingStart]]}`;
119
-
120
- // out/parser/shift/operand/unenclosed.js
121
- import { hasArkKind as hasArkKind2, writeUnresolvableMessage } from "@ark/schema";
122
- import { hasOwn as hasOwn2, nonFiniteNumbers, printable, throwParseError as throwParseError3, tryParseWellFormedBigint, tryParseWellFormedNumber, whitespaceChars as whitespaceChars3 } from "@ark/util";
123
-
124
- // out/parser/ast/validate.js
125
- var writePrefixedPrivateReferenceMessage = (name) => `Private type references should not include '#'. Use '${name}' instead.`;
126
- var shallowOptionalMessage = "Optional definitions like 'string?' are only valid as properties in an object or tuple";
127
- var shallowDefaultableMessage = "Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";
128
-
129
- // out/parser/shift/operator/bounds.js
130
- import { $ark, writeUnboundableMessage } from "@ark/schema";
131
- import { isKeyOf as isKeyOf4, throwParseError as throwParseError2 } from "@ark/util";
132
-
133
- // out/parser/ast/bounds.js
134
- var writeDoubleRightBoundMessage = (root) => `Expression ${root} must have at most one right bound`;
135
-
136
- // out/parser/reduce/shared.js
137
- import { inProgress, queueUnchecked } from "@ark/schema";
138
- var minComparators = {
139
- ">": true,
140
- ">=": true
141
- };
142
- var maxComparators = {
143
- "<": true,
144
- "<=": true
145
- };
146
- var comparators = {
147
- ">": true,
148
- ">=": true,
149
- "<": true,
150
- "<=": true,
151
- "==": true,
152
- "!=": true
153
- };
154
- var invertedComparators = {
155
- "<": ">",
156
- ">": "<",
157
- "<=": ">=",
158
- ">=": "<=",
159
- "==": "==",
160
- "!=": "!="
161
- };
162
- var unaliased = (node3) => node3.is("alias") ? node3.resolution : node3;
163
- var checkWrittenIntersection = function (result, l, r) {
164
- if (inProgress.definitions && result.is("alias") && result.operator === "&")
165
- queueUnchecked(() => void unaliased(l).rawAnd(unaliased(r)), result.id);
166
- };
167
- var writeOpenRangeMessage = (min, comparator) => `Left bounds are only valid when paired with right bounds (try ...${comparator}${min})`;
168
- var writeUnpairableComparatorMessage = (comparator) => `Left-bounded expressions must specify their limits using < or <= (was ${comparator})`;
169
- var writeMultipleLeftBoundsMessage = function (openLimit, openComparator, limit, comparator) { return `An expression may have at most one left bound (parsed ${openLimit}${invertedComparators[openComparator]}, ${limit}${invertedComparators[comparator]})` };
170
-
171
- // out/parser/shift/operand/date.js
172
- var isDateLiteral = function (value) { return typeof value === "string" && value[0] === "d" && (value[1] === "'" || value[1] === '"') && value[value.length - 1] === value[1] };
173
- var extractDateLiteralSource = (literal) => literal.slice(2, -1);
174
-
175
- // out/parser/shift/tokens.js
176
- import { isKeyOf as isKeyOf2, whitespaceChars } from "@ark/util";
177
- var terminatingChars = {
178
- "<": 1,
179
- ">": 1,
180
- "=": 1,
181
- "|": 1,
182
- "&": 1,
183
- ")": 1,
184
- "[": 1,
185
- "%": 1,
186
- ",": 1,
187
- ":": 1,
188
- "?": 1,
189
- "#": 1,
190
- ...whitespaceChars
191
- };
192
- var shiftUntilTerminator = function (sc) {
193
- const token = sc.shiftUntilNext(terminatingChars);
194
- if (!token.endsWith("!") || sc.peek !== "=")
195
- return token;
196
- sc.i--;
197
- return token.slice(0, -1);
198
- };
199
- var finalizingLookaheads = {
200
- ">": 1,
201
- ",": 1,
202
- "": 1,
203
- "=": 1,
204
- "?": 1
205
- };
206
- var lookaheadIsFinalizing = function (peek, sc) { return peek === ">" ? sc.peek === "=" ? (
207
- // >== would only occur in an expression like Array<number>==5
208
- // otherwise, >= would only occur as part of a bound like number>=5
209
- sc.peekNext === "="
210
- ) : sc.unscanned.trimStart() === "" || isKeyOf2(sc.unscanned.trimStart()[0], terminatingChars) || sc.unscanned.trimStart().startsWith("!=") : peek === "=" ? sc.peek !== "=" : peek === "," || peek === "?" };
211
-
212
- // out/parser/shift/operator/operator.js
213
- import { isKeyOf as isKeyOf3, whitespaceChars as whitespaceChars2 } from "@ark/util";
214
-
215
- // out/parser/shift/operator/brand.js
216
- var parseBrand = (s) => {
217
- s.sc.skipSpace();
218
- const brandName = shiftUntilTerminator(s.sc);
219
- s.root = s.root.brand(brandName);
220
- };
221
-
222
- // out/parser/shift/operator/divisor.js
223
- import { tryParseInteger } from "@ark/util";
224
- var parseDivisor = function (s) {
225
- s.sc.skipSpace();
226
- const divisorToken = shiftUntilTerminator(s.sc);
227
- const divisor = tryParseInteger(divisorToken, {
228
- errorOnFail: writeInvalidDivisorMessage(divisorToken)
229
- });
230
- if (divisor === 0)
231
- s.error(writeInvalidDivisorMessage(0));
232
- s.root = s.root.rawConstrain("divisor", divisor);
233
- };
234
- var writeInvalidDivisorMessage = (divisor) => `% operator must be followed by a non-zero integer literal (was ${divisor})`;
235
-
236
- // out/parser/shift/operator/operator.js
237
- var parseOperator = function (s) {
238
- const peek = s.sc.shift();
239
- return peek === "" ? s.finalize("") : peek === "[" ? s.sc.shift() === "]" ? s.setRoot(s.root.rawArray()) : s.error(incompleteArrayTokenMessage) : peek === "|" ? s.sc.peek === ">" ? s.shiftedBy(1).pushRootBranch("|>") : s.pushRootBranch(peek) : peek === "&" ? s.pushRootBranch(peek) : peek === ")" ? s.finalizeGroup() : lookaheadIsFinalizing(peek, s.sc) ? s.finalize(peek) : isKeyOf3(peek, comparatorStartChars) ? parseBound(s, peek) : peek === "%" ? parseDivisor(s) : peek === "#" ? parseBrand(s) : peek in whitespaceChars2 ? parseOperator(s) : s.error(writeUnexpectedCharacterMessage(peek));
240
- };
241
- var writeUnexpectedCharacterMessage = (char, shouldBe = "") => `'${char}' is not allowed here${shouldBe && ` (should be ${shouldBe})`}`;
242
- var incompleteArrayTokenMessage = `Missing expected ']'`;
243
-
244
- // out/parser/shift/operator/bounds.js
245
- var parseBound = function (s, start) {
246
- const comparator = shiftComparator(s, start);
247
- if (s.root.is("unit")) {
248
- if (typeof s.root.unit === "number" && Number.isFinite(s.root.unit)) {
249
- s.reduceLeftBound(s.root.unit, comparator);
250
- s.unsetRoot();
251
- return;
252
- }
253
- if (s.root.unit instanceof Date) {
254
- const literal = `d'${s.root.meta.description ?? s.root.unit.toISOString()}'`;
255
- s.unsetRoot();
256
- s.reduceLeftBound(literal, comparator);
257
- return;
258
- }
259
- }
260
- return parseRightBound(s, comparator);
261
- };
262
- var comparatorStartChars = {
263
- "<": 1,
264
- ">": 1,
265
- "=": 1,
266
- "!": 1
267
- };
268
- var shiftComparator = (s, start) => s.sc.peekIs("=") ? `${start}${s.sc.shift()}` : start === "!" ? s.error(writeUnexpectedCharacterMessage(start)) : start;
269
- var writeIncompatibleRangeMessage = (l, r) => `Bound kinds ${l} and ${r} are incompatible`;
270
- var getBoundKinds = function (comparator, limit, root, boundKind) {
271
- if (root.extends($ark.kw.number)) {
272
- if (typeof limit !== "number") {
273
- return throwParseError2(writeInvalidLimitMessage(comparator, limit, boundKind));
274
- }
275
- return comparator === "==" ? ["min", "max"] : comparator === "!=" ? ["notEqual"] : comparator[0] === ">" ? ["min"] : ["max"];
276
- }
277
- if (root.extends($ark.kw.lengthBoundable)) {
278
- if (typeof limit !== "number") {
279
- return throwParseError2(writeInvalidLimitMessage(comparator, limit, boundKind));
280
- }
281
- return comparator === "==" ? ["exactLength"] : comparator === "!=" ? ["notEqualLength"] : comparator[0] === ">" ? ["minLength"] : ["maxLength"];
282
- }
283
- if (root.extends($ark.kw.Date)) {
284
- return comparator === "==" ? ["after", "before"] : comparator === "!=" ? ["notEqual"] : comparator[0] === ">" ? ["after"] : ["before"];
285
- }
286
- return throwParseError2(writeUnboundableMessage(root.expression));
287
- };
288
- var openLeftBoundToRoot = function (lBound) { return ({
289
- rule: isDateLiteral(lBound.limit) ? extractDateLiteralSource(lBound.limit) : lBound.limit,
290
- exclusive: lBound.comparator.length === 1
291
- }) };
292
- var parseRightBound = function (s, comparator) {
293
- if (s.sc.unscanned.trimStart() === "")
294
- return s.error(writeMissingRightOperandMessage(comparator));
295
- const previousRoot = s.unsetRoot();
296
- if (s.rightBounded?.root === previousRoot) {
297
- return s.error(writeDoubleRightBoundMessage(s.rightBounded.operand.expression));
298
- }
299
- const followsArray = comparator === "<" && /(?:^|[^\w$.])Array\s*<$/.test(s.sc.scanned);
300
- const previousScannerIndex = s.sc.location;
301
- s.sc.skipSpace();
302
- let limit = limitOf(s, shiftUntilTerminator(s.sc));
303
- let limitToken = "";
304
- if (limit === void 0) {
305
- s.sc.i = previousScannerIndex;
306
- s.parseOperand();
307
- const limitNode = s.unsetRoot();
308
- limitToken = s.sc.sliceChars(previousScannerIndex, s.sc.location).trim();
309
- if (!limitNode?.is("unit") || typeof limitNode.unit !== "number" && !(limitNode.unit instanceof Date) || typeof limitNode.unit === "number" && !Number.isFinite(limitNode.unit)) {
310
- return s.error(writeInvalidLimitMessage(comparator, limitToken, "right") + (followsArray ? arrayIsNotGenericHint : ""));
311
- }
312
- limit = limitNode.unit;
313
- }
314
- s.root = previousRoot;
315
- const exclusive = comparator.length === 1;
316
- const boundKinds = getBoundKinds(comparator, typeof limit === "number" ? limit : limitToken, previousRoot, "right");
317
- const rule = comparator === "!=" && typeof limit === "number" && previousRoot.extends($ark.kw.Date) ? new Date(limit) : limit;
318
- for (const kind of boundKinds)
319
- s.constrainRoot(kind, comparator === "==" ? { rule } : { rule, exclusive });
320
- if (!s.branches.lBound) {
321
- s.rightBounded = { root: s.root, operand: previousRoot };
322
- return;
323
- }
324
- if (!isKeyOf4(comparator, maxComparators))
325
- return s.error(writeUnpairableComparatorMessage(comparator));
326
- const lowerBoundKind = getBoundKinds(s.branches.lBound.comparator, s.branches.lBound.limit, previousRoot, "left");
327
- s.constrainRoot(lowerBoundKind[0], openLeftBoundToRoot(s.branches.lBound));
328
- s.branches.lBound = null;
329
- s.rightBounded = { root: s.root, operand: previousRoot };
330
- };
331
- var arrayIsNotGenericHint = ". Array isn't generic here: write an array of strings as string[]";
332
- var writeInvalidLimitMessage = function (comparator, limit, boundKind) { return `Comparator ${boundKind === "left" ? invertedComparators[comparator] : comparator} must be ${boundKind === "left" ? "preceded" : "followed"} by a corresponding literal (was ${limit})` };
333
-
334
- // out/parser/shift/operand/genericArgs.js
335
- import { writeUnclosedGroupMessage } from "@ark/util";
336
- var parseGenericArgs = (name, g, s) => _parseGenericArgs(name, g, s, []);
337
- var _parseGenericArgs = function (name, g, s, argNodes) {
338
- const argState = s.parseUntilFinalizer();
339
- argNodes.push(argState.root);
340
- if (argState.finalizer === ">") {
341
- if (argNodes.length !== g.params.length) {
342
- return s.error(writeInvalidGenericArgCountMessage(name, g.names, argNodes.map((arg) => arg.expression)));
343
- }
344
- return argNodes;
345
- }
346
- if (argState.finalizer === ",")
347
- return _parseGenericArgs(name, g, s, argNodes);
348
- return argState.error(writeUnclosedGroupMessage(">"));
349
- };
350
- var writeInvalidGenericArgCountMessage = function (name, params, argDefs) { return `${name}<${params.join(", ")}> requires exactly ${params.length} args (got ${argDefs.length}${argDefs.length === 0 ? "" : `: ${argDefs.join(", ")}`})` };
351
-
352
- // out/parser/shift/operand/unresolvable.js
353
- import { hasArkKind } from "@ark/schema";
354
- import { editsBetween, hasOwn } from "@ark/util";
355
- var foreignAliases = {
356
- // TypeScript
357
- any: "unknown.any",
358
- void: "undefined",
359
- String: "string",
360
- Number: "number",
361
- Boolean: "boolean",
362
- BigInt: "bigint",
363
- Symbol: "symbol",
364
- Object: "object",
365
- function: "Function",
366
- array: "unknown[]",
367
- // other languages, and JSON Schema's `integer`
368
- str: "string",
369
- bool: "boolean",
370
- num: "number",
371
- int: "number.integer",
372
- integer: "number.integer",
373
- float: "number",
374
- double: "number",
375
- decimal: "number",
376
- "number.int": "number.integer",
377
- "number.float": "number",
378
- "number.positive": "number > 0",
379
- "number.negative": "number < 0",
380
- "number.nonnegative": "number >= 0",
381
- "string.nonempty": "string > 0",
382
- // Zod's formats, and JSON Schema's
383
- date: "Date",
384
- datetime: "string.date.iso",
385
- "string.datetime": "string.date.iso",
386
- timestamp: "number.epoch",
387
- email: "string.email",
388
- uuid: "string.uuid",
389
- guid: "string.uuid",
390
- "string.guid": "string.uuid",
391
- url: "string.url",
392
- uri: "string.url",
393
- "string.uri": "string.url",
394
- ip: "string.ip",
395
- ipv4: "string.ip.v4",
396
- ipv6: "string.ip.v6",
397
- "string.ipv4": "string.ip.v4",
398
- "string.ipv6": "string.ip.v6",
399
- json: "string.json",
400
- base64: "string.base64",
401
- hex: "string.hex",
402
- regex: "RegExp",
403
- regexp: "RegExp",
404
- nan: "number.NaN"
405
- };
406
- var writeUnresolvableHint = function (name, $, args) {
407
- if (hasOwn(foreignAliases, name))
408
- return writeDidYouMean([foreignAliases[name]]);
409
- if (/^[\d-]/.test(name))
410
- return "";
411
- const scopes = [args ?? {}, $.aliases, $.ambient];
412
- const path = name.split(".");
413
- let submodule;
414
- let depth = 0;
415
- for (; depth < path.length - 1; depth++) {
416
- const from = submodule ?? scopes.find((aliases) => hasOwn(aliases, path[depth]));
417
- const next2 = from && hasOwn(from, path[depth]) ? from[path[depth]] : null;
418
- if (!hasArkKind(next2, "module"))
419
- break;
420
- submodule = next2;
421
- }
422
- if (!submodule)
423
- return writeDidYouMean(nearest(name, scopes.flatMap(namesIn)));
424
- const prefix = `${path.slice(0, depth).join(".")}.`;
425
- const rest = path.slice(depth).join(".");
426
- const keys = Object.keys(submodule).filter((k) => k !== "root");
427
- const started = rest && keys.filter((k) => k.startsWith(rest));
428
- const suggested = started && started.length ? started : nearest(rest, namesIn(submodule));
429
- return suggested.length ? writeDidYouMean(suggested.map((k) => prefix + k)) : `. '${prefix.slice(0, -1)}' has ${keys.join(", ")}.`;
430
- };
431
- var writeDidYouMean = function (names) {
432
- if (names.length === 0)
433
- return "";
434
- const quoted = names.slice(0, 3).map((name) => `'${name}'`);
435
- const last = quoted.pop();
436
- return `. Did you mean ${quoted.length ? `${quoted.join(", ")} or ${last}` : last}?`;
437
- };
438
- var namesIn = function (aliases) { return Object.keys(aliases).flatMap((k) => {
439
- if (k === "root")
440
- return [];
441
- const v = aliases[k];
442
- if (!hasArkKind(v, "module"))
443
- return [k];
444
- const nested = namesIn(v).map((name) => `${k}.${name}`);
445
- return hasOwn(v, "root") ? [k, ...nested] : nested;
446
- }) };
447
- var nearest = function (name, candidates) {
448
- const lower = name.toLowerCase();
449
- let limit = name.length < 3 ? 0 : name.length < 5 ? 1 : 2;
450
- let found = [];
451
- for (const candidate of new Set(candidates)) {
452
- const full = candidate.toLowerCase();
453
- const distance = Math.min(editsBetween(lower, full), editsBetween(lower, full.slice(full.lastIndexOf(".") + 1)));
454
- if (distance > limit)
455
- continue;
456
- if (distance < limit)
457
- found = [];
458
- limit = distance;
459
- found.push(candidate);
460
- }
461
- return found;
462
- };
463
-
464
- // out/parser/shift/operand/unenclosed.js
465
- var parseUnenclosed = function (s) {
466
- const token = shiftUntilTerminator(s.sc);
467
- if (token === "keyof")
468
- s.addPrefix("keyof");
469
- else if (!reducedLeftLimit(s, token))
470
- s.root = unenclosedToNode(s, token);
471
- };
472
- var limitOf = function (s, token) {
473
- const first = token.charCodeAt(0);
474
- if (first !== 45 && (first < 48 || first > 57))
475
- return;
476
- const limit = tryParseWellFormedNumber(token);
477
- if (limit === void 0 || !Number.isFinite(limit))
478
- return;
479
- if (s.ctx.args && hasOwn2(s.ctx.args, token))
480
- return;
481
- return s.ctx.$.maybeResolve(token) === void 0 ? limit : void 0;
482
- };
483
- var reducedLeftLimit = function (s, token) {
484
- let i = s.sc.i;
485
- while (s.sc.chars[i] in whitespaceChars3)
486
- i++;
487
- if (s.sc.chars[i] !== "<")
488
- return false;
489
- const limit = limitOf(s, token);
490
- if (limit === void 0)
491
- return false;
492
- s.sc.i = i + 1;
493
- s.reduceLeftBound(limit, shiftComparator(s, "<"));
494
- return true;
495
- };
496
- var parseGenericInstantiation = function (name, g, s) {
497
- s.sc.skipSpace();
498
- const peek = s.sc.shift();
499
- if (peek !== "<")
500
- return s.error(writeInvalidGenericArgCountMessage(name, g.names, []));
501
- const parsedArgs = parseGenericArgs(name, g, s);
502
- return g(...parsedArgs);
503
- };
504
- var unenclosedToNode = function (s, token) { return maybeParseReference(s, token) ?? maybeParseUnenclosedLiteral(s, token) ?? s.error(token === "" ? s.sc.peek === "#" ? writePrefixedPrivateReferenceMessage(shiftUntilTerminator(s.shiftedBy(1).sc)) : writeMissingOperandMessage(s) : writeUnresolvableMessage(token) + writeUnresolvableHint(token, s.ctx.$, s.ctx.args)) };
505
- var maybeParseReference = function (s, token) {
506
- if (s.ctx.args && hasOwn2(s.ctx.args, token)) {
507
- const arg = s.ctx.args[token];
508
- if (typeof arg !== "string")
509
- return arg;
510
- return s.ctx.$.node("alias", { reference: arg }, { reduced: true });
511
- }
512
- const resolution = s.ctx.$.maybeResolve(token);
513
- if (hasArkKind2(resolution, "root"))
514
- return resolution;
515
- if (resolution === void 0)
516
- return;
517
- if (hasArkKind2(resolution, "generic"))
518
- return parseGenericInstantiation(token, resolution, s);
519
- return throwParseError3(`Unexpected resolution ${printable(resolution)}`);
520
- };
521
- var maybeParseUnenclosedLiteral = function (s, token) {
522
- const maybeNumber = hasOwn2(nonFiniteNumbers, token) ? nonFiniteNumbers[token] : tryParseWellFormedNumber(token);
523
- if (maybeNumber !== void 0)
524
- return s.ctx.$.node("unit", { unit: maybeNumber });
525
- const maybeBigint = tryParseWellFormedBigint(token);
526
- if (maybeBigint !== void 0)
527
- return s.ctx.$.node("unit", { unit: maybeBigint });
528
- };
529
- var writeMissingOperandMessage = function (s) {
530
- const operator = s.previousOperator();
531
- return operator ? writeMissingRightOperandMessage(operator, s.sc.unscanned) : writeExpressionExpectedMessage(s.sc.unscanned);
532
- };
533
- var writeMissingRightOperandMessage = (token, unscanned = "") => `Token '${token}' requires a right operand${unscanned ? ` before '${unscanned}'` : ""}`;
534
- var writeExpressionExpectedMessage = (unscanned) => `Expected an expression${unscanned ? ` before '${unscanned}'` : ""}`;
535
-
536
- // out/parser/shift/operand/operand.js
537
- var parseOperand = function (s) { return s.sc.peek === "" ? s.error(writeMissingOperandMessage(s)) : s.sc.peek === "(" ? s.shiftedBy(1).reduceGroupOpen() : s.sc.peekIsIn(enclosingChar) ? parseEnclosed(s, s.sc.shift()) : s.sc.peekIsIn(whitespaceChars4) ? parseOperand(s.shiftedBy(1)) : s.sc.peek === "[" && s.sc.peekNext === "]" ? s.shiftedBy(2).setRoot(emptyTuple(s.ctx.$)) : s.sc.peek === "d" ? s.sc.peekNext in enclosingQuote ? parseEnclosed(s, `${s.sc.shift()}${s.sc.shift()}`) : parseUnenclosed(s) : s.sc.peek === "x" ? s.sc.peekNext === "/" ? s.shiftedBy(2) && parseEnclosed(s, "x/") : parseUnenclosed(s) : parseUnenclosed(s) };
538
- var emptyTuple = function ($) { return $.node("intersection", {
539
- proto: $.node("proto", { proto: Array }),
540
- exactLength: $.node("exactLength", { rule: 0 })
541
- }) };
542
-
543
- // out/parser/string.js
544
- import { Scanner, throwInternalError, throwParseError as throwParseError4 } from "@ark/util";
545
-
546
- // out/parser/shift/operator/default.js
547
- import { keysOf } from "@ark/util";
548
- var emptyCollectionLiterals = keysOf(emptyCollectionDefaults);
549
- var parseDefault = function (s) {
550
- const baseNode = s.unsetRoot();
551
- s.sc.skipSpace();
552
- const emptyCollection = emptyCollectionLiterals.find((literal) => s.sc.unscanned.startsWith(literal));
553
- if (emptyCollection !== void 0) {
554
- s.sc.jumpForward(emptyCollection.length);
555
- return [baseNode, "=", emptyCollectionDefaults[emptyCollection]];
556
- }
557
- const start = s.sc.location;
558
- s.parseOperand();
559
- const defaultNode = s.unsetRoot();
560
- if (!defaultNode?.is("unit")) {
561
- return s.error(writeNonLiteralDefaultMessage(defaultNode?.expression ?? s.sc.sliceChars(start).trim()));
562
- }
563
- const defaultValue = defaultNode.unit instanceof Date ? () => new Date(defaultNode.unit) : defaultNode.unit;
564
- return [baseNode, "=", defaultValue];
565
- };
566
- var writeNonLiteralDefaultMessage = (defaultDef) => `Default value '${defaultDef}' must be a literal value`;
567
-
568
- // out/parser/string.js
569
- var parseString = function (def, ctx) {
570
- const aliasResolution = ctx.$.maybeResolveRoot(def);
571
- if (aliasResolution)
572
- return aliasResolution;
573
- if (def.endsWith("[]")) {
574
- const possibleElementResolution = ctx.$.maybeResolveRoot(def.slice(0, -2));
575
- if (possibleElementResolution)
576
- return possibleElementResolution.rawArray();
577
- }
578
- const s = new RuntimeState(new Scanner(def), ctx);
579
- const node3 = fullStringParse(s);
580
- if (s.finalizer === ">")
581
- throwParseError4(writeUnexpectedCharacterMessage(">"));
582
- return node3;
583
- };
584
- var fullStringParse = function (s) {
585
- s.parseOperand();
586
- let result = parseUntilFinalizer(s).root;
587
- if (!result) {
588
- return throwInternalError(`Root was unexpectedly unset after parsing string '${s.sc.scanned}'`);
589
- }
590
- if (s.finalizer === "=")
591
- result = parseDefault(s);
592
- else if (s.finalizer === "?")
593
- result = [result, "?"];
594
- s.sc.skipSpace();
595
- if (s.sc.peek) {
596
- throwParseError4(writeUnexpectedCharacterMessage(s.sc.peek));
597
- }
598
- return result;
599
- };
600
- var parseUntilFinalizer = (s) => {
601
- while (s.finalizer === void 0)
602
- next(s);
603
- return s;
604
- };
605
- var next = (s) => s.hasRoot() ? s.parseOperator() : s.parseOperand();
606
-
607
- // out/parser/reduce/dynamic.js
608
- var RuntimeState = class RuntimeState {
609
- root;
610
- branches = {
611
- prefixes: [],
612
- lBound: null,
613
- intersection: null,
614
- union: null,
615
- units: null,
616
- pipe: null
617
- };
618
- finalizer;
619
- groups = [];
620
- // a right bound's root and the operand it bounded, until the next operand
621
- rightBounded;
622
- /** what it's parsing, scanned up to its next token */
623
- sc;
624
- ctx;
625
- constructor(sc, ctx) {
626
- this.sc = sc;
627
- this.ctx = ctx;
628
- }
629
- error(message) {
630
- return throwParseError5(message);
631
- }
632
- hasRoot() {
633
- return this.root !== void 0;
634
- }
635
- setRoot(root) {
636
- this.root = root;
637
- }
638
- unsetRoot() {
639
- const value = this.root;
640
- this.root = void 0;
641
- return value;
642
- }
643
- constrainRoot(...args) {
644
- this.root = this.root.rawConstrain(args[0], args[1]);
645
- }
646
- finalize(finalizer) {
647
- if (this.groups.length)
648
- return this.error(writeUnclosedGroupMessage2(")"));
649
- this.finalizeBranches();
650
- this.finalizer = finalizer;
651
- }
652
- reduceLeftBound(limit, comparator) {
653
- const invertedComparator = invertedComparators[comparator];
654
- if (!isKeyOf5(invertedComparator, minComparators))
655
- return this.error(writeUnpairableComparatorMessage(comparator));
656
- if (this.branches.lBound) {
657
- return this.error(writeMultipleLeftBoundsMessage(this.branches.lBound.limit, this.branches.lBound.comparator, limit, invertedComparator));
658
- }
659
- this.branches.lBound = {
660
- comparator: invertedComparator,
661
- limit
662
- };
663
- }
664
- finalizeBranches() {
665
- this.assertRangeUnset();
666
- if (this.branches.pipe) {
667
- this.pushRootBranch("|>");
668
- this.root = this.branches.pipe;
669
- return;
670
- }
671
- if (this.branches.union || this.branches.units) {
672
- this.pushRootBranch("|");
673
- this.unionUnits();
674
- this.root = this.branches.union;
675
- return;
676
- }
677
- if (this.branches.intersection) {
678
- this.pushRootBranch("&");
679
- this.root = this.branches.intersection;
680
- return;
681
- }
682
- this.applyPrefixes();
683
- }
684
- finalizeGroup() {
685
- this.finalizeBranches();
686
- const topBranchState = this.groups.pop();
687
- if (!topBranchState)
688
- return this.error(writeUnmatchedGroupCloseMessage(")", this.sc.unscanned));
689
- this.branches = topBranchState;
690
- this.rightBounded = void 0;
691
- }
692
- addPrefix(prefix) {
693
- this.branches.prefixes.push(prefix);
694
- }
695
- applyPrefixes() {
696
- while (this.branches.prefixes.length) {
697
- const lastPrefix = this.branches.prefixes.pop();
698
- this.root = lastPrefix === "keyof" ? this.root.keyof() : throwInternalError2(`Unexpected prefix '${lastPrefix}'`);
699
- }
700
- }
701
- unionUnits() {
702
- const units = this.branches.units;
703
- if (!units)
704
- return;
705
- this.branches.units = null;
706
- this.branches.union = units.length === 1 ? units[0] : units[0].$.node("union", { branches: units });
707
- }
708
- pushRootBranch(token) {
709
- this.assertRangeUnset();
710
- this.applyPrefixes();
711
- const root = this.root;
712
- this.root = void 0;
713
- const l = this.branches.intersection;
714
- this.branches.intersection = l?.rawAnd(root) ?? root;
715
- if (l)
716
- checkWrittenIntersection(this.branches.intersection, l, root);
717
- if (token === "&")
718
- return;
719
- const operand = this.branches.intersection;
720
- this.branches.intersection = null;
721
- if (!this.branches.union && operand.is("unit") && isEmptyObject(operand.meta))
722
- (this.branches.units ??= []).push(operand);
723
- else {
724
- this.unionUnits();
725
- this.branches.union = this.branches.union?.rawOr(operand) ?? operand;
726
- }
727
- if (token === "|")
728
- return;
729
- this.unionUnits();
730
- this.branches.pipe = this.branches.pipe?.rawPipeOnce(this.branches.union) ?? this.branches.union;
731
- this.branches.union = null;
732
- }
733
- parseUntilFinalizer() {
734
- return parseUntilFinalizer(new RuntimeState(this.sc, this.ctx));
735
- }
736
- parseOperator() {
737
- return parseOperator(this);
738
- }
739
- parseOperand() {
740
- this.rightBounded = void 0;
741
- return parseOperand(this);
742
- }
743
- assertRangeUnset() {
744
- if (this.branches.lBound) {
745
- return this.error(writeOpenRangeMessage(this.branches.lBound.limit, this.branches.lBound.comparator));
746
- }
747
- }
748
- reduceGroupOpen() {
749
- this.groups.push(this.branches);
750
- this.branches = {
751
- prefixes: [],
752
- lBound: null,
753
- union: null,
754
- units: null,
755
- intersection: null,
756
- pipe: null
757
- };
758
- }
759
- previousOperator() {
760
- return (
761
- // left bounds are stored inverted, as they'd be written on the right
762
- (this.branches.lBound && invertedComparators[this.branches.lBound.comparator]) ?? this.branches.prefixes[this.branches.prefixes.length - 1] ?? (this.branches.intersection ? "&" : this.branches.union || this.branches.units ? "|" : this.branches.pipe ? "|>" : void 0)
763
- );
764
- }
765
- shiftedBy(count) {
766
- this.sc.jumpForward(count);
767
- return this;
768
- }
769
- };
770
-
771
- // out/generic.js
772
- var Generic = GenericRoot;
773
- var emptyGenericParameterMessage = "An empty string is not a valid generic parameter name";
774
- var parseGenericParamName = function (sc, result, ctx) {
775
- sc.skipSpace();
776
- const name = shiftUntilTerminator(sc);
777
- if (name === "") {
778
- if (sc.peek === "" && result.length)
779
- return result;
780
- return throwParseError6(emptyGenericParameterMessage);
781
- }
782
- sc.skipSpace();
783
- return _parseOptionalConstraint(sc, name, result, ctx);
784
- };
785
- var extendsToken = "extends ";
786
- var _parseOptionalConstraint = function (sc, name, result, ctx) {
787
- sc.skipSpace();
788
- if (sc.unscanned.startsWith(extendsToken))
789
- sc.jumpForward(extendsToken.length);
790
- else {
791
- if (sc.peek === ",")
792
- sc.shift();
793
- result.push(name);
794
- return parseGenericParamName(sc, result, ctx);
795
- }
796
- const s = parseUntilFinalizer(new RuntimeState(sc, ctx));
797
- result.push([name, s.root]);
798
- return parseGenericParamName(sc, result, ctx);
799
- };
800
-
801
- // out/match.js
802
- import { intrinsic, throwOnDefault } from "@ark/schema";
803
- import { Callable, domainOf, throwParseError as throwParseError7 } from "@ark/util";
804
- var InternalMatchParser = class extends Callable {
805
- $;
806
- constructor($) {
807
- super((...args) => new InternalChainedMatchParser($)(...args), {
808
- bind: $
809
- });
810
- this.$ = $;
811
- }
812
- in(def) {
813
- return new InternalChainedMatchParser(this.$, def === void 0 ? void 0 : this.$.parse(def));
814
- }
815
- at(key, cases) {
816
- return new InternalChainedMatchParser(this.$).at(key, cases);
817
- }
818
- case(when, then) {
819
- return new InternalChainedMatchParser(this.$).case(when, then);
820
- }
821
- };
822
- var InternalChainedMatchParser = class extends Callable {
823
- $;
824
- in;
825
- key;
826
- branches = [];
827
- constructor($, In) {
828
- super((cases) => this.caseEntries(Object.entries(cases).map(([k, v]) => k === "default" ? [k, v] : [this.$.parse(k), v])));
829
- this.$ = $;
830
- this.in = In;
831
- }
832
- at(key, cases) {
833
- if (this.key)
834
- throwParseError7(doubleAtMessage);
835
- if (this.branches.length)
836
- throwParseError7(chainedAtMessage);
837
- this.key = key;
838
- return cases ? this.match(cases) : this;
839
- }
840
- case(def, resolver) {
841
- return this.caseEntry(this.$.parse(def), resolver);
842
- }
843
- caseEntry(node3, resolver) {
844
- const wrappableNode = this.key ? this.$.parse({ [this.key]: node3 }) : node3;
845
- const branch = wrappableNode.pipe(resolver);
846
- this.branches.push(branch);
847
- return this;
848
- }
849
- match(cases) {
850
- return this(cases);
851
- }
852
- strings(cases) {
853
- return this.caseEntries(Object.entries(cases).map(([k, v]) => k === "default" ? [k, v] : [this.$.node("unit", { unit: k }), v]));
854
- }
855
- caseEntries(entries) {
856
- for (let i = 0; i < entries.length; i++) {
857
- const [k, v] = entries[i];
858
- if (k === "default") {
859
- if (i !== entries.length - 1) {
860
- throwParseError7(`default may only be specified as the last key of a switch definition`);
861
- }
862
- return this.default(v);
863
- }
864
- if (typeof v !== "function") {
865
- return throwParseError7(`Value for case "${k}" must be a function (was ${domainOf(v)})`);
866
- }
867
- this.caseEntry(k, v);
868
- }
869
- return this;
870
- }
871
- default(defaultCase) {
872
- if (typeof defaultCase === "function")
873
- this.case(intrinsic.unknown, defaultCase);
874
- const schema = {
875
- branches: this.branches,
876
- ordered: true
877
- };
878
- if (defaultCase === "never" || defaultCase === "assert")
879
- schema.meta = { onFail: throwOnDefault };
880
- const cases = this.$.node("union", schema);
881
- if (!this.in)
882
- return this.$.fin(cases);
883
- let inputValidatedCases = this.in.pipe(cases);
884
- if (defaultCase === "never" || defaultCase === "assert") {
885
- inputValidatedCases = inputValidatedCases.configureRefs({
886
- onFail: throwOnDefault
887
- }, "self");
888
- }
889
- return this.$.fin(inputValidatedCases);
890
- }
891
- };
892
- var chainedAtMessage = `A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')`;
893
- var doubleAtMessage = `At most one key matcher may be specified per expression`;
894
-
895
- // out/parser/definition.js
896
- import { $ark as $ark3, asTemplated, BaseRoot, constraintInputOf, hasArkKind as hasArkKind3, foreignTypesByMorph, inProgress as inProgress2, isCustomIssue } from "@ark/schema";
897
- import { domainOf as domainOf2, hasDomain, hasOwn as hasOwn4, isArray as isArray4, isInstanceOf, isStandardSchema, isThunk, objectKindOf, printable as printable3, throwError, throwParseError as throwParseError11 } from "@ark/util";
898
-
899
- // out/parser/objectLiteral.js
900
- import { checkDefault, intrinsic as intrinsic2, normalizeIndex, ownKeysOf, requiredPropOf } from "@ark/schema";
901
- import { append, Backslash as Backslash2, isArray as isArray2, isEmptyObject as isEmptyObject2, printable as printable2, throwParseError as throwParseError8 } from "@ark/util";
902
-
903
- // out/parser/property.js
904
- import { isArray } from "@ark/util";
905
- var parseProperty = function (def, ctx) {
906
- if (isArray(def)) {
907
- if (def[1] === "=")
908
- return [ctx.$.parseOwn(def[0], ctx), "=", def[2]];
909
- if (def[1] === "?")
910
- return [ctx.$.parseOwn(def[0], ctx), "?"];
911
- }
912
- return parseInnerDefinition(def, ctx);
913
- };
914
- var invalidOptionalKeyKindMessage = `Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }`;
915
- var invalidDefaultableKeyKindMessage = `Only required keys may specify default values, e.g. { value: 'number = 0' }`;
916
-
917
- // out/parser/objectLiteral.js
918
- var parseObjectLiteral = function (def, ctx) {
919
- let spread;
920
- let meta;
921
- const structure = {};
922
- const order = [];
923
- for (const k of ownKeysOf(def)) {
924
- const v = def[k];
925
- const parsedKey = preparseKey(k);
926
- if (parsedKey.kind === "spread") {
927
- if (!isEmptyObject2(structure))
928
- return throwParseError8(nonLeadingSpreadError);
929
- const operand = ctx.$.parseOwn(v, ctx);
930
- if (operand.equals(intrinsic2.object))
931
- continue;
932
- if (!operand.is("intersection") || // still error on attempts to spread proto nodes like ...Date
933
- !operand.basis?.equals(intrinsic2.object)) {
934
- return throwParseError8(writeInvalidSpreadTypeMessage(operand.expression));
935
- }
936
- spread = operand.structure;
937
- continue;
938
- }
939
- if (parsedKey.kind === "undeclared") {
940
- if (v !== "reject" && v !== "delete" && v !== "ignore")
941
- throwParseError8(writeInvalidUndeclaredBehaviorMessage(v));
942
- structure.undeclared = v;
943
- continue;
944
- }
945
- if (parsedKey.kind === "meta") {
946
- meta = v;
947
- continue;
948
- }
949
- const parsedValue = parseProperty(v, ctx);
950
- const parsedEntryKey = parsedKey;
951
- if (parsedKey.kind !== "index")
952
- order.push(parsedEntryKey.normalized);
953
- if (parsedKey.kind === "required") {
954
- if (!isArray2(parsedValue)) {
955
- appendNamedProp(structure, "required", {
956
- key: parsedKey.normalized,
957
- value: parsedValue
958
- }, ctx);
959
- } else {
960
- if (typeof v === "string" && typeof parsedValue[2] === "function")
961
- checkDefault(parsedValue[0], parsedValue[2](), parsedKey.normalized);
962
- appendNamedProp(structure, "optional", parsedValue[1] === "=" ? {
963
- key: parsedKey.normalized,
964
- value: parsedValue[0],
965
- default: parsedValue[2]
966
- } : {
967
- key: parsedKey.normalized,
968
- value: parsedValue[0]
969
- }, ctx);
970
- }
971
- continue;
972
- }
973
- if (isArray2(parsedValue)) {
974
- if (parsedValue[1] === "?")
975
- throwParseError8(invalidOptionalKeyKindMessage);
976
- if (parsedValue[1] === "=")
977
- throwParseError8(invalidDefaultableKeyKindMessage);
978
- }
979
- if (parsedKey.kind === "optional") {
980
- appendNamedProp(structure, "optional", {
981
- key: parsedKey.normalized,
982
- value: parsedValue
983
- }, ctx);
984
- continue;
985
- }
986
- const signature = ctx.$.parseOwn(parsedEntryKey.normalized, ctx);
987
- const normalized = normalizeIndex(signature, parsedValue, ctx.$);
988
- if (normalized.index)
989
- structure.index = append(structure.index, normalized.index);
990
- if (normalized.required) {
991
- structure.required = append(structure.required, normalized.required);
992
- for (const prop of normalized.required)
993
- order.push(prop.key);
994
- }
995
- }
996
- if (order.length > 1)
997
- structure.order = order;
998
- const structureNode = ctx.$.node("structure", structure);
999
- const node3 = ctx.$.node("intersection", {
1000
- domain: objectDomainOf(ctx.$),
1001
- structure: spread?.merge(structureNode) ?? structureNode
1002
- }, { reduced: true });
1003
- return meta === void 0 ? node3 : node3.configure(meta);
1004
- };
1005
- var objectDomains = /* @__PURE__ */ new WeakMap();
1006
- var objectDomainOf = function ($) {
1007
- let domain = objectDomains.get($);
1008
- if (!domain) {
1009
- domain = $.node("domain", { domain: "object" });
1010
- objectDomains.set($, domain);
1011
- }
1012
- return domain;
1013
- };
1014
- var appendNamedProp = function (structure, kind, input, ctx) {
1015
- structure[kind] = append(
1016
- // doesn't seem like this cast should be necessary
1017
- structure[kind],
1018
- kind === "required" ? requiredPropOf(input.key, input.value, ctx.$) : ctx.$.node(kind, input)
1019
- );
1020
- };
1021
- var writeInvalidUndeclaredBehaviorMessage = (actual) => `Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${printable2(actual)})`;
1022
- var writeOptionalIndexKeyMessage = (key) => `Index signature ${key} can't be optional. Escape its '[' with a backslash for an optional key named '${key}'`;
1023
- var nonLeadingSpreadError = "Spread operator may only be used as the first key in an object";
1024
- var preparseKey = function (key) { return typeof key === "symbol" ? { kind: "required", normalized: key } : key[key.length - 1] === "?" ? key[key.length - 2] === Backslash2 ? { kind: "required", normalized: `${key.slice(0, -2)}?` } : key[0] === "[" && key[key.length - 2] === "]" ? throwParseError8(writeOptionalIndexKeyMessage(key.slice(0, -1))) : key[0] === Backslash2 && key[1] === "[" && key[key.length - 2] === "]" ? { kind: "optional", normalized: key.slice(1, -1) } : { kind: "optional", normalized: key.slice(0, -1) } : key[0] === "[" && key[key.length - 1] === "]" ? { kind: "index", normalized: key.slice(1, -1) } : key[0] === Backslash2 && key[1] === "[" && key[key.length - 1] === "]" ? { kind: "required", normalized: key.slice(1) } : key === "..." ? { kind: "spread" } : key === "+" ? { kind: "undeclared" } : key === "@" ? { kind: "meta" } : {
1025
- kind: "required",
1026
- normalized: key === "\\..." ? "..." : key === "\\+" ? "+" : key === "\\@" ? "@" : key
1027
- } };
1028
- var writeInvalidSpreadTypeMessage = (def) => `Spread operand must resolve to an object literal type (was ${def})`;
1029
-
1030
- // out/parser/tupleExpressions.js
1031
- import { Disjoint } from "@ark/schema";
1032
- import { hasOwn as hasOwn3, objectKindOrDomainOf, throwParseError as throwParseError9 } from "@ark/util";
1033
- import { intersectNodesRoot, pipeNodesRoot } from "arksets/internal";
1034
- var maybeParseTupleExpression = function (def, ctx) { return isIndexZeroExpression(def) ? indexZeroParsers[def[0]](def, ctx) : isIndexOneExpression(def) ? indexOneParsers[def[1]](def, ctx) : null };
1035
- var parseKeyOfTuple = (def, ctx) => ctx.$.parseOwn(def[1], ctx).keyof();
1036
- var parseBranchTuple = function (def, ctx) {
1037
- if (def[2] === void 0)
1038
- return throwParseError9(writeMissingRightOperandMessage(def[1], ""));
1039
- const l = ctx.$.parseOwn(def[0], ctx);
1040
- const r = ctx.$.parseOwn(def[2], ctx);
1041
- if (def[1] === "|")
1042
- return ctx.$.node("union", { branches: [l, r] });
1043
- const result = def[1] === "&" ? intersectNodesRoot(l, r, ctx.$) : pipeNodesRoot(l, r, ctx.$);
1044
- if (result instanceof Disjoint)
1045
- return result.throw();
1046
- if (def[1] === "&")
1047
- checkWrittenIntersection(result, l, r);
1048
- return result;
1049
- };
1050
- var parseArrayTuple = (def, ctx) => ctx.$.parseOwn(def[0], ctx).rawArray();
1051
- var parseMorphTuple = function (def, ctx) {
1052
- if (typeof def[2] !== "function") {
1053
- return throwParseError9(writeMalformedFunctionalExpressionMessage("=>", def[2]));
1054
- }
1055
- return ctx.$.parseOwn(def[0], ctx).pipe(def[2]);
1056
- };
1057
- var writeMalformedFunctionalExpressionMessage = (operator, value) => `${operator === ":" ? "Narrow" : "Morph"} expression requires a function following '${operator}' (was ${typeof value})`;
1058
- var parseNarrowTuple = function (def, ctx) {
1059
- if (typeof def[2] !== "function") {
1060
- return throwParseError9(writeMalformedFunctionalExpressionMessage(":", def[2]));
1061
- }
1062
- return ctx.$.parseOwn(def[0], ctx).rawConstrain("predicate", def[2]);
1063
- };
1064
- var parseMetaTuple = (def, ctx) => ctx.$.parseOwn(def[0], ctx).configure(def[2], def[3]);
1065
- var defineIndexOneParsers = (parsers) => parsers;
1066
- var postfixParsers = defineIndexOneParsers({
1067
- "[]": parseArrayTuple,
1068
- "?": () => throwParseError9(shallowOptionalMessage)
1069
- });
1070
- var infixParsers = defineIndexOneParsers({
1071
- "|": parseBranchTuple,
1072
- "&": parseBranchTuple,
1073
- ":": parseNarrowTuple,
1074
- "=>": parseMorphTuple,
1075
- "|>": parseBranchTuple,
1076
- "@": parseMetaTuple,
1077
- // since object and tuple literals parse there via `parseProperty`,
1078
- // they must be shallow if parsed directly as a tuple expression
1079
- "=": () => throwParseError9(shallowDefaultableMessage)
1080
- });
1081
- var indexOneParsers = { ...postfixParsers, ...infixParsers };
1082
- var isIndexOneExpression = (def) => isOperatorOf(def[1], indexOneParsers);
1083
- var defineIndexZeroParsers = (parsers) => parsers;
1084
- var indexZeroParsers = defineIndexZeroParsers({
1085
- keyof: parseKeyOfTuple,
1086
- instanceof: function (def, ctx) {
1087
- if (typeof def[1] !== "function") {
1088
- return throwParseError9(writeInvalidConstructorMessage(objectKindOrDomainOf(def[1])));
1089
- }
1090
- const branches = def.slice(1).map((ctor) => typeof ctor === "function" ? ctx.$.node("proto", { proto: ctor }) : throwParseError9(writeInvalidConstructorMessage(objectKindOrDomainOf(ctor))));
1091
- return branches.length === 1 ? branches[0] : ctx.$.node("union", { branches });
1092
- },
1093
- "===": (def, ctx) => ctx.$.units(def.slice(1))
1094
- });
1095
- var isIndexZeroExpression = (def) => isOperatorOf(def[0], indexZeroParsers);
1096
- var isOperatorOf = (element, parsers) => typeof element === "string" && hasOwn3(parsers, element);
1097
- var writeInvalidConstructorMessage = (actual) => `Expected a constructor following 'instanceof' operator (was ${actual})`;
1098
-
1099
- // out/parser/tupleLiteral.js
1100
- import { $ark as $ark2, checkDefault as checkDefault2, makeRootAndArrayPropertiesMutable, postfixAfterOptionalOrDefaultableMessage } from "@ark/schema";
1101
- import { append as append2, isArray as isArray3, isEmptyObject as isEmptyObject3, throwParseError as throwParseError10 } from "@ark/util";
1102
- var parseTupleLiteral = function (def, ctx) {
1103
- let sequences = [{}];
1104
- let i = 0;
1105
- while (i < def.length) {
1106
- let spread = false;
1107
- if (def[i] === "..." && i < def.length - 1) {
1108
- spread = true;
1109
- i++;
1110
- }
1111
- const parsedProperty = parseProperty(def[i], ctx);
1112
- const [valueNode, operator, possibleDefaultValue] = !isArray3(parsedProperty) ? [parsedProperty] : parsedProperty;
1113
- if (typeof def[i] === "string" && typeof possibleDefaultValue === "function")
1114
- checkDefault2(valueNode, possibleDefaultValue(), null);
1115
- i++;
1116
- if (spread) {
1117
- if (!valueNode.extends($ark2.kw.Array))
1118
- return throwParseError10(writeNonArraySpreadMessage(valueNode.expression));
1119
- sequences = sequences.flatMap((base) => (
1120
- // since appendElement mutates base, we have to shallow-ish clone it for each branch
1121
- valueNode.distribute((branch) => appendSpreadBranch(makeRootAndArrayPropertiesMutable(base), branch))
1122
- ));
1123
- } else {
1124
- sequences = sequences.map((base) => {
1125
- if (operator === "?")
1126
- return appendOptionalElement(base, valueNode);
1127
- if (operator === "=")
1128
- return appendDefaultableElement(base, valueNode, possibleDefaultValue);
1129
- return appendRequiredElement(base, valueNode);
1130
- });
1131
- }
1132
- }
1133
- return ctx.$.node("union", {
1134
- branches: sequences.map((sequence) => isEmptyObject3(sequence) ? ctx.$.node("intersection", {
1135
- proto: ctx.$.node("proto", { proto: Array }),
1136
- exactLength: ctx.$.node("exactLength", { rule: 0 })
1137
- }) : ctx.$.node("intersection", {
1138
- proto: ctx.$.node("proto", { proto: Array }),
1139
- structure: ctx.$.node("structure", {
1140
- sequence: ctx.$.node("sequence", sequence)
1141
- })
1142
- }))
1143
- });
1144
- };
1145
- var appendRequiredElement = function (base, element) {
1146
- if (base.defaultables || base.optionals) {
1147
- return throwParseError10(base.variadic ? (
1148
- // e.g. [boolean = true, ...string[], number]
1149
- postfixAfterOptionalOrDefaultableMessage
1150
- ) : requiredPostOptionalMessage);
1151
- }
1152
- if (base.variadic) {
1153
- base.postfix = append2(base.postfix, element);
1154
- } else {
1155
- base.prefix = append2(base.prefix, element);
1156
- }
1157
- return base;
1158
- };
1159
- var appendOptionalElement = function (base, element) {
1160
- if (base.variadic)
1161
- return throwParseError10(optionalOrDefaultableAfterVariadicMessage);
1162
- base.optionals = append2(base.optionals, element);
1163
- return base;
1164
- };
1165
- var appendDefaultableElement = function (base, element, value) {
1166
- if (base.variadic)
1167
- return throwParseError10(optionalOrDefaultableAfterVariadicMessage);
1168
- if (base.optionals)
1169
- return throwParseError10(defaultablePostOptionalMessage);
1170
- base.defaultables = append2(base.defaultables, [[element, value]]);
1171
- return base;
1172
- };
1173
- var appendVariadicElement = function (base, element) {
1174
- if (base.postfix)
1175
- throwParseError10(multipleVariadicMesage);
1176
- if (base.variadic) {
1177
- if (!base.variadic.equals(element)) {
1178
- throwParseError10(multipleVariadicMesage);
1179
- }
1180
- } else {
1181
- base.variadic = element.internal;
1182
- }
1183
- return base;
1184
- };
1185
- var appendSpreadBranch = function (base, branch) {
1186
- const spread = branch.select({ method: "find", kind: "sequence" });
1187
- if (!spread) {
1188
- return appendVariadicElement(base, $ark2.kw.unknown);
1189
- }
1190
- if (spread.prefix)
1191
- for (const node3 of spread.prefix)
1192
- appendRequiredElement(base, node3);
1193
- if (spread.optionals)
1194
- for (const node3 of spread.optionals)
1195
- appendOptionalElement(base, node3);
1196
- if (spread.variadic)
1197
- appendVariadicElement(base, spread.variadic);
1198
- if (spread.postfix)
1199
- for (const node3 of spread.postfix)
1200
- appendRequiredElement(base, node3);
1201
- return base;
1202
- };
1203
- var writeNonArraySpreadMessage = (operand) => `Spread element must be an array (was ${operand})`;
1204
- var multipleVariadicMesage = "A tuple may have at most one variadic element";
1205
- var requiredPostOptionalMessage = "A required element may not follow an optional element";
1206
- var optionalOrDefaultableAfterVariadicMessage = "An optional element may not follow a variadic element";
1207
- var spreadOptionalMessage = "A spread element cannot be optional";
1208
- var spreadDefaultableMessage = "A spread element cannot have a default";
1209
- var defaultablePostOptionalMessage = "A defaultable element may not follow an optional element without a default";
1210
-
1211
- // out/parser/definition.js
1212
- var parseCache = /* @__PURE__ */ new WeakMap();
1213
- var parseInnerDefinition = function (def, ctx) {
1214
- if (typeof def === "string") {
1215
- if (ctx.args && Object.keys(ctx.args).some((k) => def.includes(k))) {
1216
- return parseString(def, ctx);
1217
- }
1218
- let scopeCache = parseCache.get(ctx.$);
1219
- if (!scopeCache) {
1220
- scopeCache = /* @__PURE__ */ Object.create(null);
1221
- parseCache.set(ctx.$, scopeCache);
1222
- }
1223
- if (scopeCache[def]) {
1224
- $ark3.reached?.cached(scopeCache, def);
1225
- return scopeCache[def];
1226
- }
1227
- const mark = $ark3.reached?.mark();
1228
- const result = parseString(def, ctx);
1229
- const node3 = isArray4(result) ? result[0] : result;
1230
- if (!inProgress2.definitions || !node3.hasAlias) {
1231
- scopeCache[def] = result;
1232
- $ark3.reached?.store(mark, scopeCache, def);
1233
- }
1234
- return result;
1235
- }
1236
- return hasDomain(def, "object") ? parseObject(def, ctx) : throwParseError11(writeBadDefinitionTypeMessage(domainOf2(def)));
1237
- };
1238
- var parseObject = function (def, ctx) {
1239
- const objectKind = objectKindOf(def);
1240
- switch (objectKind) {
1241
- case void 0:
1242
- if (hasArkKind3(def, "root")) {
1243
- return isInstanceOf(def, BaseRoot) ? def : parseStandardSchema(def, ctx, true);
1244
- }
1245
- if (isStandardSchema(def))
1246
- return parseStandardSchema(def, ctx);
1247
- return parseObjectLiteral(def, ctx);
1248
- case "Array":
1249
- return parseTuple(def, ctx);
1250
- case "RegExp":
1251
- return ctx.$.node("intersection", {
1252
- domain: ctx.$.node("domain", { domain: "string" }),
1253
- pattern: [
1254
- ctx.$.node("pattern", constraintInputOf("pattern", def))
1255
- ]
1256
- }, { reduced: true });
1257
- case "Function": {
1258
- if (isStandardSchema(def))
1259
- return parseStandardSchema(def, ctx);
1260
- const resolvedDef = isThunk(def) ? resolveThunk(def) : def;
1261
- if (hasArkKind3(resolvedDef, "root"))
1262
- return parseObject(resolvedDef, ctx);
1263
- return throwParseError11(writeBadDefinitionTypeMessage("Function"));
1264
- }
1265
- default:
1266
- return throwParseError11(writeBadDefinitionTypeMessage(objectKind ?? printable3(def)));
1267
- }
1268
- };
1269
- var resolveThunk = function (def) {
1270
- const source = Function.prototype.toString.call(def);
1271
- if (/^class\b/.test(source))
1272
- return def;
1273
- if (!/\[native code]\s*}$/.test(source))
1274
- return def();
1275
- try {
1276
- return def();
1277
- } catch (e) {
1278
- if (e instanceof TypeError)
1279
- return def;
1280
- throw e;
1281
- }
1282
- };
1283
- var parseStandardSchema = function (def, ctx, isForeign) {
1284
- const validate = (v, ctx2) => {
1285
- const result = def["~standard"].validate(v);
1286
- if (result instanceof Promise) {
1287
- return throwError(writeAsyncStandardSchemaMessage(def["~standard"].vendor));
1288
- }
1289
- if (!result.issues)
1290
- return result.value;
1291
- if (result.issues.length === 0)
1292
- return ctx2.error({ expected: "valid", message: "is invalid" });
1293
- const { vendor, _c: isCustomError } = def["~standard"];
1294
- const fromArk = vendor === "arktype";
1295
- for (const issue of result.issues) {
1296
- const relativePath = (issue.path ?? []).map((k) => typeof k === "object" ? k.key : k);
1297
- const { problem, _c, _l, _m } = issue;
1298
- const fromArk2 = isForeign && typeof problem === "string";
1299
- const error = ctx2.error({
1300
- message: fromArk2 ? problem : issue.message,
1301
- relativePath
1302
- });
1303
- if (fromArk2 || fromArk && _c === void 0 && (isCustomError ? !isCustomError(issue) : !isCustomIssue(issue))) {
1304
- asTemplated(
1305
- error,
1306
- // a union listing its branches' errors names their whole paths
1307
- _m ? _m.call(issue, ctx2.path)._l : ctx2.path.length === 0 ? _l : void 0
1308
- );
1309
- }
1310
- }
1311
- };
1312
- if (isForeign)
1313
- foreignTypesByMorph.set(validate, def);
1314
- return ctx.$.intrinsic.unknown.pipe(validate);
1315
- };
1316
- var writeAsyncStandardSchemaMessage = (vendor) => `Standard Schema definitions must validate synchronously (${vendor} returned a Promise)`;
1317
- var parseTuple = (def, ctx) => maybeParseTupleExpression(def, ctx) ?? parseTupleLiteral(def, ctx);
1318
- var writeBadDefinitionTypeMessage = function (actual) { return `Type definitions must be strings or objects (was ${actual})${hasOwn4(badDefinitionHints, actual) ? badDefinitionHints[actual] : ""}` };
1319
- var literalValueHint = ". Write a literal value in a string, or pass it to type.unit()";
1320
- var badDefinitionHints = {
1321
- Function: ". Write a class as type.instanceOf(MyClass) or a keyword like Date, and a predicate as .narrow(fn)",
1322
- number: literalValueHint,
1323
- bigint: literalValueHint,
1324
- boolean: literalValueHint,
1325
- null: literalValueHint,
1326
- undefined: literalValueHint,
1327
- symbol: literalValueHint
1328
- };
1329
-
1330
- // out/type.js
1331
- import { ArkErrors, BaseRoot as BaseRoot3, finalizeExport, GenericRoot as GenericRoot2 } from "@ark/schema";
1332
- import { Callable as Callable2, defineLazily, Hkt } from "@ark/util";
1333
-
1334
- // out/deferred.js
1335
- import { $ark as $ark4, BaseRoot as BaseRoot2, bindPrecompiledUnits, createNode, deferredCallable, inProgress as inProgress3, intrinsic as intrinsic3, isNode, lastCreated, printSelfAsThis } from "@ark/schema";
1336
- import { hasDomain as hasDomain2, isThunk as isThunk2 } from "@ark/util";
1337
- import { domainsOf, unitBitsOf } from "arksets/internal";
1338
- var deferred = /* @__PURE__ */ new WeakMap();
1339
- var stringBits = unitBitsOf("string");
1340
- var objectBits = unitBitsOf("object");
1341
- var numberBits = unitBitsOf("number");
1342
- var undefinedBits = unitBitsOf("undefined");
1343
- var symbolBits = unitBitsOf("symbol");
1344
- var settling = 0;
1345
- var settle = function (self, d) {
1346
- const prior = lastCreated;
1347
- settling++;
1348
- let node3;
1349
- try {
1350
- node3 = d.resolve();
1351
- } finally {
1352
- settling--;
1353
- }
1354
- const created = lastCreated;
1355
- d.resolve = void 0;
1356
- createNode({
1357
- id: node3.id,
1358
- kind: node3.kind,
1359
- inner: node3.inner,
1360
- meta: node3.meta,
1361
- $: node3.$,
1362
- ignoreCache: true,
1363
- shell: d
1364
- });
1365
- const key = node3.c.key;
1366
- self.c.key = key;
1367
- if (Object.getOwnPropertyDescriptor(node3, "expression")?.get)
1368
- printSelfAsThis(self, node3);
1369
- if (key && node3.id === created && created !== prior) {
1370
- node3.$.nodesByKey.set(key, self);
1371
- if ($ark4.nodesById[node3.id] === node3)
1372
- $ark4.nodesById[node3.id] = self;
1373
- }
1374
- return node3.$.fin(self);
1375
- };
1376
- var settled = (self) => {
1377
- const d = deferred.get(self);
1378
- return d?.resolve ? settle(self, d) : self;
1379
- };
1380
- var keywordDomains = {
1381
- string: "string",
1382
- "string.uuid": "string",
1383
- "string.email": "string",
1384
- "string.url": "string",
1385
- "string.date.iso": "string",
1386
- "string.date": "string",
1387
- "string.ip": "string",
1388
- "string.numeric": "string",
1389
- "string.integer": "string",
1390
- "string.digits": "string",
1391
- "string.alpha": "string",
1392
- "string.alphanumeric": "string",
1393
- "string.hex": "string",
1394
- "string.semver": "string",
1395
- number: "number",
1396
- "number.integer": "number",
1397
- "number.safe": "number",
1398
- boolean: "boolean",
1399
- bigint: "bigint",
1400
- symbol: "symbol",
1401
- object: "object",
1402
- null: "null",
1403
- undefined: "undefined",
1404
- true: "boolean",
1405
- false: "boolean"
1406
- };
1407
- var stringLiteral = /^'[^'\\]*'$/;
1408
- var numberLiteral = /^-?(?:0|[1-9]\d*)(?:\.\d*[1-9])?$/;
1409
- var branded = /^([.a-z]+)#\w[\w!]*$/;
1410
- var range = /^(?:(0|-?[1-9]\d*) (<=?) )?(\S.*) ([<>]=?) (0|-?[1-9]\d*)$/;
1411
- var defaulted = /^(.+) = ('[^'\\]*'|0|-?[1-9]\d*|true|false)$/;
1412
- var regexLiteral = /^\/(?:[^\n/\\]|\\.)+\/$/;
1413
- var record = /^Record<string, (.+)>$/;
1414
- var fits = function (value, facts) {
1415
- if (facts.values)
1416
- return facts.values.includes(value);
1417
- if (typeof value === "string") {
1418
- return facts.base === "string" && value.length >= (facts.min ?? 0) && value.length <= (facts.max ?? Infinity);
1419
- }
1420
- return typeof value === "number" && (facts.base === "number" || facts.base === "integer" && Number.isInteger(value)) && value >= (facts.min ?? -Infinity) && value <= (facts.max ?? Infinity);
1421
- };
1422
- var rangeFacts = function (d, min, max) {
1423
- if (!min && (d.base === "string" || d.base === "array"))
1424
- min = void 0;
1425
- return {
1426
- key: `${d.of}${min === void 0 ? "" : `>=${min}`}${max === void 0 ? "" : `<=${max}`}`,
1427
- domains: d.base === "string" ? stringBits : d.base === "array" ? objectBits : numberBits,
1428
- pure: d.pure,
1429
- cyclic: d.cyclic,
1430
- base: d.base,
1431
- of: d.of,
1432
- min,
1433
- max
1434
- };
1435
- };
1436
- var scanRange = function (def) {
1437
- const m = range.exec(def);
1438
- if (!m)
1439
- return;
1440
- const [, left, leftOp, word, op, right] = m;
1441
- const of = word === "string" || word === "number" || word === "number.integer" ? scanTerm(word) : word.endsWith("[]") ? scanTerm(word) : void 0;
1442
- if (!of?.pure || !of.base)
1443
- return;
1444
- const isLength = of.base === "string" || of.base === "array";
1445
- const step = of.base === "number" ? 0 : 1;
1446
- let min;
1447
- let max;
1448
- if (op[0] === "<")
1449
- max = +right - (op === "<" ? step : 0);
1450
- else
1451
- min = +right + (op === ">" ? step : 0);
1452
- if (left) {
1453
- if (op[0] !== "<")
1454
- return;
1455
- min = +left + (leftOp === "<" ? step : 0);
1456
- }
1457
- if ((min ?? 0) > (max ?? Infinity))
1458
- return;
1459
- if (min === max && (op.length === 1 || leftOp === "<"))
1460
- return;
1461
- if (isLength && ((max ?? 0) < 0 || (min ?? 0) < 0))
1462
- return;
1463
- if (isLength || op.length === 2 && (!left || leftOp === "<="))
1464
- return rangeFacts({ pure: true, base: of.base, of: of.of }, min, max);
1465
- return {
1466
- key: def,
1467
- domains: numberBits,
1468
- pure: true,
1469
- base: of.base,
1470
- min,
1471
- max
1472
- };
1473
- };
1474
- var splitTop = function (def, separator) {
1475
- const parts = [];
1476
- let depth = 0;
1477
- let quoted = false;
1478
- let start = 0;
1479
- for (let i = 0; i < def.length; i++) {
1480
- const c = def[i];
1481
- if (c === "'")
1482
- quoted = !quoted;
1483
- else if (quoted)
1484
- continue;
1485
- else if (c === "/" || c === "\\" || c === '"')
1486
- return [def];
1487
- else if (c === "(")
1488
- depth++;
1489
- else if (c === ")")
1490
- depth--;
1491
- else if (!depth && def.startsWith(separator, i)) {
1492
- parts.push(def.slice(start, i));
1493
- i += separator.length - 1;
1494
- start = i + 1;
1495
- }
1496
- }
1497
- parts.push(def.slice(start));
1498
- return parts;
1499
- };
1500
- var wrap = (f) => f.terms ? `(${f.key})` : f.key;
1501
- var arrayFacts = function (element) {
1502
- const of = `${wrap(element)}[]`;
1503
- return {
1504
- key: of,
1505
- domains: objectBits,
1506
- pure: element.pure,
1507
- cyclic: element.cyclic,
1508
- base: "array",
1509
- of
1510
- };
1511
- };
1512
- var scanTerm = function (def) {
1513
- if (stringLiteral.test(def)) {
1514
- return {
1515
- key: def,
1516
- domains: stringBits,
1517
- pure: true,
1518
- units: true,
1519
- values: [def.slice(1, -1)]
1520
- };
1521
- }
1522
- const brand = branded.exec(def);
1523
- if (brand)
1524
- return keywordDomains[brand[1]] && scanTerm(brand[1]);
1525
- if (numberLiteral.test(def) && `${+def}` === def) {
1526
- return {
1527
- key: def,
1528
- domains: numberBits,
1529
- pure: true,
1530
- units: true,
1531
- values: [+def]
1532
- };
1533
- }
1534
- if (def[0] === "(" && def[def.length - 1] === ")")
1535
- return scanUnion(def.slice(1, -1));
1536
- if (def.endsWith("[]")) {
1537
- const element = scanTerm(def.slice(0, -2));
1538
- return element?.pure ? arrayFacts(element) : void 0;
1539
- }
1540
- const bounded = scanRange(def);
1541
- if (bounded)
1542
- return bounded;
1543
- const domain = keywordDomains[def];
1544
- if (!domain)
1545
- return;
1546
- const base = def === "string" ? "string" : def === "number" ? "number" : def === "number.integer" ? "integer" : void 0;
1547
- const values = def === "true" ? [true] : def === "false" ? [false] : def === "null" ? [null] : def === "undefined" ? [void 0] : def === "boolean" ? [true, false] : void 0;
1548
- return {
1549
- key: def,
1550
- domains: unitBitsOf(domain),
1551
- pure: true,
1552
- base,
1553
- of: base && def,
1554
- values,
1555
- units: !!values
1556
- };
1557
- };
1558
- var insert = function (sorted, term) {
1559
- let i = sorted.length;
1560
- while (i && sorted[i - 1] > term)
1561
- i--;
1562
- if (sorted[i - 1] === term)
1563
- return false;
1564
- sorted.splice(i, 0, term);
1565
- return true;
1566
- };
1567
- var insertAll = (terms, f) => f.terms ? f.terms.every((t) => insert(terms, t)) : insert(terms, f.key);
1568
- var scanUnion = function (def) {
1569
- const parts = splitTop(def, " | ");
1570
- if (parts.length === 1)
1571
- return scanTerm(def);
1572
- let domains = 0;
1573
- let open = 0;
1574
- let values = [];
1575
- let units;
1576
- const terms = [];
1577
- for (let i = 0; i < parts.length; i++) {
1578
- const term = scanTerm(parts[i]);
1579
- if (!term || term.domains & (term.values ? open : domains))
1580
- return;
1581
- domains |= term.domains;
1582
- if (!term.values)
1583
- open |= term.domains;
1584
- values = term.values && values?.concat(term.values);
1585
- units ||= term.units;
1586
- if (!insertAll(terms, term))
1587
- return;
1588
- }
1589
- return { key: terms.join("|"), terms, domains, pure: true, values, units };
1590
- };
1591
- var refinesString = (f) => !!f && f.pure && f.domains === stringBits && !f.values && !f.defaults;
1592
- var andFacts = function (l, r) {
1593
- if ((l.min !== void 0 || l.max !== void 0) && (r.min !== void 0 || r.max !== void 0))
1594
- return;
1595
- return {
1596
- key: l.key < r.key ? `${l.key}&${r.key}` : `${r.key}&${l.key}`,
1597
- domains: stringBits,
1598
- pure: true,
1599
- min: l.min ?? r.min,
1600
- max: l.max ?? r.max
1601
- };
1602
- };
1603
- var scanAnd = function (def) {
1604
- const at = def.indexOf(" & ");
1605
- if (at === -1)
1606
- return scanUnion(def);
1607
- const l = scanTerm(def.slice(0, at));
1608
- const right = def.slice(at + 3);
1609
- const r = regexLiteral.test(right) ? regexFacts(new RegExp(right.slice(1, -1))) : scanTerm(right);
1610
- return refinesString(l) && refinesString(r) ? andFacts(l, r) : void 0;
1611
- };
1612
- var regexFacts = (v) => ({
1613
- key: String(v),
1614
- domains: stringBits,
1615
- pure: true
1616
- });
1617
- var scanned = /* @__PURE__ */ new Map();
1618
- var scanLeaf = function (def) {
1619
- let facts = scanned.get(def);
1620
- if (facts === void 0) {
1621
- try {
1622
- facts = scanUncached(def) ?? null;
1623
- } catch {
1624
- facts = null;
1625
- }
1626
- scanned.set(def, facts);
1627
- }
1628
- return facts ?? void 0;
1629
- };
1630
- var scanUncached = function (def) {
1631
- const withDefault = defaulted.exec(def);
1632
- if (withDefault) {
1633
- const base = scanUnion(withDefault[1]);
1634
- const raw = withDefault[2];
1635
- const value = raw[0] === "'" ? raw.slice(1, -1) : raw === "true" ? true : raw === "false" ? false : +raw;
1636
- if (!base || !fits(value, base))
1637
- return;
1638
- return {
1639
- key: defaultKey(base, value),
1640
- domains: base.domains,
1641
- pure: false,
1642
- defaults: true
1643
- };
1644
- }
1645
- if (def === "string.trim")
1646
- return { key: def, domains: stringBits, pure: false };
1647
- if (def.startsWith("string.trim |> ")) {
1648
- const to = scanAnd(def.slice(15));
1649
- return to?.domains === stringBits && !to.values ? { key: `string.trim|>${to.key}`, domains: stringBits, pure: false } : void 0;
1650
- }
1651
- if (regexLiteral.test(def))
1652
- return regexFacts(new RegExp(def.slice(1, -1)));
1653
- const record$ = record.exec(def);
1654
- if (record$) {
1655
- const value = scanUnion(record$[1]);
1656
- return value ? { key: `Record<${value.key}>`, domains: objectBits, pure: true } : void 0;
1657
- }
1658
- return scanAnd(def);
1659
- };
1660
- var isPlainObject = (v) => {
1661
- const proto2 = Object.getPrototypeOf(v);
1662
- return proto2 === Object.prototype || proto2 === null;
1663
- };
1664
- var fnIds = /* @__PURE__ */ new WeakMap();
1665
- var fnCount = 0;
1666
- var fnKey = (fn) => {
1667
- let id = fnIds.get(fn);
1668
- if (!id)
1669
- fnIds.set(fn, id = ++fnCount);
1670
- return `#${id}`;
1671
- };
1672
- var defaultKey = (of, value) => `${wrap(of)}=${typeof value === "function" ? fnKey(value) : `${typeof value}:${String(value)}`}`;
1673
- var nodeFacts = function (node3) {
1674
- if (node3.isNever() || node3.topAlias)
1675
- return;
1676
- const key = `@${node3.id}`;
1677
- const domains = domainsOf(node3);
1678
- if (node3.hasAlias)
1679
- return { key, domains, pure: false, cyclic: true };
1680
- let values = [];
1681
- let units = false;
1682
- for (const branch of node3.branches) {
1683
- if (branch.is("unit")) {
1684
- units = true;
1685
- if (typeof branch.unit !== "object")
1686
- values?.push(branch.unit);
1687
- else
1688
- values = void 0;
1689
- } else
1690
- values = void 0;
1691
- }
1692
- return { key, domains, pure: !node3.alters, values, units };
1693
- };
1694
- var thisFacts = function (v) { return v === "this" || v === "this[]" ? {
1695
- key: `${v}#${++fnCount}`,
1696
- domains: objectBits,
1697
- pure: false,
1698
- cyclic: "this"
1699
- } : void 0 };
1700
- var valueFacts = function (v, into) {
1701
- if (typeof v === "string") {
1702
- const facts = scanLeaf(v);
1703
- return facts && [facts, v];
1704
- }
1705
- if (Array.isArray(v)) {
1706
- const element = v.length === 2 && v[1] === "[]" && valueFacts(v[0], into);
1707
- return element && !element[0].defaults ? [arrayFacts(element[0]), [element[1], "[]"]] : void 0;
1708
- }
1709
- if (v instanceof RegExp)
1710
- return [regexFacts(v), v];
1711
- if (typeof v !== "object" && typeof v !== "function")
1712
- return;
1713
- if (!v)
1714
- return;
1715
- const d = deferred.get(v);
1716
- if (d)
1717
- return [d.facts, v];
1718
- if (isNode(v)) {
1719
- const of = v.isRoot() && nodeFacts(v);
1720
- return of ? [of, v] : void 0;
1721
- }
1722
- if (typeof v === "function" || !isPlainObject(v))
1723
- return;
1724
- const nested = { key: "", domains: objectBits, pure: true };
1725
- const held = walkLiteral(v, nested, into);
1726
- return held && [{ key: nested.key, domains: objectBits, pure: into.pure }, held];
1727
- };
1728
- var walkLiteral = function (def, facts, outer) {
1729
- if (Object.getOwnPropertySymbols(def).length)
1730
- return;
1731
- const keys = Object.keys(def);
1732
- if (!keys.length)
1733
- return;
1734
- const copy = {};
1735
- const names = [];
1736
- const entries = [];
1737
- const props = [];
1738
- let closed = true;
1739
- let spreadThis;
1740
- let spreadOf;
1741
- let spreadNode;
1742
- for (let i = 0; i < keys.length; i++) {
1743
- const k = keys[i];
1744
- if (k === "__proto__")
1745
- return;
1746
- const v = def[k];
1747
- const key = preparseKey(k);
1748
- if (key.kind === "undeclared") {
1749
- if (v !== "reject" && v !== "delete" && v !== "ignore")
1750
- return;
1751
- if (v !== "ignore")
1752
- facts.pure = false;
1753
- closed = false;
1754
- entries.unshift(`+${v}`);
1755
- copy[k] = v;
1756
- continue;
1757
- }
1758
- if (key.kind === "spread") {
1759
- if (i)
1760
- return;
1761
- const d = deferred.get(v);
1762
- if (d ? !d.facts.literal : !isNode(v) || !v.is("intersection") || !v.structure || v.structure.index || v.structure.sequence || !v.basis?.is("domain") || v.basis.domain !== "object" || v.hasAlias)
1763
- return;
1764
- if (d ? !d.facts.pure : v.alters)
1765
- facts.pure = false;
1766
- if (d?.facts.cyclic) {
1767
- facts.cyclic = d.facts.cyclic;
1768
- spreadThis = d.facts.key;
1769
- }
1770
- closed = false;
1771
- if (d)
1772
- spreadOf = d.facts;
1773
- else
1774
- spreadNode = v;
1775
- entries.push(d ? "" : `...@${spreadNode.structure.id}`);
1776
- copy[k] = v;
1777
- continue;
1778
- }
1779
- if (key.kind !== "required" && key.kind !== "optional")
1780
- return;
1781
- const name = key.normalized;
1782
- if (names.includes(name))
1783
- return;
1784
- if (spreadThis?.includes(`${name.length}${name}`))
1785
- return;
1786
- if (spreadNode?.structure.byKey[name])
1787
- return;
1788
- names.push(name);
1789
- const isTuple = Array.isArray(v) && v[1] !== "[]";
1790
- if (isTuple && key.kind === "optional")
1791
- return;
1792
- if (isTuple && !(v[1] === "=" ? v.length === 3 : v[1] === "?" && v.length === 2))
1793
- return;
1794
- const held = isTuple ? v[0] : v;
1795
- const self = thisFacts(held);
1796
- const value = self ? [self, held] : valueFacts(held, facts);
1797
- if (!value)
1798
- return;
1799
- const [of, kept] = value;
1800
- if (of.defaults && (isTuple || key.kind === "optional"))
1801
- return;
1802
- if (isTuple && v[1] === "=") {
1803
- if (!isThunk2(v[2]) && (hasDomain2(v[2], "object") || !fits(v[2], of)))
1804
- return;
1805
- facts.pure = false;
1806
- }
1807
- if (!of.pure)
1808
- facts.pure = false;
1809
- if (of.cyclic && facts.cyclic !== true)
1810
- facts.cyclic = of.cyclic;
1811
- const optional = isTuple || of.defaults || key.kind === "optional";
1812
- if (optional && !of.pure && (of.domains & undefinedBits || of.cyclic === true))
1813
- return;
1814
- if (!optional && of.values)
1815
- (facts.tags ??= /* @__PURE__ */ new Map()).set(name, of.values);
1816
- const entry = `${name.length}${name}${isTuple && v[1] === "=" ? `:${defaultKey(of, v[2])}` : optional && !of.defaults ? `?${of.key}` : `:${of.key}`}`;
1817
- entries.push(entry);
1818
- props.push([name, entry]);
1819
- copy[k] = isTuple ? [kept, ...v.slice(1)] : kept;
1820
- }
1821
- if (outer && !facts.pure)
1822
- outer.pure = false;
1823
- if (outer && facts.cyclic && outer.cyclic !== true)
1824
- outer.cyclic = facts.cyclic;
1825
- if (closed) {
1826
- facts.names = names;
1827
- facts.entries = entries;
1828
- }
1829
- facts.props = props;
1830
- if (spreadOf) {
1831
- const spread = spreadOf.props.map(([name, entry]) => names.includes(name) ? `${name.length}${name}~` : entry);
1832
- if (spreadOf.spread)
1833
- spread.unshift(spreadOf.spread);
1834
- facts.spread = entries[entries.indexOf("")] = `...{${spread.join()}}`;
1835
- }
1836
- facts.key = `{${entries.join()}}`;
1837
- return copy;
1838
- };
1839
- var disjointByTag = function (l, r) {
1840
- if (l.tags && r.tags) {
1841
- for (const [k, values] of l.tags) {
1842
- const other = r.tags.get(k);
1843
- if (other && !values.some((v) => other.includes(v)))
1844
- return true;
1845
- }
1846
- }
1847
- return false;
1848
- };
1849
- var determinate = function (l, r) { return !(l.domains & r.domains) || l.pure && r.pure && !(l.narrowed && r.units) && !(r.narrowed && l.units) || disjointByTag(l, r) };
1850
- var deferUnion = function (branches, $) {
1851
- if (branches.length < 2 || !canDefer($))
1852
- return;
1853
- const all = [];
1854
- const defs = [];
1855
- const terms = [];
1856
- try {
1857
- for (let i = 0; i < branches.length; i++) {
1858
- const branch = branches[i];
1859
- const shell = hasDomain2(branch, "object") && !deferred.has(branch) && !isNode(branch) ? deferDefinition(branch, $) : branch;
1860
- if (!shell)
1861
- return;
1862
- const value = valueFacts(shell, { key: "", domains: 0, pure: true });
1863
- if (!value || value[0].defaults || value[0].cyclic === true)
1864
- return;
1865
- all.push(value[0]);
1866
- defs.push(value[1]);
1867
- if (!insertAll(terms, value[0]))
1868
- return;
1869
- }
1870
- } catch {
1871
- return;
1872
- }
1873
- let domains = 0;
1874
- let pure = true;
1875
- let values = [];
1876
- let units;
1877
- let narrowed;
1878
- let cyclic;
1879
- for (let i = 0; i < all.length; i++) {
1880
- const f = all[i];
1881
- for (let j = i + 1; j < all.length; j++)
1882
- if (!determinate(f, all[j]))
1883
- return;
1884
- domains |= f.domains;
1885
- pure &&= f.pure;
1886
- values = f.values && values?.concat(f.values);
1887
- units ||= f.units;
1888
- narrowed ||= f.narrowed;
1889
- cyclic ||= f.cyclic;
1890
- }
1891
- let tags;
1892
- if (all[0].tags) {
1893
- for (const [k, of] of all[0].tags) {
1894
- let union = of;
1895
- for (let i = 1; union && i < all.length; i++) {
1896
- const other = all[i].tags?.get(k);
1897
- union = other && union.concat(other);
1898
- }
1899
- if (union)
1900
- (tags ??= /* @__PURE__ */ new Map()).set(k, union);
1901
- }
1902
- }
1903
- return defer({
1904
- key: terms.join("|"),
1905
- terms,
1906
- domains,
1907
- pure,
1908
- tags,
1909
- values,
1910
- units,
1911
- narrowed,
1912
- cyclic
1913
- }, $, () => $.or(...defs));
1914
- };
1915
- var boundMethod = function (bases, isMin) { return (d, [n]) => {
1916
- const { bounds, of, min, max, pure, cyclic } = d.facts;
1917
- const over = of ? d.facts.base : bounds;
1918
- if (cyclic === true || !over || !pure && (!of || over !== "array") || !bases.includes(over) || typeof n !== "number" || !(over === "number" ? Number.isFinite(n) : Number.isSafeInteger(n) && n >= 0))
1919
- return;
1920
- const lo = isMin && !(min > n) ? n : min;
1921
- const hi = !isMin && !(max < n) ? n : max;
1922
- if ((lo ?? -Infinity) > (hi ?? Infinity))
1923
- return;
1924
- return of ? rangeFacts(d.facts, lo, hi) : {
1925
- ...d.facts,
1926
- key: `${wrap(d.facts)}${isMin ? ">=" : "<="}${n}`,
1927
- terms: void 0,
1928
- min: lo,
1929
- max: hi
1930
- };
1931
- } };
1932
- var metaFacts = function (d, meta) { return ({
1933
- ...d.facts,
1934
- key: `${wrap(d.facts)}@${JSON.stringify(meta)}`,
1935
- terms: void 0,
1936
- of: void 0,
1937
- names: void 0,
1938
- literal: false
1939
- }) };
1940
- var isPlainMeta = function (meta) {
1941
- if (!hasDomain2(meta, "object") || !isPlainObject(meta))
1942
- return false;
1943
- for (const k in meta) {
1944
- if (!"description expected title".includes(k) || typeof meta[k] !== "string")
1945
- return false;
1946
- }
1947
- return true;
1948
- };
1949
- var deferredMethods = {
1950
- array: (d) => arrayFacts(d.facts),
1951
- narrow: function ({ facts }, [predicate]) { return typeof predicate === "function" && !isNode(predicate) && !facts.units ? {
1952
- key: `${wrap(facts)}:${fnKey(predicate)}`,
1953
- domains: facts.domains,
1954
- pure: facts.pure,
1955
- cyclic: facts.cyclic,
1956
- tags: facts.tags,
1957
- min: facts.min,
1958
- max: facts.max,
1959
- bounds: facts.of ? facts.base : facts.bounds,
1960
- narrowed: true
1961
- } : void 0 },
1962
- _pipe: function ({ facts }, morphs) { return morphs.length && morphs.every((morph) => typeof morph === "function" && !isNode(morph)) ? {
1963
- key: `${wrap(facts)}|>${morphs.map(fnKey).join()}`,
1964
- domains: facts.domains,
1965
- pure: false
1966
- } : void 0 },
1967
- and: function (d, args) {
1968
- const { facts } = d;
1969
- const [r] = args;
1970
- const string = r instanceof RegExp ? regexFacts(r) : typeof r === "string" ? scanLeaf(r) : void 0;
1971
- if (string) {
1972
- return refinesString(facts) && refinesString(string) ? andFacts(facts, string) : void 0;
1973
- }
1974
- if (!facts.names)
1975
- return;
1976
- const shell = deferred.has(r) ? r : hasDomain2(r, "object") && !isNode(r) ? deferDefinition(r, d.$) : void 0;
1977
- const rf = shell && deferred.get(shell)?.facts;
1978
- if (!rf?.names)
1979
- return;
1980
- for (let i = 0; i < rf.names.length; i++)
1981
- if (facts.names.includes(rf.names[i]))
1982
- return;
1983
- args[0] = shell;
1984
- const entries = [...facts.entries, ...rf.entries];
1985
- return {
1986
- key: `{${entries.join()}}`,
1987
- domains: objectBits,
1988
- pure: facts.pure && rf.pure,
1989
- cyclic: facts.cyclic || rf.cyclic,
1990
- names: [...facts.names, ...rf.names],
1991
- entries,
1992
- tags: new Map([...facts.tags ?? [], ...rf.tags ?? []])
1993
- };
1994
- },
1995
- describe: (d, [description, selector]) => typeof description === "string" && !selector ? metaFacts(d, { description }) : void 0,
1996
- configure: (d, [meta, selector]) => isPlainMeta(meta) && !selector ? metaFacts(d, meta) : void 0,
1997
- to: function ({ facts }, [r]) {
1998
- const to = typeof r === "string" ? scanAnd(r) : r instanceof RegExp ? regexFacts(r) : deferred.get(r)?.facts;
1999
- return facts.key === "string.trim" && refinesString(to) ? { key: `string.trim>${to.key}`, domains: stringBits, pure: false } : void 0;
2000
- },
2001
- onUndeclaredKey: function ({ facts }, [rule]) { return facts.domains === objectBits && facts.cyclic !== true && (rule === "reject" || rule === "ignore") ? {
2002
- ...facts,
2003
- key: `${facts.key}+${rule}`,
2004
- pure: rule === "ignore" && facts.pure,
2005
- names: void 0,
2006
- entries: void 0
2007
- } : void 0 },
2008
- exclude: function ({ facts }, [r]) {
2009
- const excluded = typeof r === "string" ? scanLeaf(r) : void 0;
2010
- if (!facts.terms || !facts.values || !excluded?.values)
2011
- return;
2012
- const remaining = facts.values.filter((v) => !excluded.values.includes(v));
2013
- const excludedTerms = excluded.terms ?? [excluded.key];
2014
- const kept = facts.terms.filter((t) => !excludedTerms.includes(t));
2015
- if (!kept.length || kept.length !== remaining.length)
2016
- return;
2017
- return {
2018
- key: kept.join("|"),
2019
- terms: kept.length > 1 ? kept : void 0,
2020
- domains: facts.domains,
2021
- pure: true,
2022
- values: remaining,
2023
- units: true
2024
- };
2025
- },
2026
- atLeastLength: boundMethod("string array", true),
2027
- atMostLength: boundMethod("string array", false),
2028
- atLeast: boundMethod("number integer", true),
2029
- atMost: boundMethod("number integer", false)
2030
- };
2031
- var deferredForms = {
2032
- default: (self, d, [value]) => isThunk2(value) || !hasDomain2(value, "object") && fits(value, d.facts) ? [self, "=", value] : void 0,
2033
- optional: (self) => [self, "?"],
2034
- or: (self, d, [r]) => deferUnion([self, r], d.$)
2035
- };
2036
- var composes = "narrow _pipe and or";
2037
- var builders = {};
2038
- var built = (self, method, args) => builders[method].apply(settled(self), args);
2039
- var proto = BaseRoot2.prototype;
2040
- for (const k of [
2041
- ...Object.keys(deferredMethods),
2042
- ...Object.keys(deferredForms)
2043
- ]) {
2044
- builders[k] = proto[k];
2045
- proto[k] = function(...args) {
2046
- const d = deferred.get(this);
2047
- const blocked = d?.facts.cyclic === true ? composes.includes(k) : d?.facts.cyclic ? k === "_pipe" || k === "narrow" : false;
2048
- if (d && !blocked && canDefer(d.$)) {
2049
- if (deferredForms[k]) {
2050
- const form = deferredForms[k](this, d, args);
2051
- if (form)
2052
- return form;
2053
- } else {
2054
- const facts = deferredMethods[k](d, args);
2055
- if (facts)
2056
- return defer(facts, d.$, () => built(this, k, args));
2057
- }
2058
- }
2059
- return built(this, k, args);
2060
- };
2061
- }
2062
- var shellProto = new Proxy(Object.create(proto), {
2063
- get: function (target, k, receiver) {
2064
- if (!deferred.get(receiver)?.resolve)
2065
- return Reflect.get(target, k, receiver);
2066
- if (k === "pipe") {
2067
- return Object.assign((...morphs) => proto._pipe.apply(receiver, morphs), {
2068
- try: (...morphs) => settled(receiver).pipe.try(...morphs)
2069
- });
2070
- }
2071
- if (typeof k === "string" && (deferredMethods[k] || deferredForms[k]))
2072
- return target[k];
2073
- settled(receiver);
2074
- return receiver[k];
2075
- },
2076
- set: (_, k, v, receiver) => {
2077
- settled(receiver);
2078
- return Reflect.set(receiver, k, v);
2079
- },
2080
- // a read of an own key, which it can't ask of a Type it isn't told of
2081
- has: (target, k) => k in target || k in intrinsic3.object
2082
- });
2083
- var defer = function (facts, $, resolve) {
2084
- const existing = $.nodesByKey.get(facts.key);
2085
- if (existing)
2086
- return existing;
2087
- const { fn, c } = deferredCallable();
2088
- const self = fn;
2089
- Object.setPrototypeOf(self, shellProto);
2090
- deferred.set(self, { facts, fn, c, $, resolve });
2091
- $.nodesByKey.set(facts.key, self);
2092
- return self;
2093
- };
2094
- var canDefer = function ($) {
2095
- if (!$.isBuiltin || $.name !== "ark" || $ark4.reached || $ark4.eagerTypes || settling || bindPrecompiledUnits || inProgress3.definitions || inProgress3.resolutions)
2096
- return false;
2097
- for (const k in $ark4.config)
2098
- if (k !== "exactOptionalPropertyTypes" && k !== "jitless")
2099
- return false;
2100
- void $.cfg;
2101
- return true;
2102
- };
2103
- var literalOf = function (value) { return typeof value === "string" ? `'${value}'` : typeof value === "number" || value === null || typeof value === "boolean" ? `${value}` : value === void 0 ? "undefined" : "?" };
2104
- var deferUnits = function (values, $) {
2105
- const literals = values.map(literalOf);
2106
- return literals.length === 1 ? deferDefinition(literals[0], $) : deferUnion(literals, $);
2107
- };
2108
- var deferredRecord = function ($, generic) {
2109
- const instantiate = (...args) => {
2110
- const [k, v] = args;
2111
- const into = { key: "", domains: 0, pure: true };
2112
- const key = canDefer($) && valueFacts(k, into)?.[0];
2113
- const value = key && (typeof v === "string" ? scanUnion(v) : valueFacts(v, into)?.[0]);
2114
- return !value || !key || !key.pure || key.units || key.domains & ~(stringBits | symbolBits) || value.defaults || value.cyclic ? generic()(...args) : defer({
2115
- key: `Record<${key.key === "string" ? "" : `${key.key},`}${value.key}>`,
2116
- domains: objectBits,
2117
- pure: value.pure
2118
- }, $, () => generic()(k, v));
2119
- };
2120
- return Object.setPrototypeOf(instantiate, new Proxy({}, {
2121
- get: (_, k) => generic()[k],
2122
- has: (_, k) => k in generic(),
2123
- getPrototypeOf: () => Object.getPrototypeOf(generic())
2124
- }));
2125
- };
2126
- var deferDefinition = function (def, $) {
2127
- if (!canDefer($))
2128
- return;
2129
- if (deferred.has(def))
2130
- return def;
2131
- if (typeof def === "string") {
2132
- const facts2 = scanLeaf(def);
2133
- return !facts2 || facts2.defaults ? void 0 : lastCreated ? $.nodesByKey.get(facts2.key) : defer(facts2, $, () => $.parseDef(def));
2134
- }
2135
- if (def instanceof RegExp)
2136
- return defer(regexFacts(def), $, () => $.parseDef(def));
2137
- if (typeof def !== "object" || !def || !isPlainObject(def))
2138
- return;
2139
- const facts = {
2140
- key: "",
2141
- domains: objectBits,
2142
- pure: true,
2143
- literal: true
2144
- };
2145
- let literal;
2146
- try {
2147
- literal = walkLiteral(def, facts);
2148
- } catch {
2149
- return;
2150
- }
2151
- if (!literal)
2152
- return;
2153
- const copy = literal;
2154
- return defer(facts, $, () => $.parseDef(copy));
2155
- };
2156
-
2157
- // out/type.js
2158
- var InternalTypeParser = class extends Callable2 {
2159
- constructor($) {
2160
- const attach = {
2161
- errors: ArkErrors,
2162
- hkt: Hkt,
2163
- $,
2164
- raw: $.parse,
2165
- module: $.constructor.module,
2166
- scope: $.constructor.scope,
2167
- declare: $.declare,
2168
- define: $.define,
2169
- match: $.match,
2170
- generic: $.generic,
2171
- schema: $.schema,
2172
- // this won't be defined during bootstrapping, but externally always will be
2173
- keywords: $.ambient,
2174
- unit: ((value) => deferUnits([value], $) ?? $.unit(value)),
2175
- enumerated: ((...values) => deferUnits(values, $) ?? $.enumerated(...values)),
2176
- instanceOf: $.instanceOf,
2177
- valueOf: $.valueOf,
2178
- or: ((...branches) => deferUnion(branches, $) ?? $.or(...branches)),
2179
- and: $.and,
2180
- merge: $.merge,
2181
- pipe: $.pipe,
2182
- fn: $.fn
2183
- };
2184
- super((...args) => {
2185
- if (args.length === 1) {
2186
- return deferDefinition(args[0], $) ?? $.parse(args[0]);
2187
- }
2188
- if (args.length === 2 && typeof args[0] === "string" && args[0][0] === "<" && args[0][args[0].length - 1] === ">") {
2189
- const paramString = args[0].slice(1, -1);
2190
- const params = $.parseGenericParams(paramString, {});
2191
- return new GenericRoot2(params, args[1], $, $, null);
2192
- }
2193
- return $.parse(args);
2194
- }, { attach });
2195
- const typeAttachments = $arkTypeRegistry.typeAttachments;
2196
- const resolve = (k) => {
2197
- const bound = $.bindKw(typeAttachments[k]);
2198
- return $.resolved ? finalizeExport($, bound) : bound;
2199
- };
2200
- for (const k in typeAttachments)
2201
- defineLazily(this, k, resolve);
2202
- }
2203
- };
2204
- var Type = BaseRoot3;
2205
-
2206
- // out/scope.js
2207
- $ark5.sets ??= setEngine;
2208
- var $arkTypeRegistry = $ark5;
2209
- var InternalScope = class InternalScope extends BaseScope {
2210
- get ambientAttachments() {
2211
- if (!$arkTypeRegistry.typeAttachments)
2212
- return;
2213
- return this.memo("ambientAttachments", flatMorph(Object.keys($arkTypeRegistry.typeAttachments), (_, k) => [
2214
- k,
2215
- this.type[k]
2216
- ]));
2217
- }
2218
- keywordConfigOf(qualifiedName) {
2219
- const { keywords } = this.cfg;
2220
- return hasOwn5(keywords, qualifiedName) ? keywords[qualifiedName] : void 0;
2221
- }
2222
- preparseEntry(alias, def) {
2223
- const firstParamIndex = alias.indexOf("<");
2224
- if (firstParamIndex === -1) {
2225
- if (hasArkKind4(def, "module") || hasArkKind4(def, "generic"))
2226
- return [alias, def];
2227
- const qualifiedName = this.name === "ark" ? alias : alias === "root" ? this.name : `${this.name}.${alias}`;
2228
- const configured = (def2) => {
2229
- const config = this.keywordConfigOf(qualifiedName);
2230
- return config ? [def2, "@", config] : def2;
2231
- };
2232
- if (!isThunk3(def))
2233
- return [alias, configured(def)];
2234
- return [
2235
- alias,
2236
- () => {
2237
- const resolution = def();
2238
- if (hasArkKind4(resolution, "generic"))
2239
- return resolution;
2240
- return configured(resolution);
2241
- }
2242
- ];
2243
- }
2244
- if (alias[alias.length - 1] !== ">") {
2245
- throwParseError12(`'>' must be the last character of a generic declaration in a scope`);
2246
- }
2247
- const name = alias.slice(0, firstParamIndex);
2248
- if (hasArkKind4(def, "generic"))
2249
- throwParseError12(writeParameterizedGenericKeyMessage(name));
2250
- const paramString = alias.slice(firstParamIndex + 1, -1);
2251
- const genericName = name[0] === "#" ? name.slice(1) : name;
2252
- return [
2253
- name,
2254
- // use a thunk definition for the generic so that we can parse
2255
- // constraints within the current scope
2256
- new LazyGenericRoot(() => parseGeneric(this.parseGenericParams(paramString, { alias: genericName }), def, this, genericName), { attach: { paramsDef: paramString, bodyDef: def } })
2257
- ];
2258
- }
2259
- parseGenericParams(def, opts) {
2260
- return parseGenericParamName(new Scanner2(def), [], this.createParseCtx({
2261
- ...opts,
2262
- def,
2263
- prefix: "generic"
2264
- }));
2265
- }
2266
- normValue(resolution) {
2267
- if (isThunk3(resolution) && !hasArkKind4(resolution, "generic"))
2268
- return resolution();
2269
- return resolution;
2270
- }
2271
- preparseOwn(def, opts) {
2272
- return {
2273
- ...opts,
2274
- def,
2275
- prefix: opts.alias ?? "type"
2276
- };
2277
- }
2278
- parseOwn(def, ctx) {
2279
- const isScopeAlias = ctx.alias && ctx.alias in this.aliases;
2280
- if (!isScopeAlias && !ctx.args)
2281
- ctx.args = { this: ctx.id };
2282
- const result = parseInnerDefinition(def, ctx);
2283
- if (isArray5(result)) {
2284
- if (result[1] === "=")
2285
- return throwParseError12(shallowDefaultableMessage);
2286
- if (result[1] === "?")
2287
- return throwParseError12(shallowOptionalMessage);
2288
- }
2289
- return result;
2290
- }
2291
- unit = (value) => this.units([value]);
2292
- valueOf = (tsEnum) => this.units(enumValues(tsEnum));
2293
- enumerated = (...values) => this.units(values);
2294
- instanceOf = (ctor) => this.node("proto", { proto: ctor }, { reduced: true });
2295
- or = (...defs) => this.fin(this.node("union", {
2296
- branches: defs.map((def) => this.parse(def))
2297
- }));
2298
- and = (...defs) => defs.reduce((node3, def) => node3.and(this.parse(def)), this.intrinsic.unknown);
2299
- merge = (...defs) => defs.reduce((node3, def) => node3.merge(this.parse(def)), this.intrinsic.object);
2300
- pipe = (...morphs) => this.intrinsic.unknown.pipe(...morphs);
2301
- fn = new InternalFnParser(this);
2302
- match = new InternalMatchParser(this);
2303
- declare = () => ({
2304
- type: this.type
2305
- });
2306
- define(def) {
2307
- return def;
2308
- }
2309
- type = new InternalTypeParser(this);
2310
- static scope = ((def, config = {}) => new InternalScope(def, config));
2311
- static module = ((def, config = {}) => InternalScope.scope(def, config).export());
2312
- };
2313
- var keywordModule = function (def, config) {
2314
- const module = new RootModule({});
2315
- let exports;
2316
- const resolve = (name) => (exports ??= new InternalScope(def, config, true).exportLazily())[name];
2317
- for (const name in def)
2318
- if (name[0] !== "#")
2319
- defineLazily2(module, name, resolve, isFinalResolution);
2320
- return module;
2321
- };
2322
- var writeParameterizedGenericKeyMessage = (name) => `${name} is defined by a generic, so its key must not declare parameters`;
2323
- var scope = Object.assign(InternalScope.scope, {
2324
- define: (def) => def
2325
- });
2326
- var Scope = InternalScope;
2327
-
2328
- // out/keywords/ts.js
2329
- var tsKeywordDefinitions = {
2330
- bigint: () => intrinsic4.bigint,
2331
- boolean: () => intrinsic4.boolean,
2332
- false: () => intrinsic4.false,
2333
- never: () => intrinsic4.never,
2334
- null: () => intrinsic4.null,
2335
- number: () => intrinsic4.number,
2336
- object: () => intrinsic4.object,
2337
- string: () => intrinsic4.string,
2338
- symbol: () => intrinsic4.symbol,
2339
- true: () => intrinsic4.true,
2340
- unknown: () => intrinsic4.unknown,
2341
- undefined: () => intrinsic4.undefined
2342
- };
2343
- var arkTsKeywords = /* @__PURE__ */ keywordModule(tsKeywordDefinitions, { name: "ts" });
2344
- var unknown = keywordModule({
2345
- root: () => intrinsic4.unknown,
2346
- any: () => intrinsic4.unknown
2347
- }, {
2348
- name: "unknown"
2349
- });
2350
- var json = keywordModule({
2351
- root: () => intrinsic4.jsonObject,
2352
- stringify: () => node2("morph", {
2353
- morphs: [intrinsic4.jsonObject, stringifyJson],
2354
- declaredOut: intrinsic4.string
2355
- })
2356
- }, {
2357
- name: "object.json"
2358
- });
2359
- var object = keywordModule({
2360
- root: () => intrinsic4.object,
2361
- json
2362
- }, {
2363
- name: "object"
2364
- });
2365
- var RecordHkt = class extends Hkt2 {
2366
- description = 'instantiate an object from an index signature and corresponding value type like `Record("string", "number")`';
2367
- };
2368
- var Record = cached2(function () { return genericNode(["K", intrinsic4.key], "V")((args) => ({
2369
- domain: "object",
2370
- index: {
2371
- signature: args.K,
2372
- value: args.V
2373
- }
2374
- }), RecordHkt) });
2375
- var PickHkt = class extends Hkt2 {
2376
- description = 'pick a set of properties from an object like `Pick(User, "name | age")`';
2377
- };
2378
- var Pick = cached2(() => genericNode(["T", intrinsic4.object], ["K", intrinsic4.key])((args) => args.T.pick(args.K), PickHkt));
2379
- var OmitHkt = class extends Hkt2 {
2380
- description = 'omit a set of properties from an object like `Omit(User, "age")`';
2381
- };
2382
- var Omit = cached2(() => genericNode(["T", intrinsic4.object], ["K", intrinsic4.key])((args) => args.T.omit(args.K), OmitHkt));
2383
- var PartialHkt = class extends Hkt2 {
2384
- description = "make all named properties of an object optional like `Partial(User)`";
2385
- };
2386
- var Partial = cached2(() => genericNode(["T", intrinsic4.object])((args) => args.T.partial(), PartialHkt));
2387
- var RequiredHkt = class extends Hkt2 {
2388
- description = "make all named properties of an object required like `Required(User)`";
2389
- };
2390
- var Required = cached2(() => genericNode(["T", intrinsic4.object])((args) => args.T.required(), RequiredHkt));
2391
- var ExcludeHkt = class extends Hkt2 {
2392
- description = 'exclude branches of a union like `Exclude("boolean", "true")`';
2393
- };
2394
- var filterBranches = function (operator, t, u) { return !isResolvable(t) || !isResolvable(u) ? throwParseError13(writeUnresolvedFilterMessage(operator)) : operator === "Exclude" ? t.exclude(u) : t.extract(u) };
2395
- var Exclude = cached2(() => genericNode("T", "U")((args) => filterBranches("Exclude", args.T, args.U), ExcludeHkt));
2396
- var ExtractHkt = class extends Hkt2 {
2397
- description = 'extract branches of a union like `Extract("0 | false | 1", "number")`';
2398
- };
2399
- var Extract = cached2(() => genericNode("T", "U")((args) => filterBranches("Extract", args.T, args.U), ExtractHkt));
2400
- var tsGenericDefinitions = {
2401
- Exclude,
2402
- Extract,
2403
- Omit,
2404
- Partial,
2405
- Pick,
2406
- Record,
2407
- Required
2408
- };
2409
- var arkTsGenerics = /* @__PURE__ */ keywordModule(tsGenericDefinitions, {
2410
- name: "ts.generics"
2411
- });
2412
- var writeUnresolvedFilterMessage = (operator) => `${operator} can't filter a type still being defined`;
2413
-
2414
- export {
2415
- parseEnclosed,
2416
- enclosingQuote,
2417
- enclosingChar,
2418
- enclosingLiteralTokens,
2419
- enclosingRegexTokens,
2420
- enclosingTokens,
2421
- untilLookaheadIsClosing,
2422
- writeUnterminatedEnclosedMessage,
2423
- writePrefixedPrivateReferenceMessage,
2424
- shallowOptionalMessage,
2425
- shallowDefaultableMessage,
2426
- writeDoubleRightBoundMessage,
2427
- minComparators,
2428
- maxComparators,
2429
- comparators,
2430
- invertedComparators,
2431
- checkWrittenIntersection,
2432
- writeOpenRangeMessage,
2433
- writeUnpairableComparatorMessage,
2434
- writeMultipleLeftBoundsMessage,
2435
- isDateLiteral,
2436
- extractDateLiteralSource,
2437
- terminatingChars,
2438
- shiftUntilTerminator,
2439
- finalizingLookaheads,
2440
- lookaheadIsFinalizing,
2441
- parseBrand,
2442
- parseDivisor,
2443
- writeInvalidDivisorMessage,
2444
- parseOperator,
2445
- writeUnexpectedCharacterMessage,
2446
- incompleteArrayTokenMessage,
2447
- parseBound,
2448
- comparatorStartChars,
2449
- shiftComparator,
2450
- writeIncompatibleRangeMessage,
2451
- getBoundKinds,
2452
- parseRightBound,
2453
- arrayIsNotGenericHint,
2454
- writeInvalidLimitMessage,
2455
- parseGenericArgs,
2456
- writeInvalidGenericArgCountMessage,
2457
- foreignAliases,
2458
- writeUnresolvableHint,
2459
- parseUnenclosed,
2460
- limitOf,
2461
- parseGenericInstantiation,
2462
- writeMissingOperandMessage,
2463
- writeMissingRightOperandMessage,
2464
- writeExpressionExpectedMessage,
2465
- parseOperand,
2466
- parseDefault,
2467
- writeNonLiteralDefaultMessage,
2468
- parseString,
2469
- fullStringParse,
2470
- parseUntilFinalizer,
2471
- RuntimeState,
2472
- Generic,
2473
- emptyGenericParameterMessage,
2474
- parseGenericParamName,
2475
- InternalMatchParser,
2476
- InternalChainedMatchParser,
2477
- chainedAtMessage,
2478
- doubleAtMessage,
2479
- parseProperty,
2480
- invalidOptionalKeyKindMessage,
2481
- invalidDefaultableKeyKindMessage,
2482
- parseObjectLiteral,
2483
- writeInvalidUndeclaredBehaviorMessage,
2484
- writeOptionalIndexKeyMessage,
2485
- nonLeadingSpreadError,
2486
- preparseKey,
2487
- writeInvalidSpreadTypeMessage,
2488
- maybeParseTupleExpression,
2489
- parseKeyOfTuple,
2490
- parseMorphTuple,
2491
- writeMalformedFunctionalExpressionMessage,
2492
- parseNarrowTuple,
2493
- writeInvalidConstructorMessage,
2494
- parseTupleLiteral,
2495
- writeNonArraySpreadMessage,
2496
- multipleVariadicMesage,
2497
- requiredPostOptionalMessage,
2498
- optionalOrDefaultableAfterVariadicMessage,
2499
- spreadOptionalMessage,
2500
- spreadDefaultableMessage,
2501
- defaultablePostOptionalMessage,
2502
- parseInnerDefinition,
2503
- parseObject,
2504
- writeAsyncStandardSchemaMessage,
2505
- parseTuple,
2506
- writeBadDefinitionTypeMessage,
2507
- keywordDomains,
2508
- deferUnion,
2509
- deferUnits,
2510
- deferredRecord,
2511
- deferDefinition,
2512
- InternalTypeParser,
2513
- Type,
2514
- $arkTypeRegistry,
2515
- InternalScope,
2516
- keywordModule,
2517
- writeParameterizedGenericKeyMessage,
2518
- scope,
2519
- Scope,
2520
- tsKeywordDefinitions,
2521
- arkTsKeywords,
2522
- unknown,
2523
- json,
2524
- object,
2525
- RecordHkt,
2526
- tsGenericDefinitions,
2527
- arkTsGenerics,
2528
- writeUnresolvedFilterMessage
2529
- };