@mojir/dvala 0.0.7 → 0.0.9

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 (316) hide show
  1. package/dist/cli/cli.js +1553 -1599
  2. package/dist/cli/reference/examples.d.ts +1 -1
  3. package/dist/cli/src/AutoCompleter/AutoCompleter.d.ts +4 -2
  4. package/dist/cli/src/{Dvala/Cache.d.ts → Cache.d.ts} +1 -1
  5. package/dist/cli/src/builtin/specialExpressions/functions.d.ts +1 -1
  6. package/dist/cli/src/createDvala.d.ts +47 -0
  7. package/dist/cli/src/evaluator/ContextStack.d.ts +10 -2
  8. package/dist/cli/src/evaluator/effectTypes.d.ts +5 -5
  9. package/dist/cli/src/evaluator/trampoline.d.ts +10 -1
  10. package/dist/cli/src/parser/subParsers/parseDo.d.ts +1 -1
  11. package/dist/cli/src/tokenizer/token.d.ts +2 -4
  12. package/dist/cli/src/tokenizer/tokenize.d.ts +1 -2
  13. package/dist/cli/src/tokenizer/tokenizers.d.ts +2 -3
  14. package/dist/cli/src/tooling.d.ts +51 -0
  15. package/dist/debug.esm.js +1 -1
  16. package/dist/debug.esm.js.map +1 -1
  17. package/dist/debug.js +1 -1
  18. package/dist/debug.js.map +1 -1
  19. package/dist/dvala.iife.js +1 -1
  20. package/dist/dvala.iife.js.map +1 -1
  21. package/dist/full.esm.js +1 -1
  22. package/dist/full.esm.js.map +1 -1
  23. package/dist/full.js +1 -1
  24. package/dist/full.js.map +1 -1
  25. package/dist/index.esm.js +1 -1
  26. package/dist/index.esm.js.map +1 -1
  27. package/dist/index.js +1 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/mcp-server/common/utils.d.ts +2 -0
  30. package/dist/mcp-server/mcp-server/src/server.d.ts +1 -0
  31. package/dist/mcp-server/reference/api.d.ts +73 -0
  32. package/dist/mcp-server/reference/datatype.d.ts +3 -0
  33. package/dist/mcp-server/reference/examples.d.ts +11 -0
  34. package/dist/mcp-server/reference/index.d.ts +195 -0
  35. package/dist/mcp-server/reference/shorthand.d.ts +3 -0
  36. package/dist/mcp-server/server.js +36330 -0
  37. package/dist/mcp-server/src/AutoCompleter/AutoCompleter.d.ts +27 -0
  38. package/dist/{src/Dvala → mcp-server/src}/Cache.d.ts +1 -1
  39. package/dist/mcp-server/src/allModules.d.ts +2 -0
  40. package/dist/mcp-server/src/builtin/bindingNode.d.ts +11 -0
  41. package/dist/mcp-server/src/builtin/core/array.d.ts +2 -0
  42. package/dist/mcp-server/src/builtin/core/assertion.d.ts +2 -0
  43. package/dist/mcp-server/src/builtin/core/bitwise.d.ts +2 -0
  44. package/dist/mcp-server/src/builtin/core/collection.d.ts +2 -0
  45. package/dist/mcp-server/src/builtin/core/functional.d.ts +2 -0
  46. package/dist/mcp-server/src/builtin/core/math.d.ts +2 -0
  47. package/dist/mcp-server/src/builtin/core/meta.d.ts +3 -0
  48. package/dist/mcp-server/src/builtin/core/misc.d.ts +2 -0
  49. package/dist/mcp-server/src/builtin/core/object.d.ts +2 -0
  50. package/dist/mcp-server/src/builtin/core/predicates.d.ts +2 -0
  51. package/dist/mcp-server/src/builtin/core/regexp.d.ts +2 -0
  52. package/dist/mcp-server/src/builtin/core/sequence.d.ts +2 -0
  53. package/dist/mcp-server/src/builtin/core/string.d.ts +2 -0
  54. package/dist/mcp-server/src/builtin/core/vector.d.ts +2 -0
  55. package/dist/mcp-server/src/builtin/index.d.ts +13 -0
  56. package/dist/mcp-server/src/builtin/interface.d.ts +113 -0
  57. package/dist/mcp-server/src/builtin/modules/assertion/docs.d.ts +2 -0
  58. package/dist/mcp-server/src/builtin/modules/assertion/index.d.ts +2 -0
  59. package/dist/mcp-server/src/builtin/modules/bitwise/index.d.ts +2 -0
  60. package/dist/mcp-server/src/builtin/modules/collection/index.d.ts +2 -0
  61. package/dist/mcp-server/src/builtin/modules/convert/index.d.ts +2 -0
  62. package/dist/mcp-server/src/builtin/modules/functional/index.d.ts +2 -0
  63. package/dist/mcp-server/src/builtin/modules/grid/docs.d.ts +2 -0
  64. package/dist/mcp-server/src/builtin/modules/grid/fromArray.d.ts +8 -0
  65. package/dist/mcp-server/src/builtin/modules/grid/index.d.ts +2 -0
  66. package/dist/mcp-server/src/builtin/modules/grid/transpose.d.ts +2 -0
  67. package/dist/mcp-server/src/builtin/modules/interface.d.ts +28 -0
  68. package/dist/mcp-server/src/builtin/modules/linear-algebra/docs.d.ts +2 -0
  69. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/calcFractionalRanks.d.ts +1 -0
  70. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/collinear.d.ts +2 -0
  71. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/corrleation.d.ts +8 -0
  72. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/covariance.d.ts +4 -0
  73. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/dot.d.ts +1 -0
  74. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/gaussJordanElimination.d.ts +7 -0
  75. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/getUnit.d.ts +2 -0
  76. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/isZeroVector.d.ts +1 -0
  77. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/kendallTau.d.ts +10 -0
  78. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/length.d.ts +1 -0
  79. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/pearsonCorr.d.ts +1 -0
  80. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/scale.d.ts +1 -0
  81. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/solve.d.ts +8 -0
  82. package/dist/mcp-server/src/builtin/modules/linear-algebra/helpers/subtract.d.ts +1 -0
  83. package/dist/mcp-server/src/builtin/modules/linear-algebra/index.d.ts +4 -0
  84. package/dist/mcp-server/src/builtin/modules/math/index.d.ts +2 -0
  85. package/dist/mcp-server/src/builtin/modules/matrix/docs.d.ts +2 -0
  86. package/dist/mcp-server/src/builtin/modules/matrix/helpers/adjugate.d.ts +1 -0
  87. package/dist/mcp-server/src/builtin/modules/matrix/helpers/band.d.ts +9 -0
  88. package/dist/mcp-server/src/builtin/modules/matrix/helpers/cofactor.d.ts +1 -0
  89. package/dist/mcp-server/src/builtin/modules/matrix/helpers/determinant.d.ts +6 -0
  90. package/dist/mcp-server/src/builtin/modules/matrix/helpers/inverse.d.ts +6 -0
  91. package/dist/mcp-server/src/builtin/modules/matrix/helpers/isBanded.d.ts +11 -0
  92. package/dist/mcp-server/src/builtin/modules/matrix/helpers/isDiagonal.d.ts +10 -0
  93. package/dist/mcp-server/src/builtin/modules/matrix/helpers/isIdentity.d.ts +1 -0
  94. package/dist/mcp-server/src/builtin/modules/matrix/helpers/isOrthogonal.d.ts +1 -0
  95. package/dist/mcp-server/src/builtin/modules/matrix/helpers/isSquare.d.ts +1 -0
  96. package/dist/mcp-server/src/builtin/modules/matrix/helpers/isSymetric.d.ts +8 -0
  97. package/dist/mcp-server/src/builtin/modules/matrix/helpers/isTriangular.d.ts +13 -0
  98. package/dist/mcp-server/src/builtin/modules/matrix/helpers/matrixMultiply.d.ts +7 -0
  99. package/dist/mcp-server/src/builtin/modules/matrix/helpers/minor.d.ts +1 -0
  100. package/dist/mcp-server/src/builtin/modules/matrix/helpers/norm1.d.ts +1 -0
  101. package/dist/mcp-server/src/builtin/modules/matrix/helpers/trace.d.ts +8 -0
  102. package/dist/mcp-server/src/builtin/modules/matrix/index.d.ts +4 -0
  103. package/dist/mcp-server/src/builtin/modules/number-theory/binomialCefficient.d.ts +1 -0
  104. package/dist/mcp-server/src/builtin/modules/number-theory/combinations.d.ts +2 -0
  105. package/dist/mcp-server/src/builtin/modules/number-theory/derangements.d.ts +2 -0
  106. package/dist/mcp-server/src/builtin/modules/number-theory/divisors.d.ts +4 -0
  107. package/dist/mcp-server/src/builtin/modules/number-theory/docs.d.ts +2 -0
  108. package/dist/mcp-server/src/builtin/modules/number-theory/factorial.d.ts +3 -0
  109. package/dist/mcp-server/src/builtin/modules/number-theory/index.d.ts +4 -0
  110. package/dist/mcp-server/src/builtin/modules/number-theory/partitions.d.ts +2 -0
  111. package/dist/mcp-server/src/builtin/modules/number-theory/permutations.d.ts +2 -0
  112. package/dist/mcp-server/src/builtin/modules/number-theory/powerSet.d.ts +2 -0
  113. package/dist/mcp-server/src/builtin/modules/number-theory/primeFactors.d.ts +11 -0
  114. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/abundant.d.ts +2 -0
  115. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/arithmetic.d.ts +2 -0
  116. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/bell.d.ts +1 -0
  117. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/bernoulli.d.ts +2 -0
  118. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/catalan.d.ts +1 -0
  119. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/collatz.d.ts +2 -0
  120. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/composite.d.ts +3 -0
  121. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/deficient.d.ts +2 -0
  122. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/factorial.d.ts +1 -0
  123. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/fibonacci.d.ts +1 -0
  124. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/geometric.d.ts +2 -0
  125. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/golomb.d.ts +2 -0
  126. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/happy.d.ts +2 -0
  127. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/index.d.ts +27 -0
  128. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/juggler.d.ts +2 -0
  129. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/lookAndSay.d.ts +2 -0
  130. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/lucas.d.ts +1 -0
  131. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/lucky.d.ts +2 -0
  132. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/mersenne.d.ts +1 -0
  133. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/padovan.d.ts +2 -0
  134. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/partition.d.ts +1 -0
  135. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/pell.d.ts +1 -0
  136. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/perfect.d.ts +1 -0
  137. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/perfectCube.d.ts +2 -0
  138. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/perfectPower.d.ts +10 -0
  139. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/perfectSquare.d.ts +2 -0
  140. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/poligonal.d.ts +2 -0
  141. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/prime.d.ts +3 -0
  142. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/recaman.d.ts +9 -0
  143. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/sylvester.d.ts +1 -0
  144. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/thueMorse.d.ts +2 -0
  145. package/dist/mcp-server/src/builtin/modules/number-theory/sequences/tribonacci.d.ts +1 -0
  146. package/dist/mcp-server/src/builtin/modules/sequence/index.d.ts +2 -0
  147. package/dist/mcp-server/src/builtin/modules/string/index.d.ts +2 -0
  148. package/dist/mcp-server/src/builtin/modules/vector/bincount.d.ts +9 -0
  149. package/dist/mcp-server/src/builtin/modules/vector/calcMad.d.ts +1 -0
  150. package/dist/mcp-server/src/builtin/modules/vector/calcMean.d.ts +1 -0
  151. package/dist/mcp-server/src/builtin/modules/vector/calcMedad.d.ts +1 -0
  152. package/dist/mcp-server/src/builtin/modules/vector/calcMedian.d.ts +1 -0
  153. package/dist/mcp-server/src/builtin/modules/vector/calcStdDev.d.ts +2 -0
  154. package/dist/mcp-server/src/builtin/modules/vector/calcVariance.d.ts +2 -0
  155. package/dist/mcp-server/src/builtin/modules/vector/docs.d.ts +2 -0
  156. package/dist/mcp-server/src/builtin/modules/vector/entropy.d.ts +8 -0
  157. package/dist/mcp-server/src/builtin/modules/vector/histogram.d.ts +9 -0
  158. package/dist/mcp-server/src/builtin/modules/vector/index.d.ts +2 -0
  159. package/dist/mcp-server/src/builtin/modules/vector/mode.d.ts +6 -0
  160. package/dist/mcp-server/src/builtin/modules/vector/outliers.d.ts +7 -0
  161. package/dist/mcp-server/src/builtin/modules/vector/percentile.d.ts +7 -0
  162. package/dist/mcp-server/src/builtin/modules/vector/quartiles.d.ts +1 -0
  163. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/entropy.d.ts +2 -0
  164. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/giniCoefficient.d.ts +2 -0
  165. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/index.d.ts +13 -0
  166. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/iqr.d.ts +2 -0
  167. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/kurtosis.d.ts +5 -0
  168. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/mad.d.ts +2 -0
  169. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/mean.d.ts +4 -0
  170. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/medad.d.ts +2 -0
  171. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/median.d.ts +2 -0
  172. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/prod.d.ts +2 -0
  173. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/rms.d.ts +2 -0
  174. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/skewness.d.ts +3 -0
  175. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/span.d.ts +2 -0
  176. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/standardDeviation.d.ts +3 -0
  177. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/sum.d.ts +2 -0
  178. package/dist/mcp-server/src/builtin/modules/vector/reductionFunctions/variance.d.ts +3 -0
  179. package/dist/mcp-server/src/builtin/normalExpressions/index.d.ts +9 -0
  180. package/dist/mcp-server/src/builtin/normalExpressions/initCoreDvala.d.ts +1 -0
  181. package/dist/mcp-server/src/builtin/specialExpressionTypes.d.ts +24 -0
  182. package/dist/mcp-server/src/builtin/specialExpressions/and.d.ts +6 -0
  183. package/dist/mcp-server/src/builtin/specialExpressions/array.d.ts +6 -0
  184. package/dist/mcp-server/src/builtin/specialExpressions/block.d.ts +7 -0
  185. package/dist/mcp-server/src/builtin/specialExpressions/cond.d.ts +6 -0
  186. package/dist/mcp-server/src/builtin/specialExpressions/defined.d.ts +5 -0
  187. package/dist/mcp-server/src/builtin/specialExpressions/effect.d.ts +5 -0
  188. package/dist/mcp-server/src/builtin/specialExpressions/functions.d.ts +6 -0
  189. package/dist/mcp-server/src/builtin/specialExpressions/if.d.ts +6 -0
  190. package/dist/mcp-server/src/builtin/specialExpressions/import.d.ts +6 -0
  191. package/dist/mcp-server/src/builtin/specialExpressions/let.d.ts +6 -0
  192. package/dist/mcp-server/src/builtin/specialExpressions/loop.d.ts +6 -0
  193. package/dist/mcp-server/src/builtin/specialExpressions/loops.d.ts +9 -0
  194. package/dist/mcp-server/src/builtin/specialExpressions/match.d.ts +7 -0
  195. package/dist/mcp-server/src/builtin/specialExpressions/object.d.ts +6 -0
  196. package/dist/mcp-server/src/builtin/specialExpressions/or.d.ts +6 -0
  197. package/dist/mcp-server/src/builtin/specialExpressions/parallel.d.ts +6 -0
  198. package/dist/mcp-server/src/builtin/specialExpressions/perform.d.ts +6 -0
  199. package/dist/mcp-server/src/builtin/specialExpressions/qq.d.ts +6 -0
  200. package/dist/mcp-server/src/builtin/specialExpressions/race.d.ts +6 -0
  201. package/dist/mcp-server/src/builtin/specialExpressions/recur.d.ts +5 -0
  202. package/dist/mcp-server/src/builtin/specialExpressions/unless.d.ts +6 -0
  203. package/dist/mcp-server/src/builtin/utils.d.ts +6 -0
  204. package/dist/mcp-server/src/bundler/interface.d.ts +15 -0
  205. package/dist/mcp-server/src/constants/constants.d.ts +19 -0
  206. package/dist/mcp-server/src/createDvala.d.ts +47 -0
  207. package/dist/mcp-server/src/errors.d.ts +24 -0
  208. package/dist/mcp-server/src/evaluator/ContextStack.d.ts +70 -0
  209. package/dist/mcp-server/src/evaluator/contentHash.d.ts +21 -0
  210. package/dist/mcp-server/src/evaluator/dedupSubTrees.d.ts +37 -0
  211. package/dist/mcp-server/src/evaluator/effectRef.d.ts +27 -0
  212. package/dist/mcp-server/src/evaluator/effectTypes.d.ts +181 -0
  213. package/dist/mcp-server/src/evaluator/frames.d.ts +513 -0
  214. package/dist/mcp-server/src/evaluator/interface.d.ts +14 -0
  215. package/dist/mcp-server/src/evaluator/standardEffects.d.ts +50 -0
  216. package/dist/mcp-server/src/evaluator/step.d.ts +175 -0
  217. package/dist/mcp-server/src/evaluator/suspension.d.ts +86 -0
  218. package/dist/mcp-server/src/evaluator/trampoline.d.ts +133 -0
  219. package/dist/mcp-server/src/getUndefinedSymbols/index.d.ts +7 -0
  220. package/dist/mcp-server/src/initReferenceData.d.ts +1 -0
  221. package/dist/mcp-server/src/interface.d.ts +7 -0
  222. package/dist/mcp-server/src/parser/ParserContext.d.ts +20 -0
  223. package/dist/mcp-server/src/parser/getPrecedence.d.ts +3 -0
  224. package/dist/mcp-server/src/parser/helpers.d.ts +19 -0
  225. package/dist/mcp-server/src/parser/index.d.ts +5 -0
  226. package/dist/mcp-server/src/parser/subParsers/parseArray.d.ts +3 -0
  227. package/dist/mcp-server/src/parser/subParsers/parseBindingTarget.d.ts +8 -0
  228. package/dist/mcp-server/src/parser/subParsers/parseCond.d.ts +4 -0
  229. package/dist/mcp-server/src/parser/subParsers/parseDo.d.ts +3 -0
  230. package/dist/mcp-server/src/parser/subParsers/parseExpression.d.ts +5 -0
  231. package/dist/mcp-server/src/parser/subParsers/parseForOrDoseq.d.ts +4 -0
  232. package/dist/mcp-server/src/parser/subParsers/parseFunction.d.ts +4 -0
  233. package/dist/mcp-server/src/parser/subParsers/parseFunctionCall.d.ts +3 -0
  234. package/dist/mcp-server/src/parser/subParsers/parseIfOrUnless.d.ts +5 -0
  235. package/dist/mcp-server/src/parser/subParsers/parseImplicitBlock.d.ts +5 -0
  236. package/dist/mcp-server/src/parser/subParsers/parseLet.d.ts +4 -0
  237. package/dist/mcp-server/src/parser/subParsers/parseLoop.d.ts +4 -0
  238. package/dist/mcp-server/src/parser/subParsers/parseMatch.d.ts +4 -0
  239. package/dist/mcp-server/src/parser/subParsers/parseNumber.d.ts +3 -0
  240. package/dist/mcp-server/src/parser/subParsers/parseObject.d.ts +3 -0
  241. package/dist/mcp-server/src/parser/subParsers/parseOperand.d.ts +3 -0
  242. package/dist/mcp-server/src/parser/subParsers/parseRegexpShorthand.d.ts +3 -0
  243. package/dist/mcp-server/src/parser/subParsers/parseReservedSymbol.d.ts +3 -0
  244. package/dist/mcp-server/src/parser/subParsers/parseString.d.ts +4 -0
  245. package/dist/mcp-server/src/parser/subParsers/parseSymbol.d.ts +3 -0
  246. package/dist/mcp-server/src/parser/types.d.ts +128 -0
  247. package/dist/mcp-server/src/tokenizer/minifyTokenStream.d.ts +4 -0
  248. package/dist/mcp-server/src/tokenizer/operators.d.ts +12 -0
  249. package/dist/mcp-server/src/tokenizer/reservedNames.d.ts +65 -0
  250. package/dist/mcp-server/src/tokenizer/token.d.ts +82 -0
  251. package/dist/mcp-server/src/tokenizer/tokenize.d.ts +7 -0
  252. package/dist/mcp-server/src/tokenizer/tokenizers.d.ts +13 -0
  253. package/dist/mcp-server/src/tooling.d.ts +51 -0
  254. package/dist/mcp-server/src/transformer/index.d.ts +2 -0
  255. package/dist/mcp-server/src/typeGuards/annotatedCollections.d.ts +16 -0
  256. package/dist/mcp-server/src/typeGuards/array.d.ts +9 -0
  257. package/dist/mcp-server/src/typeGuards/astNode.d.ts +19 -0
  258. package/dist/mcp-server/src/typeGuards/dvala.d.ts +26 -0
  259. package/dist/mcp-server/src/typeGuards/dvalaFunction.d.ts +9 -0
  260. package/dist/mcp-server/src/typeGuards/index.d.ts +7 -0
  261. package/dist/mcp-server/src/typeGuards/number.d.ts +66 -0
  262. package/dist/mcp-server/src/typeGuards/string.d.ts +15 -0
  263. package/dist/mcp-server/src/untokenizer/index.d.ts +2 -0
  264. package/dist/mcp-server/src/utils/arity.d.ts +10 -0
  265. package/dist/mcp-server/src/utils/debug/debugTools.d.ts +1 -0
  266. package/dist/mcp-server/src/utils/debug/getCodeMarker.d.ts +2 -0
  267. package/dist/mcp-server/src/utils/debug/getSourceCodeInfo.d.ts +2 -0
  268. package/dist/mcp-server/src/utils/docString/generateDocString.d.ts +4 -0
  269. package/dist/mcp-server/src/utils/getAssertionError.d.ts +3 -0
  270. package/dist/mcp-server/src/utils/index.d.ts +14 -0
  271. package/dist/mcp-server/src/utils/maybePromise.d.ts +54 -0
  272. package/dist/mcp-server/src/utils/symbols.d.ts +3 -0
  273. package/dist/modules/grid.esm.js +1 -1
  274. package/dist/modules/grid.esm.js.map +1 -1
  275. package/dist/modules/grid.js +1 -1
  276. package/dist/modules/grid.js.map +1 -1
  277. package/dist/modules/reference/index.d.ts +136 -136
  278. package/dist/modules/src/AutoCompleter/AutoCompleter.d.ts +4 -2
  279. package/dist/modules/src/{Dvala/Cache.d.ts → Cache.d.ts} +1 -1
  280. package/dist/modules/src/builtin/specialExpressions/functions.d.ts +1 -1
  281. package/dist/modules/src/createDvala.d.ts +47 -0
  282. package/dist/modules/src/evaluator/ContextStack.d.ts +10 -2
  283. package/dist/modules/src/evaluator/effectTypes.d.ts +5 -5
  284. package/dist/modules/src/evaluator/trampoline.d.ts +10 -1
  285. package/dist/modules/src/index.d.ts +8 -5
  286. package/dist/modules/src/parser/subParsers/parseDo.d.ts +1 -1
  287. package/dist/modules/src/resume.d.ts +41 -0
  288. package/dist/modules/src/tokenizer/token.d.ts +2 -4
  289. package/dist/modules/src/tokenizer/tokenize.d.ts +1 -2
  290. package/dist/modules/src/tokenizer/tokenizers.d.ts +2 -3
  291. package/dist/modules/src/tooling.d.ts +51 -0
  292. package/dist/reference/index.d.ts +136 -136
  293. package/dist/src/AutoCompleter/AutoCompleter.d.ts +4 -2
  294. package/dist/src/Cache.d.ts +16 -0
  295. package/dist/src/builtin/specialExpressions/functions.d.ts +1 -1
  296. package/dist/src/createDvala.d.ts +47 -0
  297. package/dist/src/evaluator/ContextStack.d.ts +10 -2
  298. package/dist/src/evaluator/effectTypes.d.ts +5 -5
  299. package/dist/src/evaluator/trampoline.d.ts +10 -1
  300. package/dist/src/index.d.ts +8 -5
  301. package/dist/src/parser/subParsers/parseDo.d.ts +1 -1
  302. package/dist/src/resume.d.ts +41 -0
  303. package/dist/src/tokenizer/token.d.ts +2 -4
  304. package/dist/src/tokenizer/tokenize.d.ts +1 -2
  305. package/dist/src/tokenizer/tokenizers.d.ts +2 -3
  306. package/dist/src/tooling.d.ts +51 -0
  307. package/dist/testFramework.esm.js +1 -1
  308. package/dist/testFramework.esm.js.map +1 -1
  309. package/dist/testFramework.js +1 -1
  310. package/dist/testFramework.js.map +1 -1
  311. package/package.json +17 -6
  312. package/dist/cli/src/Dvala/Dvala.d.ts +0 -63
  313. package/dist/modules/src/Dvala/Dvala.d.ts +0 -63
  314. package/dist/modules/src/effects.d.ts +0 -110
  315. package/dist/src/Dvala/Dvala.d.ts +0 -63
  316. package/dist/src/effects.d.ts +0 -110
package/dist/debug.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- function e(e){if(!e.position||!e.code)return"";const t=e.position.column-1,n=e.code.length-t-1;return`${" ".repeat(Math.max(t,0))}^${" ".repeat(Math.max(n,0))}`}class t extends Error{params;constructor(e){super(`recur, params: ${e}`),Object.setPrototypeOf(this,t.prototype),this.name="RecurSignal",this.params=e}}class n extends Error{sourceCodeInfo;shortMessage;constructor(t,r){const a=t instanceof Error?t.message:`${t}`;super(function(t,n){if(!n)return t;const r=`${n.position.line}:${n.position.column}`;return`${t}${n.filePath?`\n${n.filePath}:${r}`:`\nLocation ${r}`}\n${n.code}\n${e(n)}`}(a,r)),this.shortMessage=a,this.sourceCodeInfo=r,Object.setPrototypeOf(this,n.prototype),this.name="DvalaError"}getCodeMarker(){return this.sourceCodeInfo&&e(this.sourceCodeInfo)}}class r extends n{userMessage;constructor(e,t){super(e,t),this.userMessage=e,Object.setPrototypeOf(this,r.prototype),this.name="UserDefinedError"}}class a extends n{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype),this.name="AssertionError"}}class s extends n{symbol;constructor(e,t){super(`Undefined symbol '${e}'.`,t),this.symbol=e,Object.setPrototypeOf(this,s.prototype),this.name="UndefinedSymbolError"}}const o={Number:1,String:2,NormalExpression:3,SpecialExpression:4,UserDefinedSymbol:5,NormalBuiltinSymbol:6,SpecialBuiltinSymbol:7,ReservedSymbol:8,Binding:9,Spread:10},i=new Set(Object.values(o));function l(e){return Object.keys(o).find(t=>o[t]===e)}const c=new Set(["UserDefined","Partial","Comp","Constantly","Juxt","Complement","EveryPred","SomePred","Fnull","EffectMatcher","Builtin","SpecialBuiltin","Module"]);const u="^^fn^^",p="^^re^^",f="^^ef^^";function d(e){return null!==e&&"object"==typeof e&&(u in e&&"functionType"in e&&function(e){return"string"==typeof e&&c.has(e)}(e.functionType))}function m(e){return!(!Array.isArray(e)||e.length<2)&&function(e){return"number"==typeof e&&i.has(e)}(e[0])}function y(e){return d(e)?`<function ${e.name||"λ"}>`:m(e)?`${l(e[0])}-node`:null===e?"null":"object"==typeof e&&e instanceof RegExp?`${e}`:"object"==typeof e&&e instanceof Error?e.toString():JSON.stringify(e)}function g(e,t){return e?.sourceCodeInfo??t}function h(e,t,r){return new n(`Expected ${e}, got ${y(t)}.`,g(t,r))}function v(e,t){return b(e,t),e}function b(e,t){if(!function(e){return void 0!==e}(e))throw new n("Unexpected undefined",g(e,t))}function x(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function w(e){return null!==e&&"object"==typeof e&&!!e[u]}function k(e){return w(e)&&"UserDefined"===e.functionType}function A(e){return void 0!==e}function E(e,t){return N(e,t),e}function N(e,t){if(!A(e))throw h("not undefined",e,t)}function $(e){return Array.isArray(e)||"string"==typeof e}function S(e,t){if(!$(e))throw h("string or array",e,t)}function I(e){return!(null===e||"object"!=typeof e||Array.isArray(e)||e instanceof RegExp||w(e)||R(e)||T(e))}function j(e,t){if(!I(e))throw h("object",e,t)}function q(e){return $(e)||I(e)}function C(e,t){if(!q(e))throw h("string, array or object",e,t)}function R(e){return null!==e&&"object"==typeof e&&!!e[p]}function P(e,t){if(!function(e){return R(e)||"string"==typeof e}(e))throw h("string or RegularExpression",e,t)}function T(e){return null!==e&&"object"==typeof e&&!!e[f]}function O(e,t){if(!T(e))throw h("Effect",e,t)}function M(e,t){return V(e,t),e}function V(e,t){if(!function(e){return"number"==typeof e||!!q(e)||!!w(e)}(e))throw h("FunctionLike",e,t)}function U(e,t={}){return"string"==typeof e&&((!t.nonEmpty||0!==e.length)&&(!t.char||1===e.length))}function B(e,t,n={}){if(!U(e,n))throw h(""+(n.nonEmpty?"non empty string":n.char?"character":"string"),e,t)}function D(e,t,n={}){return B(e,t,n),e}function _(e){return"string"==typeof e||"number"==typeof e}function F(e,t){return L(e,t),e}function L(e,t){if(!_(e))throw h("string or number",e,t)}const z={assert:{evaluate:(e,t)=>{const n=e[0],r=2===e.length?e[1]:`${n}`;if(B(r,t),!n)throw new a(r,t);return E(n,t)},arity:{min:1,max:2},docs:{category:"assertion",description:"If $value is falsy it throws `AssertionError` with $message. If no $message is provided, message is set to $value.",returns:{type:"any"},args:{value:{type:"any"},message:{type:"string"}},variants:[{argumentNames:["value"]},{argumentNames:["value","message"]}],examples:['do assert(0, "Expected a positive value") with case effect(dvala.error) then ([msg]) -> msg end'],seeAlso:["assertion.assert-truthy","assertion.assert-true"],hideOperatorForm:!0}}};function W(e,t={}){return"number"==typeof e&&(!Number.isNaN(e)&&(!(t.integer&&!Number.isInteger(e))&&(!(t.finite&&!Number.isFinite(e))&&((!t.zero||0===e)&&((!t.nonZero||0!==e)&&(!(t.positive&&e<=0)&&(!(t.negative&&e>=0)&&(!(t.nonPositive&&e>0)&&(!(t.nonNegative&&e<0)&&(!("number"==typeof t.gt&&e<=t.gt)&&(!("number"==typeof t.gte&&e<t.gte)&&(!("number"==typeof t.lt&&e>=t.lt)&&!("number"==typeof t.lte&&e>t.lte)))))))))))))}function J(e,t,r={}){if(!W(e,r))throw new n(`Expected ${function(e){if(e.zero)return"zero";const t=function(e){return e.positive?"positive":e.negative?"negative":e.nonNegative?"non negative":e.nonPositive?"non positive":e.nonZero?"non zero":""}(e),n=e.integer?"integer":"number",r=e.finite?"finite":"",a=function(e){return"number"!=typeof e.gt&&"number"!=typeof e.gte||"number"!=typeof e.lt&&"number"!=typeof e.lte?"number"==typeof e.gt||"number"==typeof e.gte?"number"==typeof e.gt?`n > ${e.gt}`:`n >= ${e.gte}`:"number"==typeof e.lt||"number"==typeof e.lte?"number"==typeof e.lt?`n < ${e.lt}`:`n <= ${e.lte}`:"":`${"number"==typeof e.gt?`${e.gt} < n `:`${e.gte} <= n `}${"number"==typeof e.lt?`< ${e.lt}`:`<= ${e.lte}`}`}(e);return[t,r,n,a].filter(e=>!!e).join(" ")}(r)}, got ${y(e)}.`,g(e,t))}function Y(e,t){const{min:n}=e;return!("number"==typeof n&&t<n)}function K(e,t,r){const{min:a,max:s}=e;if("number"==typeof a&&t<a)throw new n(`Wrong number of arguments, expected at least ${a}, got ${y(t)}.`,r);if("number"==typeof s&&t>s)throw new n(`Wrong number of arguments, expected at most ${s}, got ${y(t)}.`,r)}function G(e){return{min:e,max:e}}function X(e,t){return{a:{type:e},b:{type:t}}}const H={"<<":{evaluate:([e,t],n)=>(J(e,n,{integer:!0}),J(t,n,{integer:!0,nonNegative:!0}),e<<t),arity:G(2),docs:{category:"bitwise",returns:{type:"integer"},args:{...X("integer","integer")},variants:[{argumentNames:["a","b"]}],description:"Shifts $a arithmetically left by $b bit positions.",seeAlso:[">>",">>>"],examples:["1 << 10","<<(1, 10)","<<(-4, 2)"]}},">>":{evaluate:([e,t],n)=>(J(e,n,{integer:!0}),J(t,n,{integer:!0,nonNegative:!0}),e>>t),arity:G(2),docs:{category:"bitwise",returns:{type:"integer"},args:{...X("integer","integer")},variants:[{argumentNames:["a","b"]}],description:"Shifts $a arithmetically right by $b bit positions.",seeAlso:["<<",">>>"],examples:["2048 >> 10",">>(2048, 10)",">>>(-16, 2)",">>(4, 10)"]}},">>>":{evaluate:([e,t],n)=>(J(e,n,{integer:!0}),J(t,n,{integer:!0,nonNegative:!0}),e>>>t),arity:G(2),docs:{category:"bitwise",returns:{type:"integer"},args:{...X("integer","integer")},variants:[{argumentNames:["a","b"]}],description:"Shifts $a arithmetically right by $b bit positions without sign extension.",seeAlso:["<<",">>"],examples:["-16 >>> 2",">>>(2048, 10)",">>>(-16, 2)",">>>(4, 10)",">>>(-1, 10)"]}},"&":{evaluate:([e,...t],n)=>(J(e,n,{integer:!0}),t.reduce((e,t)=>(J(t,n,{integer:!0}),e&t),e)),arity:{min:2},docs:{category:"bitwise",returns:{type:"integer"},args:{...X("integer","integer"),c:{type:"integer",rest:!0}},variants:[{argumentNames:["a","b"]},{argumentNames:["a","b","c"]}],description:"Returns bitwise `and` of all arguments.",seeAlso:["|","xor","bitwise.bit-not","bitwise.bit-and-not"],examples:["0b0011 & 0b0110","&(0b0011, 0b0110)","&(0b0011, 0b0110, 0b1001)"]}},"|":{evaluate:([e,...t],n)=>(J(e,n,{integer:!0}),t.reduce((e,t)=>(J(t,n,{integer:!0}),e|t),e)),arity:{min:2},docs:{category:"bitwise",returns:{type:"integer"},args:{...X("integer","integer"),c:{type:"integer",rest:!0}},variants:[{argumentNames:["a","b"]},{argumentNames:["a","b","c"]}],description:"Returns bitwise `or` of all arguments.",seeAlso:["&","xor","bitwise.bit-not","bitwise.bit-and-not"],examples:["0b0011 | 0b0110","|(0b0011, 0b0110)","|(0b1000, 0b0100, 0b0010)"]}},xor:{evaluate:([e,...t],n)=>(J(e,n,{integer:!0}),t.reduce((e,t)=>(J(t,n,{integer:!0}),e^t),e)),arity:{min:2},docs:{category:"bitwise",returns:{type:"integer"},args:{...X("integer","integer"),c:{type:"integer",rest:!0}},variants:[{argumentNames:["a","b"]},{argumentNames:["a","b","c"]}],description:"Returns bitwise `xor` of all arguments.",seeAlso:["&","|","bitwise.bit-not","bitwise.bit-and-not"],examples:["0b0011 xor 0b0110","xor(0b0011, 0b0110)","xor(0b11110000, 0b00111100, 0b10101010)"]}}};function Z(e,t){return!!q(e)&&("string"==typeof e||Array.isArray(e)?!!W(t,{integer:!0})&&(t>=0&&t<e.length):!!Object.getOwnPropertyDescriptor(e,t))}function Q(e,t,r){if(L(e,r),L(t,r),"string"==typeof e&&"string"==typeof t)return e<t?-1:e>t?1:0;if("number"==typeof e&&"number"==typeof t)return Math.sign(e-t);throw new n(`Cannot compare values of different types: ${typeof e} and ${typeof t}`,r)}function ee(e,t,n){if(e===t)return!0;if("number"==typeof e&&"number"==typeof t)return function(e,t,n=ae){if(e===t)return!0;const r=Math.abs(e-t);if(0===e||0===t||r<n)return r<n;const a=Math.abs(e),s=Math.abs(t);return r/(a+s)<n}(e,t);if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(!ee(E(e[r],n),E(t[r],n),n))return!1;return!0}if(R(e)&&R(t))return e.s===t.s&&e.f===t.f;if(x(e)&&x(t)){const r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(let a=0;a<r.length;a+=1){const s=D(r[a],n);if(!ee(e[s],t[s],n))return!1}return!0}return!1}function te(e){return e??null}function ne(...e){const t=new Set;for(const n of e)n.forEach(e=>t.add(e));return t}function re(e,t){t.forEach(t=>e.add(t))}const ae=1e-10;function se(e,t=0){const n=e.split("\n");for(;n[0]?.match(/^\s*$/);)n.shift();for(;n[n.length-1]?.match(/^\s*$/);)n.pop();const r=n.reduce((e,t)=>{if(t.match(/^\s*$/))return e;const n=t.match(/^\s*/)[0].length;return Math.min(e,n)},1/0);return n.map(e=>" ".repeat(t)+e.slice(r)).join("\n").trimEnd()}function oe(e,t){if(!Array.isArray(e))throw h("array",e,t)}function ie(e,t){if(!function(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}(e))throw h("array of strings",e,t)}function le(e,t){if(!function(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e&&1===e.length)}(e))throw h("array of strings",e,t)}const ce={filter:{evaluate:()=>{throw new Error("filter is implemented in Dvala")},arity:G(2),docs:{category:"collection",returns:{type:"collection"},args:{a:{type:"collection"},b:{type:"function"},coll:{type:"collection"},fun:{type:"function"}},variants:[{argumentNames:["coll","fun"]}],description:"Creates a new collection with all elements that pass the test implemented by $fun.",seeAlso:["collection.filteri","map","sequence.remove"],examples:['\nfilter(\n ["Albert", "Mojir", 160, [1, 2]],\n string?\n)',"\nfilter(\n [5, 10, 15, 20],\n -> $ > 10\n)","\nfilter(\n { a: 1, b: 2 },\n odd?\n)"]}},map:{evaluate:()=>{throw new Error("map is implemented in Dvala")},arity:{min:2},docs:{category:"collection",returns:{type:"collection"},args:{a:{type:"collection"},b:{type:"function"},colls:{type:"collection",rest:!0,description:"At least one."},fun:{type:"function"}},variants:[{argumentNames:["colls","fun"]}],description:"Creates a new collection populated with the results of calling $fun on every element in $colls.",seeAlso:["collection.mapi","filter","reduce","mapcat","grid.cell-map","grid.cell-mapi"],examples:["[1, 2, 3] map -","[1, 2, 3] map -> -($)",'map(["Albert", "Mojir", 42], str)',"map([1, 2, 3], inc)","map([1, 2, 3], [1, 10, 100], *)","map({ a: 1, b: 2 }, inc)","map({ a: 1, b: 2 }, { a: 10, b: 20 }, +)"]}},reduce:{evaluate:()=>{throw new Error("reduce is implemented in Dvala")},arity:G(3),docs:{category:"collection",returns:{type:"any"},args:{fun:{type:"function"},coll:{type:"collection"},initial:{type:"any"}},variants:[{argumentNames:["coll","fun","initial"]}],description:"Runs $fun function on each element of the $coll, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the $coll is a single value.",seeAlso:["collection.reduce-right","collection.reducei","collection.reductions","map","grid.cell-reduce","grid.cell-reducei"],examples:["reduce([1, 2, 3], +, 0)","reduce([], +, 0)","reduce({ a: 1, b: 2 }, +, 0)","\nreduce(\n [1, 2, 3, 4, 5, 6, 7, 8, 9],\n (result, value) -> result + (even?(value) ? value : 0),\n 0)"]}},get:{evaluate:(e,t)=>{const[n,r]=e,a=te(e[2]);if(L(r,t),null===n)return a;C(n,t);const s=function(e,t){if(I(e)){if("string"==typeof t&&Z(e,t))return te(e[t])}else if(W(t,{nonNegative:!0,integer:!0})&&t>=0&&t<e.length)return te(e[t])}(n,r);return void 0===s?a:s},arity:{min:2,max:3},docs:{category:"collection",returns:{type:"any"},args:{a:{type:"collection"},b:{type:["string","integer"]},"not-found":{type:"any",description:"Default value to return if $b is not found."}},variants:[{argumentNames:["a","b"]},{argumentNames:["a","b","not-found"]}],description:"Returns value in $a mapped at $b.",seeAlso:["collection.get-in","contains?","find","nth"],examples:["[1, 2, 3] get 1",'{ a: 1 } get "a"','"Albert" get "3"',"\nget(\n [1, 2, 3],\n 1, // Optional comma after last argument\n)","\nget(\n [],\n 1\n)",'\nget(\n [],\n 1,\n "default"\n)','\nget(\n { a: 1 },\n "a"\n)','\nget(\n { a: 1 },\n "b"\n)','\nget(\n { a: 1 },\n "b",\n "default"\n)','\nget(\n null,\n "a"\n)','\nget(\n null,\n "b",\n "default"\n)']}},count:{evaluate:([e],t)=>null===e?0:"string"==typeof e?e.length:(C(e,t),Array.isArray(e)?e.length:Object.keys(e).length),arity:G(1),docs:{category:"collection",returns:{type:"number"},args:{coll:{type:["collection","null"]}},variants:[{argumentNames:["coll"]}],description:"Returns number of elements in $coll.",seeAlso:["empty?"],examples:["count([1, 2, 3])","count([])","count({ a: 1 })",'count("")','count("Albert")',"count(null)"]}},"contains?":{evaluate:([e,t],n)=>null!==e&&(C(e,n),U(e)?(B(t,n),e.includes(t)):$(e)?(N(t,n),!!e.find(e=>ee(E(e),t,n))):(B(t,n),t in e)),arity:G(2),docs:{category:"collection",returns:{type:"boolean"},args:{a:{type:["collection","null"]},b:{type:["string","integer"]}},variants:[{argumentNames:["a","b"]}],description:"Returns `true` if $a contains $b, otherwise returns `false`. For strings, it checks if substring is included.",seeAlso:["get","find","index-of"],examples:["[1, 2, 3] contains? 1","null contains? 1",'{ a: 1, b: 2 } contains? "a"',"\ncontains?(\n [],\n 1\n)","\ncontains?(\n [1],\n 1\n)","\ncontains?(\n [1, 2, 3],\n 1\n)",'\ncontains?(\n {},\n "a"\n)','\ncontains?(\n { a: 1, b: 2 },\n "a"\n)']}},assoc:{evaluate:([e,t,n],r)=>(C(e,r),L(t,r),N(n,r),function(e,t,n,r){if(C(e,r),L(t,r),Array.isArray(e)||"string"==typeof e){if(J(t,r,{integer:!0}),J(t,r,{gte:0}),J(t,r,{lte:e.length}),"string"==typeof e)return B(n,r,{char:!0}),`${e.slice(0,t)}${n}${e.slice(t+1)}`;const a=[...e];return a[t]=n,a}B(t,r);const a={...e};return a[t]=n,a}(e,t,n,r)),arity:G(3),docs:{category:"collection",returns:{type:"collection"},args:{coll:{type:"collection"},key:{type:["string","number"]},value:{type:"any"},kvs:{type:"any",description:"Key-value pairs to associate.",rest:!0}},variants:[{argumentNames:["coll","key","value"]},{argumentNames:["coll","key","value","kvs"]}],description:"\nAdd or replace the value of element $key to $value in $coll. Repeated for all key-value pairs in $kvs.\nIf $coll is an 'array', $key must be `number` satisfying `0 <=` $key `<= length`.",seeAlso:["collection.assoc-in","dissoc","merge","collection.update"],examples:['\nassoc(\n [1, 2, 3],\n 1,\n "Two"\n)','\nassoc(\n [1, 2, 3],\n 3,\n "Four"\n)','\nassoc(\n { a: 1, b: 2 },\n "a",\n "One")','\nassoc(\n { a: 1, b: 2 },\n "c",\n "Three")','\nassoc(\n "Albert",\n 6,\n "a")']}},"++":{evaluate:(e,t)=>(W(e[0])||C(e[0],t),Array.isArray(e[0])?e.reduce((e,n)=>(oe(n,t),e.concat(n)),[]):_(e[0])?e.reduce((e,n)=>(L(n,t),`${e}${n}`),""):e.reduce((e,n)=>(j(n,t),Object.assign(e,n)),{})),arity:{min:1},docs:{category:"collection",returns:{type:"collection"},args:{a:{type:"collection"},b:{type:"collection"},colls:{type:"collection",rest:!0}},variants:[{argumentNames:["a"]},{argumentNames:["a","colls"]}],description:"Concatenates collections into one collection.",seeAlso:["mapcat","str","join","push","sequence.unshift"],examples:['"Albert" ++ " " ++ "Mojir"','"Albert" ++ "Mojir"','++("Albert", "-", "Mojir")','++("Albert")','++("A", "l", "b", "e", "r", "t")',"++([1, 2], [3, 4])","++([], [3, 4])","++([1, 2], [])","++([1, 2], [3, 4], [5, 6])","++([])","++({ a: 1, b: 2 }, { b: 1, c: 2 })","++({}, { a: 1 })"]}}},ue={range:{evaluate:(e,t)=>{const[n,r,a]=e;let s,o,i;J(n,t,{finite:!0}),1===e.length?(s=0,o=n,i=o>=0?1:-1):2===e.length?(J(r,t,{finite:!0}),s=n,o=r,i=o>=s?1:-1):(J(r,t,{finite:!0}),J(a,t,{finite:!0}),s=n,o=r,i=a,J(i,t,o>s?{positive:!0}:o<s?{negative:!0}:{nonZero:!0}));const l=[];for(let e=s;i<0?e>o:e<o;e+=i)l.push(e);return l},arity:{min:1,max:3},docs:{category:"array",returns:{type:"number",array:!0},args:{a:{type:"number"},b:{type:"number"},step:{type:"number"}},variants:[{argumentNames:["b"]},{argumentNames:["a","b"]},{argumentNames:["a","b","step"]}],description:"$range creates an array with a range of numbers from $a to $b (exclusive), by $step.\n\n$a defaults to 0.\n$step defaults to 1.",seeAlso:["repeat","vector.linspace"],examples:["range(4)","range(1, 4)","1 range 10","range(0.4, 4.9)","\nrange(\n 0.25, // start value\n 1, // end value (exclusive)\n 0.25, // step value\n)"]}},repeat:{evaluate:([e,t],n)=>{J(t,n,{integer:!0,nonNegative:!0});const r=[];for(let n=0;n<t;n+=1)r.push(e);return r},arity:G(2),docs:{category:"array",returns:{type:"any",array:!0},args:{a:{type:"any"},b:{type:"integer"}},variants:[{argumentNames:["a","b"]}],description:"Returns an array with $a repeated $b times.",seeAlso:["range","string.string-repeat"],examples:["repeat(10, 3)","repeat(10, 0)",'"Albert" repeat 5']}},flatten:{evaluate:([e,t],n)=>{oe(e,n);const r=void 0===t||t===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:function(e,t,n={}){return J(e,t,n),e}(t,n,{integer:!0,nonNegative:!0});return e.flat(r)},arity:{min:1,max:2},docs:{category:"array",returns:{type:"any",array:!0},args:{x:{type:["array","any"],description:"If $x is not an array, `[ ]` is returned."},depth:{type:"integer",description:"The depth level specifying how deep a nested array structure should be flattened. Defaults to `Infinity`."}},variants:[{argumentNames:["x"]},{argumentNames:["x","depth"]}],description:"Takes a nested array $x and flattens it.",seeAlso:["mapcat"],examples:["flatten([1, 2, [3, 4], 5])","flatten([1, [2, [3, [4]]]], 1)","flatten([1, [2, [3, [4]]]], 2)",'\nlet foo = "bar";\nflatten([\n 1,\n " 2 A ",\n [foo, [4, ["ABC"]]],\n 6,\n])'],hideOperatorForm:!0}},mapcat:{evaluate:()=>{throw new Error("mapcat is implemented in Dvala")},arity:G(2),docs:{category:"array",returns:{type:"collection"},args:{a:{type:"collection"},b:{type:"function"},colls:{type:"collection",array:!0},fun:{type:"function"}},variants:[{argumentNames:["colls","fun"]}],description:"Returns the result of applying concat to the result of applying map to $fun and $colls.",seeAlso:["flatten","map","++"],examples:["[[3, 2, 1, 0], [6, 5, 4], [9, 8, 7]] mapcat reverse","mapcat([[3, 2, 1, 0], [6, 5, 4], [9, 8, 7]], reverse)","[[3, 2, 1, 0,], [6, 5, 4,], [9, 8, 7]] mapcat reverse","\nlet foo = (n) -> do\n [n - 1, n, n + 1]\nend;\n[1, 2, 3] mapcat foo","\nmapcat(\n [[1, 2], [2, 2], [2, 3]],\n -> $ filter odd?\n)"]}},"moving-fn":{evaluate:()=>{throw new Error("moving-fn is implemented in Dvala")},arity:G(3),docs:{category:"array",returns:{type:"array"},args:{arr:{type:"array"},windowSize:{type:"number",description:"The size of the moving window."},fn:{type:"function"}},variants:[{argumentNames:["arr","windowSize","fn"]}],description:"Returns the result of applying $fn to each moving window of size $windowSize in $arr.",seeAlso:["running-fn","vector.moving-mean"],examples:["moving-fn([1, 2, 3], 2, sum)","moving-fn([1, 2, 3], 1, sum)","moving-fn([1, 2, 3], 3, sum)"]}},"running-fn":{evaluate:()=>{throw new Error("running-fn is implemented in Dvala")},arity:G(2),docs:{category:"array",returns:{type:"array"},args:{a:{type:"array"},b:{type:"function"}},variants:[{argumentNames:["a","b"]}],description:"Returns the result of applying $b to each element of $a.",seeAlso:["moving-fn","vector.running-mean"],examples:["running-fn([1, 2, 3], sum)","running-fn([1, 2, 3], max)","running-fn([1, 2, 3], min)"]}}},pe={nth:{evaluate:(e,t)=>{const[n,r]=e,a=te(e[2]);if(J(r,t,{integer:!0}),null===n)return a;if(S(n,t),r>=0&&r<n.length){return te(n[r])}return a},arity:{min:2,max:3},docs:{category:"sequence",returns:{type:"any"},args:{a:{type:"sequence"},b:{type:"integer"},seq:{type:["sequence","null"]},n:{type:"integer"},"not-found":{type:"any"}},variants:[{argumentNames:["seq","n"]},{argumentNames:["seq","n","not-found"]}],description:"Accesses element $n of $seq. Accessing out-of-bounds indices returns $not-found, if present, else `null`.",seeAlso:["first","second","last","get","slice"],examples:["[1, 2, 3] nth 1",'"A string" nth 3',"nth([1, 2, 3], 1)","nth([1, 2, 3], 3)","nth([1, 2, 3], -1)","nth([1, 2, 3], 3, 99)",'nth("A string", 1)','nth("A string", 3)','nth("A string", -3)','nth("A string", 30, "X")',"nth(null, 1)",'nth(null, 1, "Default value")']}},first:{evaluate:([e],t)=>{if(null===e)return null;S(e,t);return te(e[0])},arity:G(1),docs:{category:"sequence",returns:{type:"any"},args:{seq:{type:["sequence","null"]}},variants:[{argumentNames:["seq"]}],description:"Returns the first element of $seq. If $seq is empty or `null`, `null` is returned.",seeAlso:["second","last","nth","rest","next"],examples:['first(["Albert", "Mojir", 160, [1, 2]])',"first([])","first(null)"]}},last:{evaluate:([e],t)=>{if(null===e)return null;S(e,t);return te(e.at(-1))},arity:G(1),docs:{category:"sequence",returns:{type:"any"},args:{seq:{type:["sequence","null"]}},variants:[{argumentNames:["seq"]}],description:"Returns the last element of $seq. If $seq is empty, `null` is returned.",seeAlso:["first","second","nth","pop"],examples:['last(["Albert", "Mojir", 160, [1, 2]])',"last([1, 2])","last([1])","last([])","last(null)"]}},pop:{evaluate:([e],t)=>(S(e,t),"string"==typeof e?e.substring(0,e.length-1):e.slice(0,e.length-1)),arity:G(1),docs:{category:"sequence",returns:{type:["sequence","null"],rest:!0},args:{seq:{type:"sequence"}},variants:[{argumentNames:["seq"]}],description:"Returns a copy of $seq with last element removed. If $seq is empty `null` is returned.",seeAlso:["push","last"],examples:["pop([1, 2, 3])","pop([])"]}},"index-of":{evaluate:([e,t],n)=>{if(N(t,n),null===e)return null;if(S(e,n),"string"==typeof e){B(t,n);const r=e.indexOf(t);return-1!==r?r:null}{const r=e.findIndex(e=>ee(E(e,n),t),n);return-1!==r?r:null}},arity:G(2),docs:{category:"sequence",returns:{type:["number","null"]},args:{a:{type:"sequence"},b:{type:"any"},seq:{type:["sequence","null"]},x:{type:"any"}},variants:[{argumentNames:["seq","x"]}],description:"Returns the index of $x in $seq. If element is not present in $seq `null` is returned.",seeAlso:["sequence.last-index-of","sequence.position","contains?"],examples:["[[1], [2], [1], [2]] index-of [1]",'index-of(["Albert", "Mojir", 160, [1, 2]], "Mojir")',"index-of([5, 10, 15, 20], 15)","index-of([5, 10, 15, 20], 1)","index-of(null, 1)"]}},push:{evaluate:([e,...t],n)=>(S(e,n),"string"==typeof e?(le(t,n),[e,...t].join("")):[...e,...t]),arity:{min:2},docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"any"},seq:{type:"sequence"},values:{type:"any",rest:!0,description:"At least one."}},variants:[{argumentNames:["seq","values"]}],description:"Returns copy of $seq with $values added to the end of it.",seeAlso:["sequence.unshift","pop","++"],examples:["[1, 2, 3] push 4",'"Albert" push "!"',"push([1, 2, 3], 4)","push([1, 2, 3], 4, 5, 6)","\nlet l = [1, 2, 3];\npush(l, 4);\nl"]}},rest:{evaluate:([e],t)=>(S(e,t),Array.isArray(e)?e.length<=1?[]:e.slice(1):e.substring(1)),arity:G(1),docs:{category:"sequence",returns:{type:["sequence","null"]},args:{seq:{type:"sequence"}},variants:[{argumentNames:["seq"]}],description:"If $seq is an array, returns a new array with all but the first element from $seq.\nIf $seq has less than two elements, an empty array is returned.\nFor string $seq returns all but the first characters in $seq.",seeAlso:["next","first"],examples:['rest(["Albert", "Mojir", 160, [1, 2]])','rest(["Albert"])',"rest([])",'rest("Albert")','rest("A",)','rest("")']}},next:{evaluate:([e],t)=>(S(e,t),Array.isArray(e)?e.length<=1?null:e.slice(1):e.length<=1?null:e.substring(1)),arity:G(1),docs:{category:"sequence",returns:{type:["sequence","null"]},args:{seq:{type:"sequence"}},variants:[{argumentNames:["seq"]}],description:"If $seq is an array, returns a new array with all but the first element from $seq. If $seq has less than two elements, `null` is returned. For string $seq returns all but the first characters in $seq. If length of string $seq is less than two, `null` is returned.",seeAlso:["rest","first"],examples:['next(["Albert", "Mojir", 160, [1, 2]])','next(["Albert"])',"next([])",'next("Albert")','next("A",)','next("")']}},reverse:{evaluate:([e],t)=>null===e?null:(S(e,t),Array.isArray(e)?[...e].reverse():e.split("").reverse().join("")),arity:G(1),docs:{category:"sequence",returns:{type:["sequence","null"]},args:{seq:{type:["sequence","null"]}},variants:[{argumentNames:["seq"]}],description:"If $seq is an array, creates a new array with the elements from $seq in reversed order. If $seq is a string, returns new reversed string.",seeAlso:["sort"],examples:['reverse(["Albert", "Mojir", 160, [1, 2]])',"reverse([])",'reverse("Albert")',"reverse(null)"]}},second:{evaluate:([e],t)=>null===e?null:(S(e,t),te(e[1])),arity:G(1),docs:{category:"sequence",returns:{type:"any"},args:{seq:{type:["sequence","null"]}},variants:[{argumentNames:["seq"]}],description:"Returns the second element of $seq. If $seq has less than two elements or is `null`, `null` is returned.",seeAlso:["first","last","nth"],examples:['second(["Albert", "Mojir", 160, [1, 2]])',"second([1])","second([])","second(null)"]}},slice:{evaluate:(e,t)=>{const[n,r,a]=e;return S(n,t),J(r,t,{integer:!0}),2===e.length?(Array.isArray(n),n.slice(r)):(J(a,t,{integer:!0}),Array.isArray(n),n.slice(r,a))},arity:{min:2,max:3},docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"integer"},seq:{type:"sequence"},start:{type:"integer",description:"Defaults to `0`."},stop:{type:"integer",description:"Defaults to length of sequence + 1."}},variants:[{argumentNames:["seq","start"]},{argumentNames:["seq","start","stop"]}],description:"Returns a copy of a portion of $seq from index $start (inclusive) to $stop (exclusive).",seeAlso:["take","drop","sequence.splice","nth"],examples:["[1, 2, 3, 4, 5] slice 2","slice([1, 2, 3, 4, 5], 2, 4)","slice([1, 2, 3, 4, 5], 2)"]}},some:{evaluate:()=>{throw new Error("some is implemented in Dvala")},arity:G(2),docs:{category:"sequence",returns:{type:"any"},args:{a:{type:"sequence"},b:{type:"function"},seq:{type:["sequence","null"]},fun:{type:"function"}},variants:[{argumentNames:["seq","fun"]}],description:"Returns the first element that passes the test implemented by $fun. I no element was found, `null` is returned.",seeAlso:["sequence.position","collection.any?","find"],examples:['\nsome(\n ["Albert", "Mojir", 160, [1, 2]],\n string?\n)',"\nsome(\n [5, 10, 15, 20],\n -> $ > 10\n)","\nsome(\n [1, 2, 3, 4],\n -> $ > 10\n)","\nsome(\n [],\n -> $ > 10\n)","\nsome(\n null,\n -> $ > 10\n)"]}},sort:{evaluate:()=>{throw new Error("sort is implemented in Dvala")},arity:{min:1,max:2},docs:{category:"sequence",returns:{type:"any",rest:!0},args:{a:{type:"sequence"},b:{type:"function"},seq:{type:"sequence"},fun:{type:"function"}},variants:[{argumentNames:["seq"]},{argumentNames:["seq","fun"]}],description:"Returns a new sequence with the elements from $seq sorted according to $fun. If no $fun is supplied, builtin `compare` will be used.",seeAlso:["sequence.sort-by","compare","reverse","vector.sort-indices"],examples:["[3, 1, 2] sort (a, b) -> b - a","sort([3, 1, 2])","\nsort(\n [3, 1, 2],\n (a, b) -> cond case a < b then -1 case a > b then 1 case true then -1 end\n)","\nsort(\n [3, 1, 2],\n (a, b) -> cond case a > b then -1 case a < b then 1 case true then -1 end\n)"]}},take:{evaluate:([e,t],n)=>{J(t,n),S(e,n);const r=Math.max(Math.ceil(t),0);return e.slice(0,r)},arity:G(2),docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"integer"},n:{type:"integer"},seq:{type:"sequence"}},variants:[{argumentNames:["seq","n"]}],description:"Constructs a new array/string with the $n first elements from $seq.",seeAlso:["take-last","take-while","drop","slice","sequence.split-at"],examples:["take([1, 2, 3, 4, 5], 3)","[1, 2, 3, 4, 5] take 3","take([1, 2, 3, 4, 5], 0)",'take("Albert", 2)','take("Albert", 50)']}},"take-last":{evaluate:([e,t],n)=>{S(e,n),J(t,n);const r=Math.max(Math.ceil(t),0),a=e.length-r;return e.slice(a)},arity:G(2),docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"integer"},n:{type:"integer"},seq:{type:"sequence"}},variants:[{argumentNames:["seq","n"]}],description:"Constructs a new array with the $n last elements from $seq.",seeAlso:["take","drop-last"],examples:["take-last([1, 2, 3, 4, 5], 3)","[1, 2, 3, 4, 5] take-last 3","take-last([1, 2, 3, 4, 5], 0)"]}},drop:{evaluate:([e,t],n)=>{J(t,n);const r=Math.max(Math.ceil(t),0);return S(e,n),e.slice(r)},arity:G(2),docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"integer"},seq:{type:"sequence"},n:{type:"integer"}},variants:[{argumentNames:["seq","n"]}],description:"Constructs a new array/string with the $n first elements dropped from $seq.",seeAlso:["drop-last","drop-while","take","slice","sequence.split-at"],examples:["drop([1, 2, 3, 4, 5], 3)","[1, 2, 3, 4, 5] drop 0",'drop("Albert", 2)','drop("Albert", 50)']}},"drop-last":{evaluate:([e,t],n)=>{S(e,n),J(t,n);const r=Math.max(Math.ceil(t),0),a=e.length-r;return e.slice(0,a)},arity:G(2),docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"integer"},seq:{type:"sequence"},n:{type:"integer"}},variants:[{argumentNames:["seq","n"]}],description:"Constructs a new array with the $n last elements dropped from $seq.",seeAlso:["drop","take-last"],examples:["drop-last([1, 2, 3, 4, 5], 3)","[1, 2, 3, 4, 5] drop-last 3","drop-last([1, 2, 3, 4, 5], 0)"]}},"take-while":{evaluate:()=>{throw new Error("take-while is implemented in Dvala")},arity:G(2),docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"function"},seq:{type:"sequence"},fun:{type:"function"}},variants:[{argumentNames:["seq","fun"]}],description:"Returns the members of $seq in order, stopping before the first one for which `predicate` returns a falsy value.",seeAlso:["take","drop-while","sequence.split-with"],examples:["take-while(\n [1, 2, 3, 2, 1],\n -> $ < 3\n)","take-while(\n [1, 2, 3, 2, 1],\n -> $ > 3\n)"]}},"drop-while":{evaluate:()=>{throw new Error("drop-while is implemented in Dvala")},arity:G(2),docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"function"},seq:{type:"sequence"},fun:{type:"function"}},variants:[{argumentNames:["seq","fun"]}],description:"Returns the members of $seq in order, skipping the fist elements for witch the `predicate` returns a truethy value.",seeAlso:["drop","take-while","sequence.split-with"],examples:["drop-while(\n [1, 2, 3, 2, 1],\n -> $ < 3\n)","drop-while(\n [1, 2, 3, 2, 1],\n -> $ > 3\n)"]}}},fe=new WeakSet,de=new WeakSet,me=new WeakSet,ye=new WeakSet,ge=new WeakSet,he=new WeakSet,ve=new WeakSet;function be(e){return Array.isArray(e)?(fe.has(e)||(xe(e),Ee(e)||Ae(e)),e):e}function xe(e){return!!Array.isArray(e)&&(!!de.has(e)||!me.has(e)&&(e.every(e=>W(e))?(fe.add(e),de.add(e),!0):(me.add(e),!1)))}function we(e,t){if(!xe(e))throw new n(`Expected a vector, but got ${e}`,t)}function ke(e,t){if(we(e,t),0===e.length)throw new n(`Expected a non empty vector, but got ${e}`,t)}function Ae(e,t){if(!Array.isArray(e))return!1;if(he.has(e))return!0;if(ve.has(e))return!1;if(0===e.length)return ve.add(e),!1;if(!Array.isArray(e[0]))return ve.add(e),!1;const n=e[0].length;if(0===n)return ve.add(e),!1;for(const r of e){if(!Array.isArray(r))return ve.add(e),!1;if(r.length!==n)return ve.add(e),!1;if(t&&r.some(e=>!t(e)))return!1}return fe.add(e),he.add(e),!0}function Ee(e){return Ae(e,W)?(ye.add(e),!0):(Array.isArray(e)&&ge.add(e),!1)}function Ne(e,t){let r=!1,a=!1;for(const s of e)if(xe(s))r=!0;else if(Ee(s))a=!0;else if(!W(s))throw new n("Invalid parameter type: "+typeof s,t);if(a){if(r)throw new n("Cannot mix vector and matrix types",t);let a=null,s=null;for(const r of e)if(Ee(r))if(null===a)a=r.length,s=r[0].length;else if(r.length!==a||r[0].length!==s)throw new n("Matrix dimensions do not match",t);return["matrix",e.map(e=>Ee(e)?e:Array.from({length:a},()=>Array.from({length:s},()=>e)))]}if(r){let r=null;for(const a of e)if(xe(a))if(null===r)r=a.length;else if(a.length!==r)throw new n("Vector lengths do not match",t);return["vector",e.map(e=>xe(e)?e:Array.from({length:r},()=>e))]}return["number",e]}function $e(e){return(t,n)=>{const[r,a]=Ne(t,n);return"number"===r?e(a[0]):"vector"===r?a[0].map(t=>e(t)):a[0].map(t=>t.map(t=>e(t)))}}function Se(e){return(t,n)=>{const[r,a]=Ne(t,n);return"number"===r?e(a[0],a[1]):"vector"===r?a[0].map((t,n)=>e(t,a[1][n])):a[0].map((t,n)=>t.map((t,r)=>e(t,a[1][n][r])))}}function Ie(e,t){return(n,r)=>{if(0===n.length)return e;const[a,s]=Ne(n,r);if("number"===a)return s.reduce((e,n)=>t(e,n),e);if("vector"===a){const[e,...n]=s;return n.reduce((e,n)=>e.map((e,r)=>t(e,n[r])),e)}{const[e,...n]=s;return n.reduce((e,n)=>e.map((e,r)=>e.map((e,a)=>t(e,n[r][a]))),e)}}}const je={inc:{evaluate:$e(e=>e+1),arity:G(1),docs:{category:"math",returns:{type:"number"},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `inc` function increments its argument by 1, working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it increases each element by 1 while preserving the original structure.",seeAlso:["dec","+"],examples:["inc(0)","inc(1)","inc(100.1)","inc([1, 2, 3])","inc([[1, 2], [3, 4]])"]}},dec:{evaluate:$e(e=>e-1),arity:G(1),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `dec` function decrements its argument by 1, working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it decreases each element by 1 while preserving the original structure.",seeAlso:["inc","-"],examples:["dec(0)","dec(1)","dec(100.1)","dec([1, 2, 3])","dec([[1, 2], [3, 4]])"]}},"+":{evaluate:Ie(0,(e,t)=>e+t),arity:{},docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]},xs:{type:["number","vector","matrix"],rest:!0}},variants:[{argumentNames:["xs"]}],description:"The `+` function performs addition of numbers and element-wise addition of `vectors` and `matrices` of compatible dimensions, returning the same type as its inputs. When used with mixed types, it adds the scalar to each element of the collection.",seeAlso:["-","*","/","inc"],examples:["1 + 2","1 + 20 + 30","+(1, 2, 3, 4)","+()","+(1)","[1, 2, 3] + 2","[1, 2, 3] + [4, 5, 6]","[[1, 2, 3], [4, 5, 6]] + [[7, 8, 9], [10, 11, 12]]","[[1, 2, 3], [4, 5, 6]] + 2"]}},"*":{evaluate:Ie(1,(e,t)=>e*t),arity:{},docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]},xs:{type:["number","vector","matrix"],rest:!0}},variants:[{argumentNames:["xs"]}],description:"The `*` function performs multiplication of `numbers` and element-wise multiplication of `vectors` and `matrices` of compatible dimensions, returning the same type as its inputs. When used with mixed types, it multiplies each element of the collection by the scalar.",seeAlso:["/","+","-","^"],examples:["6 * 7","-1 * 4","*(4, 7)","*(1, 2, 3, 4, 5)","*()","*(8)","[1, 2, 3] * 2","[1, 2, 3] * [4, 5, 6]","[[1, 2, 3], [4, 5, 6]] * [[7, 8, 9], [10, 11, 12]]","[[1, 2, 3], [4, 5, 6]] * 2"]}},"/":{evaluate:(e,t)=>{if(0===e.length)return 1;const[n,r]=Ne(e,t);if("number"===n){const[e,...t]=r;return 0===t.length?1/e:t.reduce((e,t)=>e/t,e)}if("vector"===n){const e=r[0];return r.slice(1).reduce((e,t)=>e.map((e,n)=>e/t[n]),e)}{const e=r[0];return r.slice(1).reduce((e,t)=>e.map((e,n)=>e.map((e,r)=>e/t[n][r])),e)}},arity:{},docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]},xs:{type:["number","vector","matrix"],rest:!0}},variants:[{argumentNames:["xs"]}],description:"The `/` function performs division of `numbers` and element-wise division of `vectors` and `matrices` of compatible dimensions, returning the same type as its inputs. When used with mixed types, it divides each element of the collection by the scalar.",seeAlso:["*","+","-","quot","mod","%"],examples:["12 / 100","-1 / 4","/(7, 4)","/(1, 2, 4, 8)","/()","/(8)","[1, 2, 3] / 2","[1, 2, 3] / [4, 5, 6]","[[1, 2, 3], [4, 5, 6]] / [[7, 8, 9], [10, 11, 12]]","[[1, 2, 3], [4, 5, 6]] / 2"]}},"-":{evaluate:(e,t)=>{if(0===e.length)return 0;const[n,r]=Ne(e,t);if("number"===n){const[e,...t]=r;return 0===t.length?-e:t.reduce((e,t)=>e-t,e)}if("vector"===n){const e=r[0];return r.slice(1).reduce((e,t)=>e.map((e,n)=>e-t[n]),e)}{const e=r[0];return r.slice(1).reduce((e,t)=>e.map((e,n)=>e.map((e,r)=>e-t[n][r])),e)}},arity:{},docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]},xs:{type:["number","vector","matrix"],rest:!0}},variants:[{argumentNames:["xs"]}],description:"Computes difference between first value and sum of the rest. When called with only one argument, it does negation.",seeAlso:["+","*","/","dec","abs"],examples:["50 - 8","1 - 1 - 1","-()","-(4, 2)","-(4, 3, 2, 1,)","[1, 2, 3] - 2","[1, 2, 3] - [4, 5, 6]","[[1, 2, 3], [4, 5, 6]] - [[7, 8, 9], [10, 11, 12]]","[[1, 2, 3], [4, 5, 6]] - 2"]}},quot:{evaluate:Se((e,t)=>Math.trunc(e/t)),arity:G(2),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]}},variants:[{argumentNames:["a","b"]}],description:"The `quot` function performs integer division truncated toward zero, working on `numbers` and element-wise on `vectors` and `matrices` of compatible dimensions. When used with mixed types, it applies integer division between each element of the collection and the scalar.",seeAlso:["mod","%","/","trunc"],examples:["quot(5, 3)","quot(5.2, 3.1)","quot(-5, 3)","5 quot -3","-5 quot -3","quot(5, 0)","quot(0, 5)","[1, 2, 3] quot 2","2 quot [1, 2, 3]","quot([1, 2, 3], [4, 5, 6])","[[1, 2, 3], [4, 5, 6]] quot [[7, 8, 9], [10, 11, 12]]","quot([[1, 2, 3], [4, 5, 6]], 2)","[[1, 2, 3], [4, 5, 6]] quot [[7, 8, 9], [10, 11, 12]]"]}},mod:{evaluate:Se((e,t)=>e-t*Math.floor(e/t)),arity:G(2),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]}},variants:[{argumentNames:["a","b"]}],description:"The `mod` function computes the modulo of division with the same sign as the divisor, working on `numbers` and element-wise on `vectors` and `matrices` of compatible dimensions. When used with mixed types, it applies the modulo operation between each element of the collection and the scalar.",seeAlso:["%","quot","/"],examples:["mod(5, 3)","mod(5.2, 3.1)","mod(-5, 3)","5 mod -3","-5 mod -3","[1, 2, 3] mod 2","2 mod [1, 2, 3]","mod([1, 2, 3], [4, 5, 6])","[[1, 2, 3], [4, 5, 6]] mod [[7, 8, 9], [10, 11, 12]]","mod([[1, 2, 3], [4, 5, 6]], 2)"]}},"%":{evaluate:Se((e,t)=>e%t),arity:G(2),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]}},variants:[{argumentNames:["a","b"]}],description:"The `%` function computes the remainder of division with the same sign as the dividend, working on `numbers` and element-wise on `vectors` and `matrices` of compatible dimensions. When used with mixed types, it applies the remainder operation between each element of the collection and the scalar.",seeAlso:["mod","quot","/"],examples:["5 % 3","5.2 % 3.1","-5 % 3","%(5, -3)","%(-5, -3)","[1, 2, 3] % 2","2 % [1, 2, 3]","%([1, 2, 3], [4, 5, 6])","[[1, 2, 3], [4, 5, 6]] % [[7, 8, 9], [10, 11, 12]]","%([[1, 2, 3], [4, 5, 6]], 2)"]}},sqrt:{evaluate:$e(e=>Math.sqrt(e)),arity:G(1),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `sqrt` function calculates the square root of `numbers` and computes element-wise square roots of `vectors` and `matrices`. When applied to collections, it returns the square root of each element while preserving the original structure.",seeAlso:["cbrt","^"],examples:["sqrt(0)","sqrt(9)","sqrt(2)","sqrt(0)","sqrt(9)","sqrt(2)","sqrt([1, 4, 9])","sqrt([[1, 4], [9, 16]])"]}},cbrt:{evaluate:$e(e=>Math.cbrt(e)),arity:G(1),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `cbrt` function calculates the cube root of `numbers` and computes element-wise cube roots of `vectors` and `matrices`. When applied to collections, it returns the cube root of each element while preserving the original structure.",seeAlso:["sqrt","^"],examples:["cbrt(0)","cbrt(27)","cbrt(2)","cbrt(1)","cbrt(0)","cbrt(27)","cbrt(2)","cbrt(1)","cbrt([1, 8, 27])","cbrt([[1, 8], [27, 64]])"]}},"^":{evaluate:Se((e,t)=>e**t),arity:G(2),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]}},variants:[{argumentNames:["a","b"]}],description:"The ^ function computes exponentiation, raising the first argument to the power of the second, working on `numbers` and element-wise on `vectors` and `matrices` of compatible dimensions. When used with mixed types, it applies the power operation between each element of the collection and the scalar.",seeAlso:["sqrt","cbrt","*","math.ln"],examples:["2 ^ 3","2 ^ 0","2 ^ -3","^(-2, 3)","^(-2, -3)","[1, 2, 3] ^ 2","2 ^ [1, 2, 3]","^([1, 2, 3], [4, 5, 6])","[[1, 2, 3], [4, 5, 6]] ^ [[7, 8, 9], [10, 11, 12]]","^([[1, 2, 3], [4, 5, 6]], 2)"]}},round:{evaluate:([e,t],n)=>{const[r,a]=Ne([e],n);if("number"===r){if(void 0===t||0===t)return Math.round(a[0]);{J(t,n,{integer:!0,positive:!0});const e=10**t;return Math.round(a[0]*e)/e}}if("vector"===r){const e=a[0];if(void 0===t||0===t)return e.map(e=>Math.round(e));{J(t,n,{integer:!0,positive:!0});const r=10**t;return e.map(e=>Math.round(e*r)/r)}}{const e=a[0];if(void 0===t||0===t)return e.map(e=>e.map(e=>Math.round(e)));{J(t,n,{integer:!0,positive:!0});const r=10**t;return e.map(e=>e.map(e=>Math.round(e*r)/r))}}},arity:{min:1,max:2},docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:"integer"}},variants:[{argumentNames:["a"]},{argumentNames:["a","b"]}],description:"The `round` function rounds a `number` to the nearest `integer` or to a specified number of `decimal` places, working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it rounds each element while preserving the original structure.",seeAlso:["floor","ceil","trunc"],examples:["round(2)","round(2.49)","round(2.5)","round(-2.49)","round(-2.5)","round(-2.501)","round(1.23456789, 4)","1.123456789 round 2","round([1.23456789, 2.3456789], 1)","[1.23456789, 2.3456789] round 4","[[1.23456789, 2.3456789], [3.456789, 4.56789]] round 4","round([[1.23456789, 2.3456789], [3.456789, 4.56789]], 2)"]}},trunc:{evaluate:$e(e=>Math.trunc(e)),arity:G(1),docs:{category:"math",returns:{type:["integer","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `trunc` function truncates `numbers` toward zero (removing decimal portions without rounding), working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it truncates each element while preserving the original structure.",seeAlso:["round","floor","ceil","quot"],examples:["trunc(2)","trunc(2.49)","trunc(2.5)","trunc(-2.49)","trunc(-2.5)","trunc(-2.501)","trunc([1.23456789, 2.3456789])","trunc([[1.23456789, 2.3456789], [3.456789, 4.56789]])"]}},floor:{evaluate:$e(e=>Math.floor(e)),arity:G(1),docs:{category:"math",returns:{type:["integer","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `floor` function returns the largest `integer` less than or equal to a `number`, working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it returns the floor of each element while preserving the original structure.",seeAlso:["ceil","round","trunc"],examples:["floor(2)","floor(2.49)","floor(2.5)","floor(-2.49)","floor(-2.5)","floor(-2.501)","floor([1.23456789, 2.3456789])","floor([[1.23456789, 2.3456789], [3.456789, 4.56789]])"]}},ceil:{evaluate:$e(e=>Math.ceil(e)),arity:G(1),docs:{category:"math",returns:{type:["integer","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `ceil` function returns the smallest `integer` greater than or equal to a `number`, working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it returns the ceiling of each element while preserving the original structure.",seeAlso:["floor","round","trunc"],examples:["ceil(2)","ceil(2.49)","ceil(2.5)","ceil(-2.49)","ceil(-2.5)","ceil(-2.501)","ceil([1.23456789, 2.3456789])","ceil([[1.23456789, 2.3456789], [3.456789, 4.56789]])"]}},min:{evaluate:(e,t)=>{if(1===e.length&&xe(e[0])){const n=e[0];return ke(n,t),n.reduce((e,t)=>Math.min(e,t),1/0)}const[n,...r]=e;return J(n,t),r.reduce((e,n)=>(J(n,t),Math.min(e,n)),n)},arity:{min:1},docs:{category:"math",returns:{type:"number"},args:{a:{type:"number"},b:{type:"number"},xs:{type:"number",rest:!0},vector:{type:"vector"}},variants:[{argumentNames:["xs"]},{argumentNames:["vector"]}],description:"Returns the smallest value. Accepts either multiple numbers or a single vector of numbers.",seeAlso:["max","vector.span","vector.min-index"],examples:["2 min 3","min(2, 0, 1)","min(2, -1, 1)","min([2, 0, -1])","12 min 14"]}},max:{evaluate:(e,t)=>{if(1===e.length&&xe(e[0])){const n=e[0];return ke(n,t),n.reduce((e,t)=>Math.max(e,t),-1/0)}const[n,...r]=e;return J(n,t),r.reduce((e,n)=>(J(n,t),Math.max(e,n)),n)},arity:{min:1},docs:{category:"math",returns:{type:"number"},args:{a:{type:"number"},b:{type:"number"},xs:{type:"number",rest:!0},vector:{type:"vector"}},variants:[{argumentNames:["xs"]},{argumentNames:["vector"]}],description:"Returns the largest value. Accepts either multiple numbers or a single vector of numbers.",seeAlso:["min","vector.span","vector.max-index"],examples:["2 max 3","max(2, 0, 1)","max(2, -1, 1)","max([2, 0, -1])","4 max 2"]}},abs:{evaluate:$e(e=>Math.abs(e)),arity:G(1),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The abs function returns the absolute value (magnitude) of a `number`, working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it returns the absolute value of each element while preserving the original structure.",seeAlso:["sign","-"],examples:["abs(-2.3)","abs(0)","abs(2.5)","abs([1, -2, 3])","abs([[1, -2], [3, -4]])"]}},sign:{evaluate:$e(e=>Math.sign(e)),arity:G(1),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `sign` function returns the `sign` of a `number` (-1 for negative, 0 for zero, 1 for positive), working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it returns the sign of each element while preserving the original structure.",seeAlso:["abs"],examples:["sign(-2.3)","sign(-0)","sign(0)","sign(12312)","sign([1, -2, 3])","sign([[1, -2], [3, -4]])"]}}};function qe([e,...t],n){const r=E(e,n);for(const e of t)if(!ee(r,E(e,n),n))return!1;return!0}const Ce={"==":{evaluate:(e,t)=>qe(e,t),arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:"any"},b:{type:"any"},x:{type:"any"},ys:{type:"any",rest:!0}},variants:[{argumentNames:["x"]},{argumentNames:["x","ys"]}],description:"Returns `true` if all `values` are structaul equal to each other, otherwise result is `false`.",seeAlso:["!=","identical?"],examples:["1 == 1","[1, 2] == [1, 2]","\n{\n a: 1,\n b: 2,\n} == {\n b: 2,\n a: 1,\n}","==(1, 1)","==(1.01, 1)",'==("1", 1)','==("2", "2", "2", "2")',"==(2, 2, 1, 2)","==([1, 2], [1, 2])","==({ a: 1, b: 2 }, { b: 2, a: 1 })"]}},"!=":{evaluate:(e,t)=>!qe(e,t),arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:"any"},b:{type:"any"},x:{type:"any"},ys:{type:"any",rest:!0}},variants:[{argumentNames:["x"]},{argumentNames:["x","ys"]}],description:"Returns `true` if all `values` are not equal to each other, otherwise result is `false`. `(!= a b c)` is same as `(not (== a b c))`.",seeAlso:["==","identical?"],examples:["1 != 2","3 != 3","!=(3)","!=(3, 3, 2)",'!=("3", "2", "1", "0",)',"!=(0, -0)"]}},"identical?":{evaluate:e=>function([e,...t]){for(const n of t)if(n!==e)return!1;return!0}(e),arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:"any"},b:{type:"any"}},variants:[{argumentNames:["a","b"]}],description:"Returns true if $a and $b are referential equal.",seeAlso:["==","!="],examples:["identical?({ a: 10, b: 20 }, { b: 20, a: 10 })","identical?([1, true, null], [1, true, null])","identical?(0.3, 0.1 + 0.2)"]}},">":{evaluate:([e,...t],n)=>{let r=F(e);for(const e of t){if(Q(r,F(e),n)<=0)return!1;r=F(e)}return!0},arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:["number","string"]},b:{type:["number","string"]},x:{type:["number","string"]},ys:{type:["number","string"],rest:!0}},variants:[{argumentNames:["x"]},{argumentNames:["x","ys"]}],description:"Returns `true` if $x and $ys are in decreasing order, `false` otherwise.",seeAlso:["<",">=","<=","compare"],examples:[">(1, 0)",">(1.01, 1)",">(1, 1)",">(4, 3, 2, 1)",">(3, 2, 2, 1)"]}},"<":{evaluate:([e,...t],n)=>{let r=F(e);for(const e of t){if(Q(r,F(e),n)>=0)return!1;r=F(e)}return!0},arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:["number","string"]},b:{type:["number","string"]},x:{type:["number","string"]},ys:{type:["number","string"],rest:!0}},variants:[{argumentNames:["x"]},{argumentNames:["x","ys"]}],description:"Returns `true` if $x and $ys are in increasing order, `false` otherwise.",seeAlso:[">",">=","<=","compare"],examples:["<(0, 1)","<(1, 1.01)","<(1, 1)","<(1, 2, 2, 3)",'<("a", "b")']}},">=":{evaluate:([e,...t],n)=>{let r=F(e);for(const e of t){if(Q(r,F(e),n)<0)return!1;r=F(e)}return!0},arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:["number","string"]},b:{type:["number","string"]},x:{type:["number","string"]},ys:{type:["number","string"],rest:!0}},variants:[{argumentNames:["x"]},{argumentNames:["x","ys"]}],description:"Returns `true` if $x and $ys are in non increasing order, `false` otherwise.",seeAlso:[">","<","<=","compare"],examples:["1 >= 1","0 >= 1",">=(1, 0)",">=(1.01, 1)",">=(1, 1)",">=(4, 3, 2, 1)",">=(3, 2, 2, 1)"]}},"<=":{evaluate:([e,...t],n)=>{let r=F(e);for(const e of t){if(Q(r,F(e),n)>0)return!1;r=F(e)}return!0},arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:["number","string"]},b:{type:["number","string"]},x:{type:["number","string"]},ys:{type:["number","string"],rest:!0}},variants:[{argumentNames:["x"]},{argumentNames:["x","ys"]}],description:"Returns `true` if $x and $ys are in non decreasing order, `false` otherwise.",seeAlso:[">","<",">=","compare"],examples:["1 <= 1","<=(0, 1)","<=(1, 1.01)","<=(1, 1)","<=(1, 2, 3, 4)","<=(1, 2, 2, 3)"]}},not:{evaluate:([e])=>!e,arity:G(1),docs:{category:"misc",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Computes logical negation. Note that any other $x than `false`, `0`, `null` and `''` is truthy.",seeAlso:["boolean"],examples:["not(3)","not(true)",'not("A string")',"not(0)","not(false)","not(null)",'not("")']}},"epoch->iso-date":{evaluate:([e],t)=>(J(e,t),new Date(e).toISOString()),arity:G(1),docs:{category:"misc",returns:{type:"string"},args:{ms:{type:"number"}},variants:[{argumentNames:["ms"]}],description:"Returns IOS date time string from `ms` (milliseconds elapsed since the UNIX epoch).",seeAlso:["iso-date->epoch"],examples:["epoch->iso-date(1649756230899)","epoch->iso-date(0)"]}},"iso-date->epoch":{evaluate:([e],t)=>{B(e,t);const n=new Date(e).valueOf();return J(n,t,{finite:!0}),n},arity:G(1),docs:{category:"misc",returns:{type:"number"},args:{iso:{type:"string"}},variants:[{argumentNames:["iso"]}],description:"Returns milliseconds elapsed since the UNIX epoch to `iso`.",seeAlso:["epoch->iso-date"],examples:['iso-date->epoch("2022-04-12T09:37:10.899Z")','iso-date->epoch("1980-01-01")']}},boolean:{evaluate:([e])=>!!e,arity:G(1),docs:{category:"misc",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Coerces $x to boolean.",seeAlso:["not","boolean?","true?","false?"],examples:["boolean(0)","boolean(1)","boolean(null)",'boolean("Albert")']}},compare:{evaluate:([e,t],n)=>(L(e,n),L(t,n),Q(e,t,n)),arity:G(2),docs:{category:"misc",returns:{type:"number"},args:{a:{type:["number","string"]},b:{type:["number","string"]}},variants:[{argumentNames:["a","b"]}],description:"Compares two values. Returns `-1` if $a < $b, `1` if $a > $b and `0` if $a and $b have the same sort order.",seeAlso:["<",">","<=",">=","sort","sequence.sort-by"],examples:["compare(0, 1)","compare(0, 0)","compare(1, 0)",'compare("Albert", "Mojir")']}},"json-parse":{evaluate:([e],t)=>(B(e,t),JSON.parse(e)),arity:G(1),docs:{category:"misc",returns:{type:"any"},args:{x:{type:"string"}},variants:[{argumentNames:["x"]}],description:"Returns `JSON.parse(`$x`)`.",seeAlso:["json-stringify"],examples:['json-parse("[1, 2, 3]")']}},"json-stringify":{evaluate:([e,t],n)=>(N(e,n),void 0===t?JSON.stringify(e):(J(t,n),JSON.stringify(e,null,t))),arity:{min:1,max:2},docs:{category:"misc",returns:{type:"string"},args:{x:{type:"any"},indent:{type:"integer",description:"Number of spaces to use for indentation."}},variants:[{argumentNames:["x"]},{argumentNames:["x","indent"]}],description:"Returns `JSON.stringify(`$x`)`. If second argument is provided, returns `JSON.stringify(`$x`, null, `$indent`)`.",seeAlso:["json-parse"],examples:["json-stringify([1, 2, 3])","json-stringify({ a: { b: 10 }}, 2)"],hideOperatorForm:!0}},"effect-name":{evaluate:([e],t)=>function(e,t){return O(e,t),e}(e,t).name,arity:G(1),docs:{category:"meta",returns:{type:"string"},args:{e:{type:"any",description:"An effect reference."}},variants:[{argumentNames:["e"]}],description:"Returns the name of an effect reference as a string.",seeAlso:["effect-matcher","effect?"],examples:["effect-name(effect(dvala.error))","effect-name(effect(llm.complete))"]}},"effect-matcher":{evaluate:([e],t)=>{if("string"==typeof e)return{[u]:!0,sourceCodeInfo:t,functionType:"EffectMatcher",matchType:"string",pattern:e,flags:"",arity:G(1)};if(R(e))return{[u]:!0,sourceCodeInfo:t,functionType:"EffectMatcher",matchType:"regexp",pattern:e.s,flags:e.f,arity:G(1)};throw new n("effect-matcher expects a string or regexp pattern",t)},arity:G(1),docs:{category:"meta",returns:{type:"function"},args:{pattern:{type:["string","regexp"],description:"A wildcard pattern or regexp to match against effect names."}},variants:[{argumentNames:["pattern"]}],description:"Returns a predicate function that matches effects by name. If $pattern is a string, uses wildcard matching: no wildcard means exact match, `.*` suffix matches the prefix and all descendants (dot boundary enforced), and `*` alone matches everything. If $pattern is a regexp, tests the effect name against the regexp.",seeAlso:["effect-name","effect?"],examples:['let pred = effect-matcher("dvala.*"); pred(effect(dvala.error))','let pred = effect-matcher("dvala.*"); pred(effect(custom.foo))','let pred = effect-matcher("*"); pred(effect(anything))']}},"type-of":{evaluate:([e])=>null==e?"null":"boolean"==typeof e?"boolean":"number"==typeof e?"number":"string"==typeof e?"string":T(e)?"effect":R(e)?"regexp":w(e)?"function":Array.isArray(e)?"array":"object",arity:G(1),docs:{category:"misc",returns:{type:"string"},args:{x:{type:"any",description:"The value to inspect."}},variants:[{argumentNames:["x"]}],description:'Returns a string representing the type of $x. Possible return values are `"number"`, `"string"`, `"boolean"`, `"null"`, `"array"`, `"object"`, `"function"`, `"regexp"`, and `"effect"`.',seeAlso:["number?","string?","boolean?","null?","array?","object?","function?","regexp?","effect?"],examples:["type-of(42)",'type-of("hello")',"type-of(true)","type-of(null)","type-of([1, 2, 3])","type-of({ a: 1 })","type-of((x) -> x + 1)",'type-of(regexp("^start"))',"type-of(effect(dvala.io.println))"]}}},Re={keys:{evaluate:([e],t)=>(j(e,t),Object.keys(e)),arity:G(1),docs:{category:"object",returns:{type:"any",array:!0},args:{obj:{type:"object"}},variants:[{argumentNames:["obj"]}],description:"Returns array of all keys in $obj.",seeAlso:["vals","entries","zipmap","select-keys"],examples:["keys({})",'keys({ x: 10, y: true, z: "A string" })','keys(object("x", 10, "y", true, "z", "A string"))']}},vals:{evaluate:([e],t)=>(j(e,t),Object.values(e)),arity:G(1),docs:{category:"object",returns:{type:"any",array:!0},args:{obj:{type:"object"}},variants:[{argumentNames:["obj"]}],description:"Returns array of all values in $obj.",seeAlso:["keys","entries","zipmap"],examples:["vals({})",'vals({ x: 10, y: true, z: "A string" })','vals(object("x", 10, "y", true, "z", "A string"))']}},entries:{evaluate:([e],t)=>(j(e,t),Object.entries(e)),arity:G(1),docs:{category:"object",returns:{type:"array"},args:{obj:{type:"object"}},variants:[{argumentNames:["obj"]}],description:"Returns nested array of all key - value pairs in $obj.",seeAlso:["keys","vals","zipmap","find"],examples:["entries({})",'entries({ x: 10, y: true, z: "A string" })','entries(object("x", 10, "y", true, "z", "A string"))']}},find:{evaluate:([e,t],n)=>(j(e,n),B(t,n),Z(e,t)?[t,e[t]]:null),arity:G(2),docs:{category:"object",returns:{type:["array","null"]},args:{a:{type:"object"},b:{type:"string"},obj:{type:"object"},key:{type:"string"}},variants:[{argumentNames:["obj","key"]}],description:"Returns entry (key-value pair) for $key, or `null` if $key not present in $obj.",seeAlso:["get","contains?","entries","sequence.position","some"],examples:['{ a: 1, "b": 2 } find "a"','find(object("a", 1, "b", 2), "b")','find(object("a", 1, "b", 2), "c")']}},dissoc:{evaluate:([e,t],n)=>{j(e,n),B(t,n);const r={...e};return delete r[t],r},arity:G(2),docs:{category:"object",returns:{type:"object"},args:{a:{type:"object"},b:{type:"string"},obj:{type:"object"},key:{type:"string"}},variants:[{argumentNames:["obj","key"]}],description:"Return shallow copy of $obj with $key deleted.",seeAlso:["assoc","select-keys"],examples:['{ x: 10, y: 20 } dissoc "y"','dissoc({ x: 10, y: 20 }, "x")','dissoc({ x: 10 }, "y")','\nlet o = { a: 5 };\ndissoc(o, "a");\no']}},merge:{evaluate:(e,t)=>{if(0===e.length)return null;const[n,...r]=e;return j(n,t),r.reduce((e,n)=>(j(n,t),{...e,...n}),{...n})},arity:{min:0},docs:{category:"object",returns:{type:"object"},args:{a:{type:"object"},b:{type:"object"},objs:{type:"object",rest:!0}},variants:[{argumentNames:["objs"]}],description:"Returns a new object created by merging together all arguments.\n\nIf two keys appears in more than one object the value from the last object is used.\nIf no arguments are provided `null` is returned.",seeAlso:["merge-with","assoc"],examples:["{ x: 10 } merge { y: 20 }",'merge(object("x", 10), object("y", 20))','merge(object("x", 10), object("x", 15, "y", 20))']}},"merge-with":{evaluate:()=>{throw new Error("merge-with is implemented in Dvala")},arity:{min:2},docs:{category:"object",returns:{type:"object"},args:{objs:{type:"object",rest:!0},fun:{type:"function"}},variants:[{argumentNames:["objs","fun"]}],description:"\nReturns a new object created by merging together all arguments.\nIf two keys appears in more than one object $fun is used to calculate the new value.\n\nIf no arguments are provided `null` is returned.",seeAlso:["merge"],examples:['merge-with(object("x", 10), object("y", 20), +)','merge-with(object("x", 10), object("x", 15, "y", 20), +)',"merge-with({ x: 10 }, { x: 20 }, { x: 30 }, { x: 40 }, -)"],hideOperatorForm:!0}},zipmap:{evaluate:([e,t],n)=>{ie(e,n),oe(t,n);const r=Math.min(e.length,t.length),a={};for(let s=0;s<r;s+=1){a[D(e[s],n)]=te(t[s])}return a},arity:G(2),docs:{category:"object",returns:{type:"object"},args:{a:{type:"array"},b:{type:"array"}},variants:[{argumentNames:["a","b"]}],description:"Returns a new object created by mapping $a to $b.",seeAlso:["entries","keys","vals","sequence.interleave"],examples:['["a", "b", "c"] zipmap [1, 2, 3]','zipmap(["a", "b", "c"], [10, null, [1, 2, 3]])','zipmap(["a", "b", "c"], [1])',"zipmap([], [10, null, [1, 2, 3]])"]}},"select-keys":{evaluate:([e,t],n)=>(ie(t,n),j(e,n),t.reduce((t,n)=>(Z(e,n)&&(t[n]=te(e[n])),t),{})),arity:G(2),docs:{category:"object",returns:{type:"object"},args:{a:{type:"object"},b:{type:"array"}},variants:[{argumentNames:["a","b"]}],description:"Returns an object containing only those entries in $a whose key is in $b.",seeAlso:["dissoc","keys"],examples:['{ a: 1, b: 2, c: 3 } select-keys ["a", "b"]','select-keys({ a: 1, b: 2, c: 3 }, ["a", "b"])','select-keys({ a: 1 }, ["a", "b"])']}}},Pe={"function?":{evaluate:([e])=>w(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a function, otherwise `false`.",seeAlso:["string?","number?","boolean?","null?","array?","object?","regexp?","type-of"],examples:["function?(+)","function?(/)","function?((x, y) -> x + y)","function?(false)",'function?("false")',"function?([1, 2, 3])"]}},"string?":{evaluate:([e])=>"string"==typeof e,arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a string, otherwise `false`.",seeAlso:["blank?","number?","boolean?","null?","array?","object?","regexp?","function?","collection?","sequence?","type-of"],examples:['string?("")','string?("A string")','string?(true ? "A string" : false)',"string?(false)","string?([1, 2, 3])","string?(100)"]}},"number?":{evaluate:([e])=>"number"==typeof e,arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a number, otherwise `false`.",seeAlso:["integer?","zero?","pos?","neg?","finite?","number","string?","boolean?","null?","function?","type-of"],examples:["number?(0)","number?(2)","number?(-0.12)","number?(false)","number?([1, 2, 3])",'number?("A string")']}},"integer?":{evaluate:([e])=>"number"==typeof e&&W(e,{integer:!0}),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is an integer, otherwise `false`.",seeAlso:["number?","number","even?","odd?"],examples:["integer?(0)","integer?(-12)","integer?(42)","integer?(10.1)","integer?((x, y) -> x + y)","integer?(false)",'integer?("false")',"integer?([1, 2, 3])"]}},"boolean?":{evaluate:([e])=>"boolean"==typeof e,arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a `boolean`, otherwise `false`.",seeAlso:["true?","false?","boolean","string?","number?","null?","function?","type-of"],examples:["boolean?(true)","boolean?(false)","boolean?([1, 2, 3])","boolean?(0)",'boolean?("A string")']}},"null?":{evaluate:([e])=>null==e,arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is `null`, otherwise `false`.",seeAlso:["empty?","not-empty?","string?","number?","boolean?","function?","type-of"],examples:["null?(null)","null?(false)","null?([1, 2, 3])","null?(0)",'null?("A string")']}},"zero?":{evaluate:([e],t)=>(J(e,t,{finite:!0}),Math.abs(e)<ae),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is `0`, otherwise `false`.",seeAlso:["pos?","neg?","even?","number?"],examples:["zero?(0)","zero?(-0.0)","zero?(1)","zero?(0.1)"]}},"pos?":{evaluate:([e],t)=>(J(e,t,{finite:!0}),e>0),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is greater than `0`, otherwise `false`.",seeAlso:["neg?","zero?","number?"],examples:["pos?(0)","pos?(-0.0)","pos?(1)","pos?(-0.1)"]}},"neg?":{evaluate:([e],t)=>(J(e,t,{finite:!0}),e<0),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is less than `0`, otherwise `false`.",seeAlso:["pos?","zero?","number?"],examples:["neg?(0)","neg?(-0.0)","neg?(1)","neg?(-0.1)"]}},"even?":{evaluate:([e],t)=>(J(e,t,{finite:!0}),e%2==0),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is even, otherwise `false`.",seeAlso:["odd?","integer?","zero?"],examples:["even?(0)","even?(-0.0)","even?(-1)","even?(2.1)"]}},"odd?":{evaluate:([e],t)=>(J(e,t,{finite:!0}),W(e,{integer:!0})&&e%2!=0),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is odd, otherwise `false`.",seeAlso:["even?","integer?"],examples:["odd?(1.0)","odd?(1.001)","odd?(-1)","odd?(2.1)"]}},"array?":{evaluate:([e])=>Array.isArray(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is an array, otherwise `false`.",seeAlso:["sequence?","collection?","object?","string?","vector?","matrix?","grid?","function?","type-of"],examples:["array?([])","array?([1, 2, 3])",'array?(object("a", 10))',"array?(42)","array?(10.1)","array?((x, y) -> x + y)"]}},"collection?":{evaluate:([e])=>q(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a collection i.e. an array, an object or a string, otherwise `false`.",seeAlso:["sequence?","array?","object?","string?"],examples:["collection?([])","collection?([1, 2, 3])",'collection?(object("a", 10))','collection?("Albert")',"collection?(42)","collection?(10.1)","collection?((x, y) -> x + y)"]}},"sequence?":{evaluate:([e])=>$(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a sequence i.e. an array or a string, otherwise `false`.",seeAlso:["collection?","array?","string?"],examples:["sequence?([])","sequence?([1, 2, 3])",'sequence?(object("a", 10))','sequence?("Albert")',"sequence?(42)","sequence?(10.1)","sequence?((x, y) -> x + y)"]}},"object?":{evaluate:([e])=>I(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is an object, otherwise `false`.",seeAlso:["collection?","array?","string?","function?","type-of"],examples:['object?(object("a", 10))',"object?(42)","object?(10.1)","object?((x, y) -> x + y)",'object?(#"^start")','object?("false")',"object?([1, 2, 3])"]}},"regexp?":{evaluate:([e])=>R(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a regexp, otherwise `false`.",seeAlso:["regexp","re-match","string?","function?","type-of"],examples:['regexp?(regexp("^start"))','regexp?(#"^start")',"regexp?(-12)","regexp?({})","regexp?(10.1)","regexp?((x, y) -> x + y)","regexp?(false)",'regexp?("false")',"regexp?([1, 2, 3])"]}},"effect?":{evaluate:([e])=>T(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is an effect, otherwise `false`.",seeAlso:["effect","effect-name","effect-matcher","perform","type-of"],examples:["effect?(effect(dvala.io.println))","effect?(42)",'effect?("hello")',"effect?(null)","effect?({})","effect?([1, 2, 3])"]}},"finite?":{evaluate:([e],t)=>(J(e,t),Number.isFinite(e)),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is finite, otherwise `false`.",seeAlso:["positive-infinity?","negative-infinity?","number?"],examples:["finite?(1.0)","finite?(1 / 0)","finite?(-1 / 0)"]}},"positive-infinity?":{evaluate:([e],t)=>(J(e,t),e===Number.POSITIVE_INFINITY),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x equals positive infinity, otherwise `false`.",seeAlso:["negative-infinity?","finite?"],examples:["positive-infinity?(1.0)","positive-infinity?(1 / 0)","positive-infinity?(-1 / 0)"]}},"negative-infinity?":{evaluate:([e],t)=>(J(e,t),e===Number.NEGATIVE_INFINITY),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x equals negative infinity, otherwise `false`.",seeAlso:["positive-infinity?","finite?"],examples:["negative-infinity?(1.0)","negative-infinity?(1 / 0)","negative-infinity?(-1 / 0)"]}},"true?":{evaluate:([e])=>!0===e,arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is `true`, otherwise `false`.",seeAlso:["false?","boolean?","boolean"],examples:["true?(false)","true?(true)","true?(1)","true?(0)"]}},"false?":{evaluate:([e])=>!1===e,arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is `true`, otherwise `false`.",seeAlso:["true?","boolean?","boolean"],examples:["false?(false)","false?(true)","false?(1)","false?(0)"]}},"empty?":{evaluate:([e],t)=>null===e||(C(e,t),"string"==typeof e||Array.isArray(e)?0===e.length:0===Object.keys(e).length),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:["collection","string","null"]}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is empty or `null`, otherwise `false`.",seeAlso:["not-empty?","collection.not-empty","null?","blank?","count"],examples:["empty?([])","empty?([1, 2, 3])","empty?({})","empty?({ a: 2 })",'empty?("")','empty?("Albert")',"empty?(null)"]}},"not-empty?":{evaluate:([e],t)=>null!==e&&(C(e,t),"string"==typeof e||Array.isArray(e)?e.length>0:Object.keys(e).length>0),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:["collection","string","null"]}},variants:[{argumentNames:["x"]}],description:"Returns `false` if $x is empty or `null`, otherwise `true`.",seeAlso:["empty?","collection.not-empty","null?"],examples:["not-empty?([])","not-empty?([1, 2, 3])","not-empty?({})","not-empty?({ a: 2 })",'not-empty?("")','not-empty?("Albert")',"not-empty?(null)"]}},"vector?":{evaluate:([e])=>xe(e),arity:G(1),docs:{category:"predicate",description:"Checks if a value is a `vector`. A `vector` is an array of `numbers`.",seeAlso:["matrix?","grid?","array?"],returns:{type:"boolean"},args:{value:{type:"any",description:"The value to check."}},variants:[{argumentNames:["value"]}],examples:["vector?(1)","vector?([1, 2, 3])",'vector?([1, 2, "3"])']}},"matrix?":{evaluate:([e])=>Ee(e),arity:G(1),docs:{category:"predicate",description:"Checks if a value is a `matrix`. A `matrix` is an array of arrays of `numbers`.",seeAlso:["vector?","grid?","array?"],returns:{type:"boolean"},args:{value:{type:"any",description:"The value to check."}},variants:[{argumentNames:["value"]}],examples:["matrix?(1)","matrix?([1, 2, 3])","matrix?([[1, 2], [3, 4]])",'matrix?([[1, 2], [3, "4"]])',"matrix?([[1, 2], [3]])"]}},"grid?":{evaluate:([e])=>Ae(e),arity:G(1),docs:{category:"predicate",description:"Checks if a `value` is a `grid`. A `grid` is an `array` of `arrays` where all inner `arrays` have the same length.",seeAlso:["vector?","matrix?","array?"],returns:{type:"boolean"},args:{value:{type:"any",description:"The value to check."}},variants:[{argumentNames:["value"]}],examples:['grid?("1")','grid?(["1", 2, 3])','grid?([["1", 2], [3, 4]])','grid?([["1", 2], [3, "4"]])','grid?([["1", 2], [3]])']}}},Te={regexp:{evaluate:([e,t],r)=>{B(e,r);const a=e||"(?:)",s="string"==typeof t?t:"";try{new RegExp(a,s)}catch(e){throw new n(`Invalid regular expression: ${a} ${s}`,r)}return{[p]:!0,sourceCodeInfo:r,s:a,f:s}},arity:{min:1,max:2},docs:{category:"regular-expression",returns:{type:"regexp"},args:{pattern:{type:"string"},flags:{type:"string",description:"Optional flags for the regular expression. Possible values are the same as Javascript RegExp takes."}},variants:[{argumentNames:["pattern"]},{argumentNames:["pattern","flags"]}],description:"Creates a RegExp from $pattern and $flags.",examples:['regexp("^\\s*(.*)$")','#"^\\s*(.*)$"','regexp("albert", "ig")','#"albert"ig'],seeAlso:["-short-regexp","re-match","replace","replace-all","regexp?"],hideOperatorForm:!0}},"re-match":{evaluate:([e,t],n)=>{if(function(e,t){if(!R(e))throw h("RegularExpression",e,t)}(t,n),!U(e))return null;const r=new RegExp(t.s,t.f).exec(e);return r?[...r]:null},arity:G(2),docs:{category:"regular-expression",returns:{type:"any"},args:{a:{type:"regexp"},b:{type:"string"}},variants:[{argumentNames:["a","b"]}],description:"Matches $b against regular expression $a.\nIf $b is a string and matches the regular expression, a `re-match`-array is returned, otherwise `null` is returned.",seeAlso:["regexp","replace","replace-all","-short-regexp","regexp?"],examples:['re-match(" A string", regexp("^\\\\s*(.*)$"))','re-match(" A string", #"^\\s*(.*)$")','re-match("My name is Albert", #"albert"i)','re-match("My name is Ben", #"albert"i)','re-match(null, #"albert"i)','re-match(1, #"albert"i)','re-match({}, #"albert"i)']}},replace:{evaluate:([e,t,n],r)=>{B(e,r),P(t,r),B(n,r);const a=R(t)?new RegExp(t.s,`${t.f}`):t;return e.replace(a,n)},arity:G(3),docs:{category:"regular-expression",returns:{type:"string"},args:{a:{type:"string"},b:{type:["regexp","string"]},x:{type:"string"}},variants:[{argumentNames:["a","b","x"]}],description:"Returns a new string with first match of regular expression $b replaced by $x.",seeAlso:["replace-all","regexp","re-match","-short-regexp"],examples:['replace("Duck duck", "u", "i")','replace("Duck duck", #"u", "i")','replace("abcABC", regexp("a", "i"), "-")','replace("abcABC", regexp("a", "gi"), "-")','replace("abcABC", #"a"i, "-")','replace("abcABC", #"a"gi, "-")']}},"replace-all":{evaluate:([e,t,n],r)=>{B(e,r),P(t,r),B(n,r);const a=R(t)?new RegExp(t.s,`${t.f.includes("g")?t.f:`${t.f}g`}`):t;return e.replaceAll(a,n)},arity:G(3),docs:{category:"regular-expression",returns:{type:"string"},args:{a:{type:"string"},b:{type:["regexp","string"]},x:{type:"string"}},variants:[{argumentNames:["a","b","x"]}],description:"Returns a new string with all matches of regular expression $b replaced by $x.",seeAlso:["replace","regexp","re-match","-short-regexp"],examples:['replace-all("Duck duck", "u", "i")','replace-all("Duck duck", regexp("u"), "i")','replace-all("abcABC", regexp("a", "i"), "-")','replace-all("abcABC", regexp("a", "gi"), "-")','replace-all("abcABC", #"a"i, "-")','replace-all("abcABC", #"a"gi, "-")']}}},Oe=/^\s*$/,Me={str:{evaluate:e=>e.reduce((e,t)=>e+(null==t?"":I(t)||Array.isArray(t)?JSON.stringify(t):`${t}`),""),arity:{},docs:{category:"string",returns:{type:"string"},args:{values:{type:"any",rest:!0}},variants:[{argumentNames:["values"]}],description:"Concatenats $values into one string. If `value` equals `null` empty string is returned.",seeAlso:["++","join","string.template","string.string-repeat","number"],examples:['str("A string", ", and another string", " ...and more")','str("Just one string")',"str()",'str(0, false, true, null, #"^kalle", [1, 2, 3], {a: "a"})'],hideOperatorForm:!0}},number:{evaluate:([e],t)=>{B(e,t);const r=Number(e);if(Number.isNaN(r))throw new n(`Could not convert '${e}' to a number.`,t);return r},arity:G(1),docs:{category:"string",returns:{type:"number"},args:{s:{type:"string"}},variants:[{argumentNames:["s"]}],description:"Parses $s to a number.",seeAlso:["str","number?","integer?"],examples:['number("10")','number("010")','number("-1.01")']}},"lower-case":{evaluate:([e],t)=>(B(e,t),e.toLowerCase()),arity:G(1),docs:{category:"string",returns:{type:"string"},args:{s:{type:"string"}},variants:[{argumentNames:["s"]}],description:"Returns $s converted to lower case.",seeAlso:["upper-case","string.capitalize"],examples:['lower-case("Albert")','lower-case("")']}},"upper-case":{evaluate:([e],t)=>(B(e,t),e.toUpperCase()),arity:G(1),docs:{category:"string",returns:{type:"string"},args:{s:{type:"string"}},variants:[{argumentNames:["s"]}],description:"Returns $s converted to upper case.",seeAlso:["lower-case","string.capitalize"],examples:['upper-case("Albert")','upper-case("")']}},trim:{evaluate:([e],t)=>(B(e,t),e.trim()),arity:G(1),docs:{category:"string",returns:{type:"string"},args:{s:{type:"string"}},variants:[{argumentNames:["s"]}],description:"Returns a new string with leading and trailing whitespaces removed.",seeAlso:["string.trim-left","string.trim-right","blank?"],examples:['trim(" Albert ")','trim(" ")','trim("")']}},join:{evaluate:([e,t],n)=>(oe(e,n),e.forEach(e=>L(e,n)),B(t,n),e.join(t)),arity:G(2),docs:{category:"string",returns:{type:"string"},args:{a:{type:"array"},b:{type:"string"},arr:{type:"array"},delimiter:{type:"string"}},variants:[{argumentNames:["arr","delimiter"]}],description:"Returns a new string by concatenating all of the elements in $arr, separated by $delimiter.",seeAlso:["split","str","++","sequence.interpose"],examples:['map([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], str) join ", "','([0, 1, 2, 3, 4, 5, 6, 7, 8, 9] map str) join ", "','join(["Albert", 10], ", ")','join(["Albert", "Mojir"], " ")','join(map([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], str), ", ")']}},split:{evaluate:([e,t,n],r)=>{B(e,r),P(t,r),void 0!==n&&J(n,r,{integer:!0,nonNegative:!0});const a="string"==typeof t?t:new RegExp(t.s,t.f);return e.split(a,n)},arity:{min:2,max:3},docs:{category:"string",returns:{type:"string",array:!0},args:{a:{type:"string"},b:{type:"string"},s:{type:"string"},delimiter:{type:"string"},limit:{type:"integer"}},variants:[{argumentNames:["s","delimiter"]},{argumentNames:["s","delimiter","limit"]}],description:"Divides $s into an array of substrings. The division is done by searching for `delimiter`. If `limit` as provided, at most `limit` number of substrings are returned.",seeAlso:["join","string.split-lines"],examples:['"Albert Mojir" split " "','split("Albert Mojir", " ")','split("abcdefghijklmnopqrstuvw", #"[aoueiy]")','split("0123456789", "")','split("0123456789", "", 5) map number']}},"blank?":{evaluate:([e],t)=>null===e||(B(e,t),Oe.test(e)),arity:G(1),docs:{category:"string",returns:{type:"boolean"},args:{s:{type:["string","null"]}},variants:[{argumentNames:["s"]}],description:"Returns true if $s is null or only contains whitespace characters.",seeAlso:["trim","empty?","string?"],examples:['blank?("")',"blank?(null)",'blank?("\n")','blank?(" ")','blank?(".")']}}},Ve={"|>":{evaluate:()=>{throw new Error("|> is implemented in Dvala")},arity:G(2),docs:{category:"functional",returns:{type:"any"},args:{a:{type:"any"},b:{type:"function"}},variants:[{argumentNames:["a","b"]}],description:"Takes a value $a and a function $b, and returns the result of applying $b to $a.",seeAlso:["apply","comp"],examples:["\n1 |> inc |> inc","range(10)\n |> map(_, -> $ ^ 2) // [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n |> filter(_, odd?) // [1, 9, 25, 49, 81]\n |> reduce(_, +, 0) // 165\n |> sqrt // 12.84523257866513\n |> round(_, 2)"]}},apply:{evaluate:()=>{throw new Error("apply is implemented in Dvala")},arity:{min:2},docs:{category:"functional",returns:{type:"any"},args:{a:{type:"function"},b:{type:"array"},fun:{type:"function"},args:{type:"array"}},variants:[{argumentNames:["fun","args"]}],description:"Call supplied function $fun with specified arguments $args.",seeAlso:["|>"],examples:["\napply(+, [1, 2, 3])","\napply(\n (x, y) -> sqrt(x ^ 2 + y ^ 2),\n [3, 4]\n)","\n(x, y) -> sqrt(x ^ 2 + y ^ 2) apply [3, 4]"]}},identity:{evaluate:([e])=>te(e),arity:G(1),docs:{category:"functional",returns:{type:"any"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns $x.",seeAlso:["constantly","functional.fnull"],examples:["identity(1)",'identity("Albert")',"identity({ a: 1 })","identity(null)"]}},comp:{evaluate:(e,t)=>{return e.forEach(e=>V(e,t)),{[u]:!0,sourceCodeInfo:t,functionType:"Comp",params:e,arity:e.length>0?(n=e.at(-1),"number"==typeof n||q(n)?G(1):n.arity):{min:1,max:1}};var n},arity:{},docs:{category:"functional",returns:{type:"function"},args:{a:{type:"function"},b:{type:"function"},fns:{type:"function",rest:!0}},variants:[{argumentNames:["fns"]}],description:"Takes a variable number of functions and returns a function that is the composition of those.\n\n The returned function takes a variable number of arguments,\n applies the rightmost function to the args,\n the next function (right-to-left) to the result, etc.",seeAlso:["|>","functional.juxt","functional.complement"],examples:["\nlet negative-quotient = comp(-, /);\nnegative-quotient(9, 3)",'\nlet x = { bar: { foo: 42 } };\ncomp("foo", "bar")(x)']}},constantly:{evaluate:([e],t)=>({[u]:!0,sourceCodeInfo:t,functionType:"Constantly",value:te(e),arity:{}}),arity:G(1),docs:{category:"functional",returns:{type:"function"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns a function that takes any number of arguments and always returns $x.",seeAlso:["identity","functional.fnull"],examples:["\nlet always-true = constantly(true);\nalways-true(9, 3)"]}}};function Ue(e){return se(`\n ${e.title}\n\n ${e.description.replace(/`(.+?)`/g,"$1").replace(/\$(\w+)/g,"$1").replace(/\*\*\*(.+)\*\*\*/g,"$1").replace(/\*\*(.+)\*\*/g,"$1")}\n\n Signature:\n ${function(e){const{title:t,variants:n,args:r,returns:a}=e,s=!Be(e)&&e._isOperator,o=n.map(n=>{if(Be(e)){const e=n.argumentNames.length>0?`, ${n.argumentNames.map(e=>{let t="";return r[e].rest&&(t+="..."),t+=e,t}).join(", ")}`:"";return` perform(effect(${t})${e}) -> ${De(a)}`}return`${` ${t}(${n.argumentNames.map(e=>{let t="";return r[e].rest&&(t+="..."),t+=e,t}).join(", ")})`} -> ${De(a)}`}),i=s?["","Operator:",` a ${t} b -> ${De(a)}`]:[];return[...o,...i]}(e).join("\n ")}\n\n Arguments:\n ${function(e){return Object.entries(e.args).map(([e,t])=>`${e}: ${De(t)}`)}(e).join("\n ")}\n\n Examples:\n${e.examples.map(e=>se(e,4)).join("\n\n")}`)}function Be(e){return"effect"in e}function De(e){const t=e.type,n=(Array.isArray(t)?t:[t]).join(" | ");return e.array||e.rest?`Array<${n}>`:n}const _e={sum:{evaluate:([e],t)=>(we(e,t),e.reduce((e,t)=>e+t,0)),arity:G(1),docs:{category:"vector",returns:{type:"number"},args:{vector:{type:"vector",description:"The vector to sum."}},variants:[{argumentNames:["vector"]}],description:"Returns the **sum** of all elements in the `vector`. Returns `0` for an empty vector.",seeAlso:["prod","mean","median","vector.moving-sum","vector.centered-moving-sum","vector.running-sum","vector.cumsum"],examples:["sum([1, 2, 3, 4, 5])","sum([1, -2, 3])","sum([])"]}},prod:{evaluate:([e],t)=>(we(e,t),e.reduce((e,t)=>e*t,1)),arity:G(1),docs:{category:"vector",returns:{type:"number"},args:{vector:{type:"vector",description:"The vector to multiply."}},variants:[{argumentNames:["vector"]}],description:"Returns the **product** of all elements in the `vector`. Returns `1` for an empty vector.",seeAlso:["sum","mean","median","vector.moving-prod","vector.centered-moving-prod","vector.running-prod","vector.cumprod"],examples:["prod([1, 2, 3, 4, 5])","prod([1, -2, 3])","prod([])"]}},mean:{evaluate:([e],t)=>(ke(e,t),e.reduce((e,t)=>e+t,0)/e.length),arity:G(1),docs:{category:"vector",returns:{type:"number"},args:{vector:{type:"vector",description:"The vector to calculate the mean of."}},variants:[{argumentNames:["vector"]}],description:"Returns the arithmetic **mean** of all elements in the `vector`. Throws for an empty vector.",seeAlso:["median","sum","prod","vector.moving-mean","vector.centered-moving-mean","vector.running-mean","vector.geometric-mean","vector.harmonic-mean","vector.rms","vector.mode"],examples:["mean([1, 2, 3, 4, 5])","mean([1, -2, 3])"]}},median:{evaluate:([e],t)=>(ke(e,t),function(e){const t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2==0?(t[n-1]+t[n])/2:t[n]}(e)),arity:G(1),docs:{category:"vector",returns:{type:"number"},args:{vector:{type:"vector",description:"The vector to calculate the median of."}},variants:[{argumentNames:["vector"]}],description:"Returns the **median** of all elements in the `vector`. For even-length vectors, returns the average of the two middle values. Throws for an empty vector.",seeAlso:["mean","sum","prod","vector.moving-median","vector.centered-moving-median","vector.running-median","vector.mode","vector.quartiles","vector.percentile","vector.iqr","vector.medad"],examples:["median([1, 2, 3, 4, 5])","median([1, 2, 3, 4])","median([3, 1, 4, 1, 5])"]}}},Fe={...z,...H,...ce,...ue,...pe,...je,...function(e,t){return{doc:{evaluate:([n],r)=>{if(b(e),T(n)){const e=`-effect-${n.name}`,r=t[e];return r?Ue(r):""}if(V(n,r),!w(n))return"";if("Builtin"===n.functionType){const t=e[n.name];return t?Ue(t):""}return"UserDefined"===n.functionType?n.docString:""},arity:G(1),docs:{category:"meta",returns:{type:"string"},args:{value:{type:["function","effect"]}},variants:[{argumentNames:["value"]}],description:"Returns documentation string of the $value. Works on functions and effects.",seeAlso:["arity"],examples:["doc(+)","doc(effect(dvala.io.println))",'\nlet add = (x, y) -> do\n """\n Adds two numbers.\n Args:\n x: First number.\n y: Second number.\n Returns:\n Sum of x and y.\n """;\n x + y;\nend;\n\ndoc(add)']}},arity:{evaluate:([e],n)=>{if(T(e)){const n=`-effect-${e.name}`,r=t[n];if(!r)return{};const a=r.variants.map(e=>e.argumentNames.length);return{min:Math.min(...a),max:Math.max(...a)}}return V(e,n),w(e)?e.arity:G(1)},arity:G(1),docs:{category:"meta",returns:{type:"object"},args:{value:{type:["function","effect"]}},variants:[{argumentNames:["value"]}],description:"Returns arity of the $value. The arity is an object with the properties: `min` and `max`. If the function has fixed arity, `min` and `max` are equal to the number of required parameters. If no restrictions apply, empty object is returned. Also works on effects.",seeAlso:["doc"],examples:["arity(+)","arity(defined?)","arity(effect(dvala.random.int))","\nlet add = (x, y = 0) -> do\n x + y;\nend;\n\narity(add)","\nlet foo = (k, ...x) -> do\n k + x;\nend;\n arity(foo)"]}}}}({},{}),...Ce,...Re,...Pe,...Te,...Me,...Ve,..._e};Object.entries(Fe).forEach(([e,t])=>{t.name=e});const Le={...Fe},ze={},We=[];Object.entries(Le).forEach(([e,t],n)=>{ze[e]=n,We.push(t)});const Je={arity:{},docs:{category:"special-expression",returns:{type:"any"},args:{a:{type:"any"},b:{type:"any"},c:{type:"any",rest:!0}},variants:[{argumentNames:["a","b"]},{argumentNames:["a","b","c"]}],description:"\nComputes logical `and`. Evaluation of expressions starts from left.\nAs soon as an `expression` evaluates to a falsy value, the result is returned.\n\nIf all expressions evaluate to truthy values, the value of the last expression is returned.",examples:["true && 1","&&(1, 1)",'&&(3 > 2, "string")','&&(3 < 2, "string")',"&&(true, true, true, true)","&&(true, true, 0, true)"]},evaluateAsNormalExpression:(e,t)=>{let n=!0;for(const r of e)if(n=E(r,t),!n)break;return n},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1],t,r,a)},Ye={arity:{},docs:{category:"special-expression",customVariants:["cond cond-branch cond-branch ... end"],details:[["cond-branch","case test then body","A branch of the cond expression."],["test","expression","The condition to test."],["body","expressions","The expressions to evaluate if the test is truthy."]],description:"Used for branching. `cond-branches` are tested sequentially from the top. If no branch is tested truthy, `null` is returned.",examples:['\ncond\n case false then "FALSE"\n case true then "TRUE"\nend','\ncond\n case false then "FALSE"\n case null then "null"\nend ?? "TRUE"','\ncond\n case false then "FALSE"\n case null then "null"\nend ?? "TRUE"']},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1].flat(),t,r,a)},Ke=11,Ge=12,Xe=13,He=14,Ze=15,Qe=16;function et(e,t){return e instanceof Promise?e.then(t):t(e)}async function tt(e,t,n,r,a){t.push(await e);for(let e=a+1;e<n.length;e++)t.push(await r(n[e],e));return t}function nt(e,t,n){let r=n;for(let n=0;n<e.length;n++){const a=t(r,e[n],n);if(a instanceof Promise)return rt(a,e,t,n);r=a}return r}async function rt(e,t,n,r){let a=await e;for(let e=r+1;e<t.length;e++)a=await n(a,t[e],e);return a}function at(e,t){for(let n=0;n<e.length;n++){const r=t(e[n],n);if(r instanceof Promise)return st(r,e,t,n)}}async function st(e,t,n,r){await e;for(let e=r+1;e<t.length;e++)await n(t[e],e)}function ot(e,t){if(e[0]===Xe)Object.values(e[1][0]).forEach(e=>{e[1][1]&&t(e[1][1]),ot(e,t)});else if(e[0]===He)for(let n=0;n<e[1][0].length;n+=1){const r=e[1][0][n]??null;null!==r&&(r[1][1]&&t(r[1][1]),ot(r,t))}}function it(e,t,n){const r=e[2],a={};return et(lt(e,t,n,r,a),()=>a)}function lt(e,t,r,a,s){if(e[0]===Xe){!function(e,t){if(!x(e))throw new n(`Expected UnknownRecord, got ${y(e)}.`,g(e,t))}(t,a);const o=new Set;let i;return et(at(Object.entries(e[1][0]),([e,n])=>{if(n[0]===Ge)return void(i=n);o.add(e);const l=t[e];return et(void 0!==l?l:n[1][1]?r(n[1][1]):null,e=>{const t=e??null;return N(t,a),lt(n,t,r,a,s)})}),()=>{if(i){const e=Object.entries(t).filter(([e])=>!o.has(e)).reduce((e,[t,n])=>(e[t]=E(n),e),{});s[i[1][0]]=e}})}if(e[0]===He){let n=null;oe(t,a);const o=[];for(let t=0;t<e[1][0].length;t+=1){const r=e[1][0][t]??null;if(null!==r){if(r[0]===Ge){n=t;break}o.push({element:r,index:t})}}return et(at(o,({element:e,index:n})=>{const o=t[n];return et(void 0!==o?o:e[1][1]?r(e[1][1]):null,t=>{const n=t??null;return N(n,a),lt(e,n,r,a,s)})}),()=>{if(null!==n){const r=t.slice(n),a=e[1][0][n];s[a[1][0]]=r}})}e[0]===Ge?s[e[1][0]]=E(t):s[e[1][0][1]]=E(t)}function ct(e){const t={};return ut(e,t),t}function ut(e,t){if(null!==e)if(e[0]===He)for(const n of e[1][0])ut(n,t);else if(e[0]===Xe)for(const n of Object.values(e[1][0]))ut(n,t);else if(e[0]===Ge){if(t[e[1][0]])throw new n(`Duplicate binding name: ${e[1][0]}`,e[2]);t[e[1][0]]=!0}else if(e[0]===Ke){if(t[e[1][0][1]])throw new n(`Duplicate binding name: ${e[1][0]}`,e[2]);t[e[1][0][1]]=!0}}function pt(e,t,n){const r={};return et(ft(e,t,n,r),e=>e?r:null)}function ft(e,t,n,r){if(e[0]===Qe)return!0;if(e[0]===Ze){const r=e[1][0];return et(n(r),e=>ee(t,e))}if(e[0]===Ke){const a=e[1][0],s=e[1][1];if(null==t){if(s)return et(n(s),e=>(r[a[1]]=E(e),!0));r[a[1]]=t??null}else r[a[1]]=E(t);return!0}if(e[0]===Xe){if(!x(t))return!1;const a=new Set;let s;const o=Object.entries(e[1][0]);let i=!0;for(const[e,l]of o)i=et(i,o=>{if(!o)return!1;if(l[0]===Ge)return s=l,!0;a.add(e);const i=t[e];if(void 0===i&&l[0]===Ze)return et(n(l[1][0]),e=>ee(void 0,e));return et(void 0!==i?i:l[1]&&l[1][1]?n(l[1][1]):null,e=>ft(l,e??null,n,r))});return et(i,e=>{if(!e)return!1;if(s){const e=Object.entries(t).filter(([e])=>!a.has(e)).reduce((e,[t,n])=>(e[t]=E(n),e),{});r[s[1][0]]=e}return!0})}{const a=e;if(!Array.isArray(t))return!1;const s=a[1][0];let o=null;for(let e=0;e<s.length;e+=1){const t=s[e];if(null!==t&&t[0]===Ge){o=e;break}}if(null===o&&t.length!==s.length)return!1;if(null!==o&&t.length<o)return!1;let i=!0;for(let e=0;e<s.length;e+=1){const a=s[e];if(null===a)continue;if(a[0]===Ge){r[a[1][0]]=t.slice(e);break}const o=a;i=et(i,a=>!!a&&ft(o,E(t[e]),n,r))}return i}}const dt={arity:{},docs:{category:"special-expression",customVariants:["match value match-branch match-branch ... end"],details:[["value","any","The value to match against patterns."],["match-branch","case pattern [when guard] then body","A branch of the match expression."],["pattern","pattern","A pattern to match: literal, variable, array destructuring, object destructuring, or wildcard (_)."],["guard","expression","An optional guard expression that must be truthy for the match to succeed."],["body","expressions","The expressions to evaluate if the pattern matches."]],description:"Pattern matching expression. Matches `value` against each `pattern` sequentially. If a pattern matches (and the optional `when` guard is truthy), the corresponding `body` is evaluated and its result returned. Bound variables from the pattern are available in the guard and body. If no pattern matches, `null` is returned.",examples:['\nmatch 1\n case 1 then "One"\n case 2 then "Two"\nend','\nmatch [1, 2, 3]\n case [x] then "one element"\n case [x, y] then "two elements"\n case [x, ...xs] then "first: " ++ str(x) ++ " rest: " ++ str(xs)\nend','\nmatch { type: "click", x: 10, y: 20 }\n case { type: "click", x, y } then "Click at " ++ str(x) ++ ", " ++ str(y)\n case { type: "keydown", key } then "Key: " ++ key\n case _ then "unknown event"\nend','\nmatch { role: "admin", name: "Alice" }\n case { role: "admin", name } then "Admin: " ++ name\n case { role, name } when role == "user" then "User: " ++ name\n case _ then "Unknown role"\nend']},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>{const s=new Set;n([e[1][1]],t,r,a).forEach(e=>s.add(e));for(const[o,i,l]of e[1][2]){const e={};Object.assign(e,ct(o));const c=t.create(e);l&&n([l],c,r,a).forEach(e=>s.add(e)),n([i],c,r,a).forEach(e=>s.add(e))}return s}},mt={category:"special-expression",returns:{type:"boolean"},args:{symbol:{type:"any"}},variants:[{argumentNames:["symbol"]}],description:"Returns `true` if `symbol` is defined, `false` otherwise.\n\nBuilt-in symbols are always considered defined. For user-defined symbols, checks if the symbol exists in the current scope.",examples:["let x = 42; defined?(x)","defined?(x)","defined?(+)"]},yt={arity:G(1),docs:mt,getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n([e[1][1]],t,r,a)},gt={arity:{},docs:{category:"special-expression",customVariants:["do body end","do body with case effect(name) then handler end"],details:[["body","expressions","The expressions to evaluate."],["effect(name)","expression","An expression evaluating to an effect value."],["handler","expression","A function (args) -> result that handles the effect. Its return value resumes the perform call."]],description:"Evaluates `body`. Resulting value is the value of the last expression. Effect handlers can be installed via `with` to intercept `perform` calls.",examples:["\ndo\n let a = 1 + 2 + 3 + 4;\n let b = -> $ * ( $ + 1 );\n b(a)\nend",'\ndo\n perform(effect(dvala.io.println), "hello")\nwith\n case effect(dvala.io.println) then ([msg]) -> null\nend']},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>{const s=n(e[1][1],t.create({}),r,a),o=e[1][2];if(!o||0===o.length)return s;let i=new Set;for(const[e,s]of o){i=ne(i,n([e],t,r,a),n([s],t,r,a))}return ne(s,i)}},ht={arity:{},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>function(e,t,n,r,a){const s=new Set,o={self:{value:null}};e[0].forEach(e=>{Object.assign(o,ct(e)),ot(e,e=>{re(s,n([e],t,r,a))})});const i=t.create(o),l=n(e[1],i,r,a);return re(s,l),s}(e[1][1],t,n,r,a)};const vt={arity:{min:2,max:3},docs:{category:"special-expression",customVariants:["if test then true-expr else false-expr","if test then true-expr"],details:[["test","expression","The condition to test."],["true-expr","expression","The expression to evaluate if the test is truthy."],["false-expr","expression","The expression to evaluate if the test is falsy."]],description:"Either `true-expr` or `false-expr` branch is taken. `true-expr` is selected when $test is truthy. If $test is falsy `false-expr` is executed, if no `false-expr` exists, `null` is returned.",examples:['\nif true then\n "TRUE"\nelse\n "FALSE"\nend','if false then "TRUE" else "FALSE" end','if true then "TRUE" end','if false then "TRUE" end']},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1].filter(e=>!!e),t,r,a)},bt={arity:{},docs:{category:"special-expression",customVariants:["unless test then true-expr else false-expr end","unless test true-expr end"],details:[["test","expression","The condition to test."],["true-expr","expression","The expressions to evaluate if the test is falsy."],["false-expr","expression","The expressions to evaluate if the test is truthy."]],description:"Either `true-expr` or `false-expr` branch is taken. `true-expr` is selected when $test is falsy. If $test is truthy `false-expr` is executed, if no `false-expr` exists, `null` is returned.",examples:['\nunless true then\n "TRUE"\nelse\n "FALSE"\nend','unless false then "TRUE" else "FALSE" end','unless true then "TRUE" end','unless false then "TRUE" end']},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1].filter(e=>!!e),t,r,a)},xt={category:"special-expression",customVariants:["let s = value;"],details:[["s","symbol","The name of the variable to bind."],["value","any","The value to bind to the variable."]],description:"\n Binds local variables s to `value`. `value` can be any expression. The scope of the variables is the body of the let expression.",examples:["\nlet a = 1 + 2 + 3 + 4;\nlet b = -> $ * ( $ + 1 );\nb(a)"]},wt={arity:G(0),docs:xt,getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>{const s=e[1][1],o=s[1][0],i=s[1][1],l=n([i],t,r,a);return ot(o,e=>{re(l,n([e],t,r,a))}),t.addValues(ct(o),o[2]),l}},kt={arity:{},docs:{category:"special-expression",customVariants:["loop (bindings) -> body"],details:[["bindings","binding pairs","Comma-separated bindings with initial values, e.g. `n = 10, acc = 0`."],["body","expression","The expression to evaluate repeatedly. Use `recur` to loop back with new values."]],description:"Creates a loop with initial bindings. Use `recur` inside the body to jump back to the loop head with new binding values.\n\nIf `recur` is not called, the loop terminates and returns the value of the body expression.",examples:["loop (n = 10, acc = 0) -> do\n if n == 0 then\n acc\n else\n recur(n - 1, acc + n)\n end\nend","loop (n = 5, acc = 1) -> do\n if n <= 1 then\n acc\n else\n recur(n - 1, acc * n)\n end\nend"]},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>{const s=e[1][1],o=s.reduce((e,t)=>{const n=ct(t[1][0]);return Object.keys(n).forEach(t=>{e[t]={value:!0}}),e},{});return ne(n(s.map(e=>e[1][1]),t,r,a),n([e[1][2]],t.create(o),r,a))}};function At(e,t,n,r,a){const s=new Set,o={},[,i,l]=e[1];return i.forEach(e=>{const[i,l,c,u]=e,[p,f]=i[1];n([f],t.create(o),r,a).forEach(e=>s.add(e)),Object.assign(o,ct(p)),l&&l.forEach(e=>{const[i,l]=e[1];n([l],t.create(o),r,a).forEach(e=>s.add(e)),Object.assign(o,ct(i))}),c&&n([c],t.create(o),r,a).forEach(e=>s.add(e)),u&&n([u],t.create(o),r,a).forEach(e=>s.add(e))}),n([l],t.create(o),r,a).forEach(e=>s.add(e)),s}const Et={category:"special-expression",customVariants:["for (...binding) -> body"],details:[["binding","loop-var in collection [...let-binding] [where whereExpr] [while whileExp]","A for loop binding"],["loop-var","symbol","The name of the loop variable."],["collection","any","The collection to iterate over."],["let-binding","let binding","A let binding to create a local variable."],["whereExpr","expression","An expression that must evaluate to truthy for the loop body to be executed."],["whileExp","expression","An expression that must evaluate to truthy for the loop to continue."],["body","expressions","The expressions to evaluate for each iteration of the loop."]],returns:{type:"any",array:!0},description:"Iterates over `bindings`, evaluates `body` for each `binding` and returns an `array` of results.",examples:["\nfor (i in [1, 2, 3]) -> i * 2\n ","\nfor (\n i in range(10) let ii = i ^ 2 while ii < 40 when ii % 3 == 0,\n j in range(10) when j % 2 == 1\n) -> ii + j\n "]},Nt={arity:G(1),docs:Et,getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>At(e,t,n,r,a)},$t={category:"special-expression",customVariants:["doseq (...binding) -> body"],details:[["binding","loop-var in collection [...let-binding] [where whereExpr] [while whileExp]","A doseq loop binding"],["loop-var","symbol","The name of the loop variable."],["collection","any","The collection to iterate over."],["let-binding","let binding","A let binding to create a local variable."],["whereExpr","expression","An expression that must evaluate to truthy for the loop body to be executed."],["whileExp","expression","An expression that must evaluate to truthy for the loop to continue."],["body","expressions","The expressions to evaluate for each iteration of the loop."]],returns:{type:"null"},description:"Iterates over `bindings`, evaluates `body` for each `binding` and returns `null`. This is useful for side effects.",examples:["\ndoseq (i in [1, 2, 3]) -> perform(effect(dvala.io.println), i * 2)\n "]},St={arity:G(1),docs:$t,getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>At(e,t,n,r,a)},It={arity:{},docs:{category:"special-expression",returns:{type:"boolean"},args:{a:{type:"any"},b:{type:"any"},c:{type:"any",rest:!0}},variants:[{argumentNames:["a","b"]},{argumentNames:["a","b","c"]}],description:"\n Computes logical `or`. Evaluation of expressions evaluation starts from left.\n As soon as a `expression` evaluates to a truthy value, the result is returned.\n\n If all expressions evaluate to falsy values, the value of the last expression is returned.",examples:["false || 1","||(1, 1)",'||(3 > 2, "string")','||(3 < 2, "string")',"||(false, false, false, true)","||(1, 2, 3, 4)"]},evaluateAsNormalExpression:(e,t)=>{let n=!1;for(const r of e)if(n=E(r,t),n)break;return n},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1],t,r,a)},jt={arity:{min:1},docs:{category:"special-expression",returns:{type:"any"},args:{a:{type:"any"},b:{type:"any"},c:{type:"any",rest:!0}},variants:[{argumentNames:["a"]},{argumentNames:["a","b"]},{argumentNames:["a","b","c"]}],description:"Nullish coalescing operator. Returns the first non-`null` value.\n\nEvaluation is short-circuited — as soon as a non-`null` value is found, the remaining expressions are not evaluated.\n\nIf all values are `null`, returns `null`.\n\nAlso works with undefined symbols — if a symbol is undefined, it is treated as `null`.",examples:["1 ?? 2","null ?? 2","??(null)",'??(null, "default")','??(1, "default")','false ?? "default"',"??(null, null, 3)"]},evaluateAsNormalExpression:(e,t)=>{for(const n of e){const e=E(n,t);if(null!==e)return e}return null},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1],t,r,a)},qt={arity:{},docs:{category:"special-expression",customVariants:["recur(...recur-args)"],description:"Recursevly calls enclosing function or loop with its evaluated `recur-args`.",examples:["\nlet foo = (n) -> do\n if zero?(n) then\n 0\n else\n n + recur(n - 1)\n end\nend;\nfoo(3)","\n((n) -> do\n if zero?(n) then\n 0\n else\n n + recur(n - 1)\n end\nend)(3)","\nloop (n = 3, acc = 0) -> do\n if zero?(n) then\n acc\n else\n recur(n - 1, acc + n)\n end\nend"]},evaluateAsNormalExpression:e=>{throw new t(e)},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1],t,r,a)},Ct={arity:{},docs:{category:"special-expression",returns:{type:"any",array:!0},args:{values:{type:"any",rest:!0}},variants:[{argumentNames:["values"]}],description:"Makes new array from $values.",examples:["array(1, 2, 3)","array(array(null, false, true))","[]","[1, 2, 3]","[1, 2, ...[3, 4, 5], 6]","[[null, false, true]]","[1, 2, 3][1]"],hideOperatorForm:!0},evaluateAsNormalExpression:(e,t)=>{const n=[];for(const r of e)n.push(E(r,t));return n},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1],t,r,a)},Rt={arity:{},docs:{category:"special-expression",customVariants:["effect(name)"],details:[["name","dotted identifier","The effect name, e.g. `llm.complete` or `dvala.io.println`."]],description:"Returns the unique effect reference for the given name. Calling `effect` with the same name always returns the same reference. Effect references are first-class values that can be stored, passed, and compared with `==`.",examples:["effect(dvala.io.println)","==(effect(llm.complete), effect(llm.complete))"],seeAlso:["effect?"]},getUndefinedSymbols:()=>new Set},Pt={arity:{},docs:{category:"special-expression",returns:{type:"object"},args:{kvps:{type:"any",rest:!0,description:"key - value pairs, where key is a string"}},variants:[{argumentNames:["kvps"]}],description:"Constructs a new object. Object members are created from the $kvps key-value pairs. Requires an even number of arguments.",examples:["object()",'\nlet default = {\n type: "Person",\n name: "John Doe",\n age: 42\n};\n\n{\n ...default,\n name: "Lisa"\n}','object("x", 10, "y", true, "z", "A string")',"{}","{ a: 1, b: 2 }"],hideOperatorForm:!0},evaluateAsNormalExpression:(e,t)=>{const n={};for(let r=0;r<e.length;r+=2){const a=e[r],s=e[r+1];B(a,t),n[a]=s??null}return n},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1],t,r,a)},Tt={arity:G(1),docs:{category:"special-expression",description:"Imports all functions from a module as an object. Use destructuring to pick specific functions.",customVariants:["import(module-name)"],returns:{type:"object"},examples:["let v = import(vector); v.stdev([1, 2, 3, 4])","let { linspace } = import(vector); linspace(0, 10, 5)","let g = import(grid); g.row([[1, 2], [3, 4]], 0)"]},getUndefinedSymbols:()=>new Set},Ot={arity:{min:1},docs:{category:"special-expression",customVariants:["parallel(expr1, expr2, ...)"],details:[["expr1, expr2, ...","expressions","Expressions to evaluate concurrently. Typically `perform(...)` calls."]],description:"Evaluates all branch expressions concurrently and returns an array of results in order. Each branch runs as an independent trampoline invocation. If any branch suspends, the entire `parallel` suspends with a composite blob. On resume, branches are resumed one at a time. Only available in async mode (`run()`). Requires at least one branch.",examples:[]},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>ne(...e[1][1].map(e=>n([e],t,r,a)))},Mt={arity:{min:1},docs:{category:"special-expression",customVariants:["perform(eff)","perform(eff, arg1)","perform(eff, arg1, arg2, ...)"],details:[["eff","expression","An expression evaluating to an effect value (from `effect(name)`)."],["arg1, arg2, ...","expressions","Arguments passed to the effect handler."]],description:"Invokes an effect. The nearest enclosing `do/with` handler matching the effect intercepts the call. The handler receives the arguments as an array and its return value becomes the result of `perform`. If no local handler matches, the effect is dispatched to the host.",examples:['\ndo\n perform(effect(dvala.io.println), "hello")\nwith\n case effect(dvala.io.println) then ([msg]) -> msg\nend\n'],seeAlso:["effect?"]},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>{const[,s,o]=e[1];return ne(n([s],t,r,a),n(o,t,r,a))}},Vt={arity:{min:1},docs:{category:"special-expression",customVariants:["race(expr1, expr2, ...)"],details:[["expr1, expr2, ...","expressions","Expressions to race concurrently. Typically `perform(...)` calls."]],description:"Races all branch expressions concurrently. The first branch to complete wins — its value becomes the result. Losing branches are cancelled via AbortSignal. Errored branches are silently dropped. If all branches error, throws an aggregate error. If no branch completes but some suspend, the race suspends. On resume, the host provides the winner value directly. Only available in async mode (`run()`). Requires at least one branch.",examples:[]},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>ne(...e[1][1].map(e=>n([e],t,r,a)))},Ut={"??":0,"&&":1,"||":2,array:3,cond:4,"defined?":5,block:6,doseq:7,"0_lambda":8,for:9,if:10,let:11,loop:12,object:13,recur:14,match:15,unless:16,import:17,effect:18,perform:19,parallel:20,race:21},Bt={normalExpressions:Le,specialExpressions:[jt,Je,It,Ct,Ye,yt,gt,St,ht,Nt,vt,wt,kt,Pt,qt,dt,bt,Tt,Rt,Mt,Ot,Vt],allNormalExpressions:We},Dt=Object.keys(Le),_t=Object.keys(Ut);function Ft(e){return o.UserDefinedSymbol===e[0]}function Lt(e,t){return function(e,t){if(!Ft(e))throw h("UserDefinedSymbolNode",e,t)}(e,t),e}function zt(e){return o.NormalBuiltinSymbol===e[0]}function Wt(e){return o.SpecialBuiltinSymbol===e[0]}function Jt(e){return!!function(e){return e[0]===o.NormalExpression}(e)&&function(e){const t=e[0];return o.UserDefinedSymbol===t||o.NormalBuiltinSymbol===t||o.SpecialBuiltinSymbol===t}(e[1][0])}function Yt(e){return e[0]===o.Spread}class Kt{_contexts;globalContext;values;modules;valueModules;pure;constructor({contexts:e,values:t,modules:n,valueModules:r,pure:a}){this.globalContext=v(e[0]),this._contexts=e,this.values=t,this.modules=n??new Map,this.valueModules=r??new Map,this.pure=a??!1}getContextsRaw(){return this._contexts}getHostValues(){return this.values}getGlobalContextIndex(){return this._contexts.indexOf(this.globalContext)}static fromDeserialized(e){const t=new Kt({contexts:e.contexts,values:e.values,modules:e.modules,pure:e.pure});return e.globalContextIndex>=0&&e.globalContextIndex<e.contexts.length&&(t.globalContext=e.contexts[e.globalContextIndex]),t}setContextsFromDeserialized(e,t){this._contexts=e,t>=0&&t<e.length&&(this.globalContext=e[t])}getModule(e){return this.modules.get(e)}getValueModule(e){return this.valueModules.has(e)?{value:this.valueModules.get(e),found:!0}:{value:void 0,found:!1}}registerValueModule(e,t){this.valueModules.set(e,t)}create(e){const t=this.globalContext,n=new Kt({contexts:[e,...this._contexts],values:this.values,modules:this.modules,valueModules:this.valueModules,pure:this.pure});return n.globalContext=t,n}new(e){return new Kt({contexts:[{},e],modules:this.modules,valueModules:this.valueModules,pure:this.pure})}addValues(e,t){const r=this._contexts[0];for(const[a,s]of Object.entries(e)){if(r[a])throw new n(`Cannot redefine value "${a}"`,t);const e=Gt(a);if(e)throw new n(`Cannot shadow ${e}`,t);r[a]={value:te(s)}}}getValue(e){for(const t of this._contexts){const n=t[e];if(n)return n.value}return this.values?.[e]}lookUp(e){const t=e[1];for(const e of this._contexts){const n=e[t];if(n)return n}const n=this.values?.[t];return void 0!==n?{value:te(n)}:null}evaluateSymbol(e){if(Wt(e)){const t=e[1];switch(t){case Ut["&&"]:case Ut["||"]:case Ut.array:case Ut.object:case Ut["defined?"]:case Ut.recur:case Ut["??"]:{const n=v(Bt.specialExpressions[t],e[2]);return{[u]:!0,functionType:"SpecialBuiltin",specialBuiltinSymbolType:t,sourceCodeInfo:e[2],arity:n.arity}}default:throw new n(`Unknown special builtin symbol type: ${t}`,e[2])}}if(zt(e)){const t=e[1],n=We[t],r=n.name;return{[u]:!0,functionType:"Builtin",normalBuiltinSymbolType:t,sourceCodeInfo:e[2],arity:n.arity,name:r}}const t=this.lookUp(e);if(x(r=t)&&void 0!==r.value)return t.value;var r;throw new s(e[1],e[2])}}function Gt(e){return _t.includes(e)?`special expression "${e}"`:Dt.includes(e)?`builtin function "${e}"`:"self"===e?`builtin value "${e}"`:null}function Xt(e){const t=Gt(e);if(t)throw new n(`Cannot shadow ${t}`,void 0)}function Ht(e={},t,r){const a=e.globalContext??{},s=e.contexts?[a,...e.contexts]:[a];let o;if(e.bindings)for(const[t,r]of Object.entries(e.bindings)){if(t.includes("."))throw new n(`Dots are not allowed in binding keys: "${t}"`,void 0);Xt(t),o||(o={}),o[t]=r}const i=new Kt({contexts:s,values:o,modules:t,pure:r});return e.globalModuleScope?i:i.create({})}const Zt=(e,t,n,r)=>{const a=Array.isArray(e)?e:[[o.SpecialExpression,[Ut.block,e.body,void 0]]],s=new Set;for(const e of a)Qt(e,t,n,r)?.forEach(e=>s.add(e));return s};function Qt(e,t,r,a){const s=e[0];switch(s){case o.UserDefinedSymbol:{const n=e;return null===t.lookUp(n)?new Set([n[1]]):null}case o.NormalBuiltinSymbol:case o.SpecialBuiltinSymbol:case o.String:case o.Number:case o.ReservedSymbol:case o.Binding:return null;case o.NormalExpression:{const n=e,s=new Set;if(Jt(n)){const[,[e]]=n;if(Ft(e)){null===t.lookUp(e)&&s.add(e[1])}}else{const[,[e]]=n;Qt(e,t,r,a)?.forEach(e=>s.add(e))}for(const e of n[1][1])Qt(e,t,r,a)?.forEach(e=>s.add(e));return s}case o.SpecialExpression:{const n=e,s=n[1][0];return(0,r.specialExpressions[s].getUndefinedSymbols)(n,t,{getUndefinedSymbols:Zt,builtin:r,evaluateNode:a})}case o.Spread:return Qt(e[1],t,r,a);default:throw new n(`Unhandled node type: ${s}`,e[2])}}const en=["^","*","/","%","+","-","<<",">>",">>>","++","<","<=","≤",">",">=","≥","==","!=","!=","&","xor","|","&&","||","??","|>"],tn=[...en,"?",":","->","...",".",",","=",":",";"],nn=new Set(["comment","cond","defined?","block","doseq","if","let","loop","recur","unless","while"]);function rn(e){return!nn.has(e)}const an=new Set(en);function sn(e){return an.has(e)}const on=new Set(tn);function ln(e){return on.has(e)}function cn(e,t){return"Symbol"===e?.[0]&&(!t||e[1]===t)}function un(e,t){return function(e,t){cn(e,t)||Cn("Symbol",void 0,e)}(e,t),e}function pn(e,t){return"ReservedSymbol"===e?.[0]&&(!t||e[1]===t)}function fn(e,t){pn(e,t)||Cn("ReservedSymbol",t,e)}function dn(e,t){return fn(e,t),e}function mn(e,t){return"Operator"===e?.[0]&&(!t||e[1]===t)}function yn(e,t){mn(e,t)||Cn("Operator",t,e)}function gn(e){return"Number"===e?.[0]}function hn(e){return"BasePrefixedNumber"===e?.[0]}function vn(e){return"LParen"===e?.[0]}function bn(e){vn(e)||Cn("LParen",void 0,e)}function xn(e){return"RParen"===e?.[0]}function wn(e){xn(e)||Cn("RParen",void 0,e)}function kn(e){return"LBracket"===e?.[0]}function An(e){return function(e){kn(e)||Cn("LBracket",void 0,e)}(e),e}function En(e){return"RBracket"===e?.[0]}function Nn(e){En(e)||Cn("RBracket",void 0,e)}function $n(e){return"LBrace"===e?.[0]}function Sn(e){return function(e){$n(e)||Cn("LBrace",void 0,e)}(e),e}function In(e){return"RBrace"===e?.[0]}function jn(e){return"string"===e?.[0]}function qn(e){return"Operator"===e?.[0]&&sn(e[1])}function Cn(e,t,r){const a=r?`${r[0]} '${r[1]}'`:"end of input";throw new n(`Unexpected token: ${a}, expected ${e}${t?` '${t}'`:""}`,r?.[2])}function Rn(e,t){return t&&(e[2]=t),e}function Pn(e,t){return void 0!==Ut[e]&&"fn"!==e&&"defn"!==e?Rn([o.SpecialBuiltinSymbol,Ut[e]],t):void 0!==ze[e]?Rn([o.NormalBuiltinSymbol,ze[e]],t):Rn([o.UserDefinedSymbol,e],t)}function Tn(e){return e.substring(1,e.length-1).replace(/(\\{2})|(\\')|\\(.)/g,(e,t,n,r)=>t?"\\":n?"'":`\\${r}`)}const On=Object.entries(ze).reduce((e,[t,n])=>(e[n]=t,e),[]),Mn=Object.entries(Ut).reduce((e,[t,n])=>(e[n]=t,e),[]);function Vn(e){return Ft(e)?e[1]:zt(e)?On[e[1]]:Mn[e[1]]}function Un(e,t,n){const r=Rn([o.NormalExpression,[e,t]],n);return zt(e)&&K(We[e[1]].arity,r[1][1].length,n),r}function Bn(e){if(e.isAtEnd())return!0;const t=e.tryPeek();return mn(t)?[";",",",":"].includes(t[1]):!!pn(t)&&["else","when","while","case","let","then","end","do"].includes(t[1])}function Dn(e,t,r,a,s){const i=e[1];switch(i){case"^":case"*":case"/":case"%":case"+":case"-":case"<<":case">>":case">>>":case"++":case"<":case"<=":case"≤":case">":case">=":case"≥":case"==":case"!=":case"&":case"xor":case"|":case"|>":return Un(t,[r,a],s);case"&&":case"||":case"??":return Rn([o.SpecialExpression,[Ut[i],[r,a]]],s);default:throw new n(`Unknown binary operator: ${i}`,s)}}class _n{tokens;position;storedPosition=0;parseExpression;constructor(e){this.tokens=e.tokens,this.position=0}advance(){this.position+=1}tryPeek(){return this.tokens[this.position]}peek(){const e=this.tokens[this.position];if(!e){const e=this.tokens.at(-1),t=e?e[2]:void 0;throw new n("Unexpected end of input",t)}return e}isAtEnd(){return this.position>=this.tokens.length}peekSourceCodeInfo(){const e=this.tryPeek();return e?e[2]:this.tokens.at(-1)?.[2]}storePosition(){return this.storedPosition=this.position}restorePosition(){this.position=this.storedPosition}peekAhead(e){return this.tokens[this.position+e]}getPosition(){return this.position}getTokenAt(e){return this.tokens[e]}}function Fn(e,t){switch(e){case"^":return 12;case"*":case"/":case"%":return 11;case"+":case"-":return 10;case"<<":case">>":case">>>":return 9;case"++":return 8;case"<":case"<=":case"≤":case">":case">=":case"≥":return 7;case"==":case"!=":return 6;case"&":case"xor":case"|":return 5;case"&&":case"||":case"??":return 4;case"|>":return 2;default:throw new n(`Unknown binary operator: ${e}`,t)}}function Ln(e,t){const r=[];for(;!e.isAtEnd()&&!zn(e,t);)mn(e.tryPeek(),";")?e.advance():r.push(e.parseExpression());if(function(e,t){if(!zn(e,t))throw new n(`Expected ${t.map(e=>e[1]).join(" or ")}`,e.peekSourceCodeInfo())}(e,t),0===r.length)throw new n("Expected expression",e.peekSourceCodeInfo());return 1===r.length?r[0]:Rn([o.SpecialExpression,[Ut.block,r,void 0]],e.peekSourceCodeInfo())}function zn(e,t){for(const n of t)if(pn(e.tryPeek(),n))return!0;return!1}function Wn(e,t){e.advance();const n=t[1].substring(1,t[1].length-1).replace(/(\\{2})|(\\")|(\\n)|(\\t)|(\\r)|(\\b)|(\\f)|\\(.)/g,(e,t,n,r,a,s,o,i,l)=>t?"\\":r?"\n":a?"\t":s?"\r":o?"\b":i?"\f":n?'"':l);return Rn([o.String,n],t[2])}function Jn(e,t=!1){const r=dn(e.tryPeek(),"do");e.advance();let a="";t&&function(e){return"DocString"===e?.[0]}(e.tryPeek())&&(a=function(e){const t=e.peek(),n=t[2]?["string",t[1].slice(2,-2),t[2]]:["string",t[1].slice(2,-2)],r=Wn(e,n);return se(r[1])}(e),e.isAtEnd()||pn(e.tryPeek(),"end")||pn(e.tryPeek(),"with")||(yn(e.tryPeek(),";"),e.advance()));const s=[];for(;!e.isAtEnd()&&!pn(e.tryPeek(),"end")&&!pn(e.tryPeek(),"with");)if(s.push(e.parseExpression()),mn(e.tryPeek(),";"))e.advance();else if(!pn(e.tryPeek(),"end")&&!pn(e.tryPeek(),"with"))throw new n("Expected end",e.peekSourceCodeInfo());let i;if(pn(e.tryPeek(),"with"))for(e.advance(),i=[];!e.isAtEnd()&&!pn(e.tryPeek(),"end");){fn(e.tryPeek(),"case"),e.advance();const t=e.parseExpression();fn(e.tryPeek(),"then"),e.advance();const n=Ln(e,["case","end"]);i.push([t,n])}return fn(e.tryPeek(),"end"),e.advance(),[Rn([o.SpecialExpression,[Ut.block,s,i]],r[2]),a]}function Yn(e){const t=e.peek();if(e.advance(),!cn(t))throw new n(`Expected symbol token, got ${t[0]}`,t[2]);return"'"===t[1][0]?Pn(Tn(t[1]),t[2]):Pn(t[1],t[2])}function Kn(e){const t=e.peek();e.advance();const n=t[1],r="-"===n[0],a=(r?n.substring(1):n).replace(/_/g,"");return Rn([o.Number,r?-Number(a):Number(a)],t[2])}function Gn(e,{requireDefaultValue:t,noRest:r,allowLiteralPatterns:a}={}){const s=e.tryPeek();if(a&&pn(s,"_"))return e.advance(),Rn([Qe,[]],s[2]);if(a&&Hn(s)){if(gn(s)||hn(s)){const t=Kn(e);return Rn([Ze,[t]],s[2])}if(jn(s)){const t=Wn(e,s);return Rn([Ze,[t]],s[2])}if(pn(s,"true")){e.advance();const t=Rn([o.ReservedSymbol,"true"],s[2]);return Rn([Ze,[t]],s[2])}if(pn(s,"false")){e.advance();const t=Rn([o.ReservedSymbol,"false"],s[2]);return Rn([Ze,[t]],s[2])}if(pn(s,"null")){e.advance();const t=Rn([o.ReservedSymbol,"null"],s[2]);return Rn([Ze,[t]],s[2])}}if(cn(s)){const r=Yn(e);if(!Ft(r))throw new n("Expected user defined symbol",s[2]);const a=Xn(e);if(t&&!a)throw new n("Expected assignment",e.peekSourceCodeInfo());return Rn([Ke,[r,a]],s[2])}if(mn(s,"...")){if(r)throw new n("Rest element not allowed",s[2]);e.advance();const t=Lt(Yn(e));if(mn(e.tryPeek(),"="))throw new n("Rest argument can not have default value",e.peekSourceCodeInfo());return Rn([Ge,[t[1],void 0]],s[2])}if(kn(s)){e.advance();const r=[];let o=e.peek(),i=!1;for(;!En(o);){if(i)throw new n("Rest argument must be last",o[2]);if(mn(o,",")){r.push(null),e.advance(),o=e.peek();continue}const t=Gn(e,{allowLiteralPatterns:a});t[0]===Ge&&(i=!0),r.push(t),o=e.peek(),En(o)||(yn(o,","),e.advance()),o=e.peek()}e.advance();const l=Xn(e);if(t&&!l)throw new n("Expected assignment",e.peekSourceCodeInfo());return Rn([He,[r,l]],s[2])}if($n(s)){e.advance();const r={};let o=e.peek(),i=!1;for(;!In(o);){if(i)throw new n("Rest argument must be last",o[2]);mn(o,"...")&&(i=!0,e.advance());const t=Yn(e),l=Vn(t);if(o=e.peek(),pn(o,"as")){if(i)throw new n("Rest argument can not have alias",o[2]);e.advance();const t=Lt(Yn(e));if(r[t[1]])throw new n(`Duplicate binding name: ${t}`,o[2]);r[l]=Rn([Ke,[t,Xn(e)]],s[2])}else if(In(o)||mn(o,",")||mn(o,"=")){const a=Lt(t,t[2]);if(r[a[1]])throw new n(`Duplicate binding name: ${a}`,o[2]);if(i&&mn(e.tryPeek(),"="))throw new n("Rest argument can not have default value",e.peekSourceCodeInfo());r[a[1]]=Rn(i?[Ge,[a[1],Xn(e)]]:[Ke,[a,Xn(e)]],s[2])}else if(mn(o,":")){if(e.advance(),o=e.peek(),a){if(!$n(o)&&!kn(o)&&!Hn(o))throw new n("Expected literal, object or array pattern",o[2])}else if(!$n(o)&&!kn(o))throw new n("Expected object or array",o[2]);r[l]=Gn(e,{allowLiteralPatterns:a})}In(e.peek())||(yn(e.peek(),","),e.advance()),o=e.peek()}e.advance(),o=e.peek();const l=Xn(e);if(t&&!l)throw new n("Expected assignment",o[2]);return Rn([Xe,[r,l]],s[2])}throw new n("Expected symbol",e.peekSourceCodeInfo())}function Xn(e){if(mn(e.tryPeek(),"="))return e.advance(),e.parseExpression()}function Hn(e){return gn(e)||hn(e)||jn(e)||pn(e,"true")||pn(e,"false")||pn(e,"null")}function Zn(e,t){e.advance();const n=Gn(e,{requireDefaultValue:!0,noRest:!0}),r=n[1][1];n[1][1]=void 0;const a=Rn([o.Binding,[n,r]],t[2]);return Rn([o.SpecialExpression,[Ut.let,a]],t[2])}function Qn(e){const t=function(e){const t=un(e.tryPeek()),n=Lt(Yn(e));fn(e.tryPeek(),"in"),e.advance();const r=e.parseExpression();return Rn([o.Binding,[Rn([Ke,[n,void 0]],t[2]),r]],t[2])}(e),r=[];let a=e.peek();er(a,["let","when","while"]);const s=[];if("let"===a[1])for(r.push("&let");cn(a,"let");){const t=Zn(e,a),r=s.flatMap(e=>Object.keys(ct(e[1][0])));if(Object.keys(ct(t[1][1][1][0])).some(e=>r.includes(e)))throw new n("Duplicate binding",t[1][1][2]);s.push(t[1][1]),a=e.peek(),er(a,["let","when","while"]),a=e.peek()}let i,l;for(;pn(a,"when")||pn(a,"while");){e.advance(),"when"===a[1]?(r.push("&when"),i=e.parseExpression()):(r.push("&while"),l=e.parseExpression()),a=e.peek();er(a,r.includes("&when")&&r.includes("&while")?[]:r.includes("&when")?["while"]:["when"]),a=e.peek()}return er(a,[]),[t,s,i,l]}function er(e,t){if(!function(e,t){if(mn(e,",")||xn(e))return!0;for(const n of t){if("let"===n&&cn(e,"let"))return!0;if(["when","while"].includes(n)&&pn(e,n))return!0}return!1}(e,t)){const r=`${[...t,","].map(e=>`"${e}"`).join(", ")} or ")"`;throw new n(`Expected symbol ${r}`,e[2])}}const tr=(1+Math.sqrt(5))/2,nr={E:Math.E,"-E":-Math.E,"ε":Math.E,"-ε":-Math.E,PI:Math.PI,"-PI":-Math.PI,"π":Math.PI,"-π":-Math.PI,PHI:tr,"-PHI":-tr,"φ":tr,"-φ":-tr,POSITIVE_INFINITY:Number.POSITIVE_INFINITY,"∞":Number.POSITIVE_INFINITY,NEGATIVE_INFINITY:Number.NEGATIVE_INFINITY,"-∞":Number.NEGATIVE_INFINITY,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,MAX_VALUE:Number.MAX_VALUE,MIN_VALUE:Number.MIN_VALUE,NaN:Number.NaN},rr={true:!0,false:!1,null:null,do:null,else:null,case:null,each:null,in:null,when:null,while:null,function:null,as:null,then:null,end:null,with:null,_:null,...nr};function ar(e){const t=dn(e.tryPeek());e.advance();const n=t[1];return function(e){return e in nr}(n)?Rn([o.Number,nr[n]],t[2]):Rn([o.ReservedSymbol,t[1]],t[2])}const sr=/^\$([1-9]\d?)?$/;function or(e){const t=e.peek();if(vn(t)&&cn(e.peekAhead(1))&&mn(e.peekAhead(2),"->"))return null;try{const r=function(e){const t=e.peek();if(cn(t))return[Rn([Ke,[Yn(e),void 0]],t[2])];bn(t),e.advance();let r=!1,a=!1;const s=[];for(;!e.isAtEnd()&&!xn(e.peek())&&!cn(e.peek(),"let");){if(r)throw new n("Rest argument must be last",e.peekSourceCodeInfo());const t=Gn(e);if(void 0!==t[1][1]&&(a=!0),t[0]===Ge&&(r=!0),a&&!t[1][1])throw new n("Default arguments must be last",e.peekSourceCodeInfo());if(s.push(t),!mn(e.peek(),",")&&!xn(e.peek())&&!cn(e.peek(),"let"))throw new n("Expected comma or closing parenthesis",e.peekSourceCodeInfo());mn(e.peek(),",")&&e.advance()}if(!xn(e.peek()))throw new n("Expected closing parenthesis",e.peekSourceCodeInfo());return e.advance(),s}(e);if(!mn(e.peek(),"->"))return null;let a;e.advance();let s="";if(pn(e.peek(),"do")){const t=Jn(e,!0);s=t[1];const n=t[0],r=n[1][2];a=r&&r.length>0?[n]:n[1][1]}else a=[e.parseExpression()];return Rn([o.SpecialExpression,[Ut["0_lambda"],[r,a],s]],t[2])}catch{return null}}function ir(e,t){if(e.advance(),Wt(t)&&t[1]===Ut.effect)return function(e,t){const r=t[2],a=e.peek();if(!cn(a))throw new n("effect expects a dotted name identifier",a[2]);let s=a[1];e.advance();for(;mn(e.tryPeek(),".");){e.advance();const t=e.peek();if(!cn(t))throw new n("Expected identifier after dot in effect name",t[2]);s+=`.${t[1]}`,e.advance()}if(!xn(e.tryPeek()))throw new n("Expected closing parenthesis after effect name",e.peekSourceCodeInfo());return e.advance(),Rn([o.SpecialExpression,[Ut.effect,s]],r)}(e,t);const r=[];for(;!e.isAtEnd()&&!xn(e.tryPeek());){mn(e.tryPeek(),"...")?(e.advance(),r.push(Rn([o.Spread,e.parseExpression()],e.peekSourceCodeInfo()))):r.push(e.parseExpression());const t=e.tryPeek();if(!mn(t,",")&&!xn(t))throw new n("Expected comma or closing parenthesis",e.tryPeek()?.[2]);mn(t,",")&&e.advance()}if(!xn(e.tryPeek()))throw new n("Expected closing parenthesis",e.peekSourceCodeInfo());if(e.advance(),!Wt(t))return zt(t)||Ft(t)?Un(t,r,t[2]):Rn([o.NormalExpression,[t,r]],t[2]);{const e=t[1];if(e===Ut.import){if(1!==r.length)throw new n(`import expects exactly 1 argument, got ${r.length}`,t[2]);const a=r[0];if(!Ft(a))throw new n("import expects a module name (symbol), got a non-symbol argument",a[2]??t[2]);const s=a[1];return Rn([o.SpecialExpression,[e,s]],t[2])}const a=e;switch(K(Bt.specialExpressions[a].arity,r.length,t[2]),a){case Ut["||"]:case Ut["&&"]:case Ut.recur:case Ut.array:case Ut.object:case Ut["??"]:return Rn([o.SpecialExpression,[a,r]],t[2]);case Ut["defined?"]:{const[e]=r;return Rn([o.SpecialExpression,[a,e]],t[2])}case Ut.perform:{const[e,...n]=r;return Rn([o.SpecialExpression,[a,e,n]],t[2])}case Ut.parallel:case Ut.race:return Rn([o.SpecialExpression,[a,r]],t[2]);case Ut["0_lambda"]:throw new n(`${a} is not allowed`,t[2]);default:throw new n(`Unknown special expression: ${a}`,t[2])}}}function lr(e){const t=Sn(e.tryPeek());e.advance();const r=[];for(;!e.isAtEnd()&&!In(e.tryPeek());){if(mn(e.tryPeek(),"..."))e.advance(),r.push(Rn([o.Spread,e.parseExpression()],e.peekSourceCodeInfo()));else{const t=e.tryPeek();if(jn(t)){const n=Wn(e,t);r.push(Rn([o.String,n[1]],t[2]))}else if(cn(t)){const n=t[1].startsWith("'")?Tn(t[1]):t[1];r.push(Rn([o.String,n],t[2])),e.advance()}else{if(!kn(t))throw new n("Expected key to be a symbol or a string",e.peekSourceCodeInfo());e.advance(),r.push(e.parseExpression()),Nn(e.tryPeek()),e.advance()}yn(e.tryPeek(),":"),e.advance(),r.push(e.parseExpression())}const t=e.tryPeek();if(!mn(t,",")&&!In(t))throw new n("Expected comma or closing brace",e.peekSourceCodeInfo());mn(t,",")&&e.advance()}var a;return In(a=e.tryPeek())||Cn("RBrace",void 0,a),e.advance(),Rn([o.SpecialExpression,[Ut.object,r]],t[2])}function cr(e){let t=function(e){const t=e.peek();if(vn(t)){e.storePosition();const t=or(e);if(t)return t;e.restorePosition(),e.advance();const r=e.parseExpression();if(!xn(e.peek()))throw new n("Expected closing parenthesis",e.peekSourceCodeInfo());return e.advance(),r}if(mn(t)){const r=t[1];if(sn(r))return e.advance(),Rn(void 0!==Ut[r]?[o.SpecialBuiltinSymbol,Ut[r]]:[o.NormalBuiltinSymbol,ze[r]],t[2]);if("->"===r)return function(e){const t=e.peek();e.advance();const r=e.getPosition();let a,s="";if(pn(e.peek(),"do")){const t=Jn(e,!0);s=t[1];const n=t[0],r=n[1][2];a=r&&r.length>0?[n]:n[1][1]}else a=[e.parseExpression()];const i=e.getPosition()-1;let l=0,c="NOT_SET";for(let a=r;a<=i;a+=1){const r=e.getTokenAt(a);if(cn(r)){const e=sr.exec(r[1]);if(e){const r=e[1]??"1";if("1"===r){if(!e[1]&&"WITH_1"===c||e[1]&&"NAKED"===c)throw new n("Please make up your mind, either use $ or $1",t[2]);c=e[1]?"WITH_1":"NAKED"}if(l=Math.max(l,Number(r)),l>20)throw new n("Can't specify more than 20 arguments",t[2])}}}const u=[];for(let e=1;e<=l;e+=1)1===e&&"NAKED"===c?u.push(Rn([Ke,[[o.UserDefinedSymbol,"$"],void 0]],t[2])):u.push(Rn([Ke,[[o.UserDefinedSymbol,`$${e}`],void 0]],t[2]));return Rn([o.SpecialExpression,[Ut["0_lambda"],[u,a],s]],t[2])}(e);throw new n(`Illegal operator: ${r}`,t[2])}if($n(t))return lr(e);if(kn(t))return function(e){const t=An(e.tryPeek());e.advance();const r=[];for(;!e.isAtEnd()&&!En(e.tryPeek());){mn(e.tryPeek(),"...")?(e.advance(),r.push(Rn([o.Spread,e.parseExpression()],e.peekSourceCodeInfo()))):r.push(e.parseExpression());const t=e.tryPeek();if(!mn(t,",")&&!En(t))throw new n("Expected comma or closing parenthesis",e.peekSourceCodeInfo());mn(t,",")&&e.advance()}return Nn(e.tryPeek()),e.advance(),Rn([o.SpecialExpression,[Ut.array,r]],t[2])}(e);const r=t[0];switch(r){case"Number":case"BasePrefixedNumber":return Kn(e);case"string":return Wn(e,t);case"Symbol":{e.storePosition();const t=or(e);return t||(e.restorePosition(),Yn(e))}case"ReservedSymbol":return ar(e);case"RegexpShorthand":return function(e){const t=e.peek();e.advance();const n=t[1].lastIndexOf('"'),r=t[1].substring(2,n),a=t[1].substring(n+1),s=Rn([o.String,r],t[2]),i=Rn([o.String,a],t[2]);return Rn([o.NormalExpression,[Rn([o.NormalBuiltinSymbol,ze.regexp],t[2]),[s,i]]],t[2])}(e);default:throw new n(`Unknown token type: ${r}`,t[2])}}(e),r=e.tryPeek();for(;mn(r,".")||kn(r)||vn(r);)if("."===r[1]){e.advance();const a=e.tryPeek();if(!cn(a))throw new n("Expected symbol",e.peekSourceCodeInfo());t=ur(t,Rn([o.String,a[1]],a[2]),r[2]),e.advance(),r=e.tryPeek()}else if(kn(r)){e.advance();const a=e.parseExpression();if(!En(e.tryPeek()))throw new n("Expected closing bracket",e.peekSourceCodeInfo());t=ur(t,a,r[2]),e.advance(),r=e.tryPeek()}else vn(r)&&(t=ir(e,t),r=e.tryPeek());return t}function ur(e,t,n){return Rn([o.NormalExpression,[[o.NormalBuiltinSymbol,ze.get],[e,t]]],n)}function pr(e,t=0){const r=e.tryPeek();let a;if(cn(r))switch(r[1]){case"let":return Zn(e,r);case"if":case"unless":a=function(e,t){const n="unless"===t[1];e.advance();const r=e.parseExpression();fn(e.tryPeek(),"then"),e.advance();const a=Ln(e,["else","end"]);let s;return pn(e.tryPeek(),"else")&&(e.advance(),s=Ln(e,["end"])),e.advance(),Rn(n?[o.SpecialExpression,[Ut.unless,[r,a,s]]]:[o.SpecialExpression,[Ut.if,[r,a,s]]],t[2])}(e,r);break;case"cond":a=function(e,t){e.advance();const n=[];for(;!e.isAtEnd()&&!pn(e.tryPeek(),"end");){fn(e.tryPeek(),"case"),e.advance();const t=e.parseExpression();fn(e.tryPeek(),"then"),e.advance();const r=Ln(e,["case","end"]);if(n.push([t,r]),pn(e.tryPeek(),"end"))break}return fn(e.tryPeek()),e.advance(),Rn([o.SpecialExpression,[Ut.cond,n]],t[2])}(e,r);break;case"match":a=function(e,t){e.advance();const n=e.parseExpression(),r=[];for(;!e.isAtEnd()&&!pn(e.tryPeek(),"end");){fn(e.tryPeek(),"case"),e.advance();const t=Gn(e,{allowLiteralPatterns:!0});let n;pn(e.tryPeek(),"when")&&(e.advance(),n=e.parseExpression()),fn(e.tryPeek(),"then"),e.advance();const a=Ln(e,["case","end"]);if(r.push([t,a,n]),pn(e.tryPeek(),"end"))break}return fn(e.tryPeek(),"end"),e.advance(),Rn([o.SpecialExpression,[Ut.match,n,r]],t[2])}(e,r);break;case"for":case"doseq":a=function(e,t){const r="doseq"===t[1];e.advance(),bn(e.tryPeek()),e.advance();const a=[];for(;!e.isAtEnd()&&!xn(e.tryPeek());){const t=Qn(e),r=a.flatMap(e=>Object.keys(ct(e[0][1][0]))),s=ct(t[0][1][0]);if(Object.keys(s).some(e=>r.includes(e)))throw new n("Duplicate binding",t[0][2]);a.push(t),mn(e.tryPeek(),",")&&e.advance()}wn(e.tryPeek()),e.advance(),yn(e.tryPeek(),"->"),e.advance();const s=e.parseExpression();return Rn(r?[o.SpecialExpression,[Ut.doseq,a,s]]:[o.SpecialExpression,[Ut.for,a,s]],t[2])}(e,r);break;case"loop":a=function(e,t){e.advance(),bn(e.tryPeek()),e.advance();const r=[];let a=e.tryPeek();for(;!e.isAtEnd()&&!xn(a);){const t=Gn(e,{requireDefaultValue:!0,noRest:!0}),n=t[1][1];t[1][1]=void 0,r.push(Rn([o.Binding,[t,n]],t[2])),mn(e.tryPeek(),",")&&e.advance(),a=e.tryPeek()}if(0===r.length)throw new n("Expected binding",e.peekSourceCodeInfo());wn(a),e.advance(),yn(e.tryPeek(),"->"),e.advance();const s=e.parseExpression();return Rn([o.SpecialExpression,[Ut.loop,r,s]],t[2])}(e,r)}else pn(r,"do")&&(a=Jn(e)[0]);a||=cr(e);let s=e.tryPeek();for(;!Bn(e);){if(qn(s)){const n=s[1],r=Fn(n,s[2]);if(r<=t&&(12!==r||12!==t))break;const i=Rn(Ut[n]?[o.SpecialBuiltinSymbol,Ut[n]]:[o.NormalBuiltinSymbol,ze[n]],s[2]);e.advance();a=Dn(s,i,a,pr(e,r),s[2])}else if(cn(s)){if(!rn(s[1]))break;const r=3;if(r<=t)break;const o=Yn(e),i=pr(e,r);if(Wt(o))throw new n("Special expressions are not allowed in binary functional operators",o[2]);a=Un(o,[a,i],s[2])}else{if("?"!==s?.[1])break;{if(1<=t)break;e.advance();const r=pr(e);if(!mn(e.tryPeek(),":"))throw new n("Expected :",e.peekSourceCodeInfo());e.advance();const s=pr(e);a=Rn([o.SpecialExpression,[Ut.if,[a,r,s]]],a[2])}}s=e.tryPeek()}return a}function fr(e){e.tokens.forEach(e=>{if("Error"===e[0])throw new n(e[3],e[2])});const t=[],r=function(e){const t=new _n(e);return t.parseExpression=(e=0)=>pr(t,e),t}(e);for(;!r.isAtEnd();)if(t.push(pr(r,0)),mn(r.tryPeek(),";"))r.advance();else if(!r.isAtEnd())throw new n("Expected ;",r.peekSourceCodeInfo());return t}function dr(e,{removeWhiteSpace:t}){const n=e.tokens.filter(e=>!(function(e){return"SingleLineComment"===e?.[0]}(e)||function(e){return"MultiLineComment"===e?.[0]}(e)||function(e){return"Shebang"===e?.[0]}(e)||t&&function(e){return"Whitespace"===e?.[0]}(e)));return{...e,tokens:n}}const mr=["(",")","[","]","{","}","'",'"',"`",",",".",";"," ","\n","\r","\t"],yr=["0","1","2","3","4","5","6","7","8","9",...mr],gr=new Set(mr),hr=new Set(yr),vr=/\s/,br=[0],xr=(e,t)=>{if('"'!==e[t])return br;let n='"',r=1,a=e[t+r],s=!1;for(;a&&('"'!==a||s);)r+=1,s?(s=!1,n+=a):("\\"===a&&(s=!0),n+=a),a=e[t+r];return a?(n+='"',[r+1,["string",n]]):[r,["Error",n,void 0,`Unclosed string at position ${t}`]]};function wr(e,t,n,r){return t===n.slice(r,r+t.length)?[t.length,[e,t]]:br}const kr=/\d/,Ar=/[0-7]/,Er=/[0-9a-f]/i,Nr=/[01]/,$r=/[\s)\]}(,;]/,Sr=(e,t)=>{let n=e[t];if("'"===n){let r=1,a=e[t+r],s=!1;for(;"'"!==a||s;){if(void 0===a)return[r,["Error",n,void 0,`Unclosed quoted symbol at position ${t}`]];r+=1,s?(s=!1,n+=a):("\\"===a&&(s=!0),n+=a),a=e[t+r]}return n+="'",[r+1,["Symbol",n]]}if(!hr.has(n)){const r=t;let a=e[t+=1];for(;a&&!gr.has(a);)n+=a,a=e[t+=1];return n.endsWith(":")?[t-r-1,["Symbol",n.slice(0,-1)]]:[t-r,["Symbol",n]]}return br},Ir=[(e,t)=>{let n=e[t];if(!n||!vr.test(n))return br;let r=n;for(n=e[t+=1];n&&vr.test(n);)r+=n,n=e[t+=1];return[r.length,["Whitespace",r]]},(e,t)=>{if("/"===e[t]&&"*"===e[t+1]){let n=2,r="/*";for(;("*"!==e[t+n]||"/"!==e[t+n+1])&&t+n+1<e.length;)r+=e[t+n],n+=1;return t+n+1>=e.length?[n,["Error",r,void 0,`Unclosed multi-line comment at position ${t}`]]:(r+="*/",n+=2,[n,["MultiLineComment",r]])}return br},(e,t)=>{if("/"===e[t]&&"/"===e[t+1]){let n=2,r="//";for(;"\n"!==e[t+n]&&t+n<e.length;)r+=e[t+n],n+=1;return[n,["SingleLineComment",r]]}return br},(e,t)=>{const n=Sr(e,t);if(0===n[0]||!n[1])return br;let r=n[1][1];r=r.startsWith("'")?r.slice(1,r.length-1):r;return void 0===rr[r]?br:[n[0],["ReservedSymbol",r]]},(e,t)=>wr("LParen","(",e,t),(e,t)=>wr("RParen",")",e,t),(e,t)=>wr("LBracket","[",e,t),(e,t)=>wr("RBracket","]",e,t),(e,t)=>wr("LBrace","{",e,t),(e,t)=>wr("RBrace","}",e,t),(e,t)=>{if('"'!==e[t]||'"'!==e[t+1]||'"'!==e[t+2])return br;let n='"""',r=3,a=e[t+r],s=e.slice(t+r,t+r+3),o=!1;for(;a&&('"""'!==s||o);)r+=1,o?(o=!1,n+=a):("\\"===a&&(o=!0),n+=a),a=e[t+r],s=e.slice(t+r,t+r+3);return a?(n+='"""',[r+3,["DocString",n]]):[r,["Error",n,void 0,`Unclosed doc string at position ${t}`]]},xr,(e,t)=>{if("#"!==e[t])return br;const[n,r]=xr(e,t+1);if(!r)return br;if("Error"===r[0]){return[n+1,["Error",`#${r[1]}`,void 0,`Unclosed regexp at position ${t}`]]}t+=n+1;let a=n+1,s="";for(;"g"===e[t]||"i"===e[t];)if(s+=e[t],a+=1,t+=1,s.includes(e[t]))return[a,["Error",`#${r[1]}${s}`,void 0,`Duplicated regexp option "${e[t]}"`]];return[a,["RegexpShorthand",`#${r[1]}${s}`]]},(e,t)=>{if("0"!==e[t])return br;const n=e[t+1],r="b"===n||"B"===n?"binary":"o"===n||"O"===n?"octal":"x"===n||"X"===n?"hex":null;if(null===r)return br;let a;for(a=t+2;a<e.length;a+=1){const t=e[a];if("binary"===r&&!Nr.test(t))break;if("octal"===r&&!Ar.test(t))break;if("hex"===r&&!Er.test(t))break}const s=a-t;if(s<=2)return br;const o=e[a];return o&&!$r.test(o)?br:[s,["BasePrefixedNumber",e.substring(t,a)]]},(e,t)=>{let n;const r="-"===e[t],a="+"===e[t],s=r||a?t+1:t;let o=!1,i=!1;for(n=s;n<e.length;n+=1){const r=e[n];if("_"===r){if(!kr.test(e[n-1])||!kr.test(e[n+1]))return n===s?br:[n-t+1,["Error",e.substring(t,n+1),void 0,`Invalid number format at position ${n+1}`]]}else if("."===r){if(n===s)return br;if(o||i)return[n-t+1,["Error",e.substring(t,n+1),void 0,`Invalid number format at position ${n+1}`]];o=!0}else if("e"===r||"E"===r){if(n===s)return br;if(i)return[n-t+1,["Error",e.substring(t,n+1),void 0,`Invalid number format at position ${n+1}`]];if("."===e[n-1]||"+"===e[n-1]||"-"===e[n-1])return[n-t+1,["Error",e.substring(t,n+1),void 0,`Invalid number format at position ${n+1}`]];"+"!==e[n+1]&&"-"!==e[n+1]||(n+=1),i=!0}else if(!kr.test(r))break}if((r||a)&&n===s)return br;const l=n-t;if(0===l)return br;const c=e[n];return c&&":"!==c&&!$r.test(c)?[n-t+1,["Error",e.substring(t,n+1),void 0,`Invalid number format at position ${n+1}`]]:[l,["Number",e.substring(t,n)]]},(e,t)=>{const n=e.slice(t,t+3);if(t+2<e.length&&ln(n))return[3,["Operator",n]];const r=e.slice(t,t+2);if(t+1<e.length&&ln(r))return[2,["Operator",r]];const a=e[t]??"";return ln(a)?[1,["Operator",a]]:br},Sr];function jr(e,t,n){let r=0;const a={tokens:[],filePath:n,hasDebugData:t};for(;r<e.length;){const s=t?qr(e,r,n):void 0,o=Cr(e,r),[i,l]=o;r+=i,l&&(s&&(l[2]=s),a.tokens.push(l))}return a}function qr(e,t,n){const r=e.substring(0,t+1).split(/\r\n|\r|\n/),a=r[r.length-1],s=function(e,t){return e.split(/\r\n|\r|\n/)[t]}(e,r.length-1);return{code:s,position:{line:r.length,column:a.length},filePath:n}}function Cr(e,t){const n=t;if(0===t){const[r,a]=((e,t)=>{if("#"===e[t]&&"!"===e[t+1]){let n=2,r="#!";for(;"\n"!==e[t+n]&&t+n<e.length;)r+=e[t+n],n+=1;return[n,["SingleLineComment",r]]}return br})(e,t);if(t+=r,r>0)return[t-n,a]}for(const r of Ir){const[a,s]=r(e,t);if(t+=a,0!==a)return[t-n,s]}return[1,["Error",e[n],void 0,"Unrecognized character"]]}function Rr(e,t){if("*"===t)return!0;if(t.endsWith(".*")){const n=t.slice(0,-2);return e===n||e.startsWith(`${n}.`)}return e===t}function Pr(e,t){if(!t)return[];const n=[];for(const[r,a]of Object.entries(t))Rr(e,r)&&n.push([r,a]);return n}class Tr{k;snapshots;nextSnapshotIndex;meta;_brand="SuspensionSignal";constructor(e,t,n,r){this.k=e,this.snapshots=t,this.nextSnapshotIndex=n,this.meta=r}}function Or(e){return e instanceof Tr}class Mr{continuation;value;trimToIndex;_brand="ResumeFromSignal";constructor(e,t,n){this.continuation=e,this.value=t,this.trimToIndex=n}}function Vr(e){return e instanceof Mr}const Ur=new Map;function Br(e){let t=Ur.get(e);return t||(t={[f]:!0,name:e},Ur.set(e,t)),t}function Dr(e,t){return Math.imul(e^255&t,16777619)}function _r(e,t){return e=Dr(e,t),e=Dr(e,t>>>8),e=Dr(e,t>>>16),e=Dr(e,t>>>24)}function Fr(e,t){for(let n=0;n<t.length;n++){const r=t.charCodeAt(n);e=Dr(e,r),e=Dr(e,r>>>8)}return e}function Lr(e){let t=2166136261;if(null===e)return t=Dr(t,0),t>>>0;if(void 0===e)return t=Dr(t,7),t>>>0;const n=typeof e;if("boolean"===n)return t=Dr(t,e?1:2),t>>>0;if("number"===n)return t=Dr(t,3),t=Fr(t,Object.is(e,-0)?"-0":String(e)),t>>>0;if("string"===n)return t=Dr(t,4),t=Fr(t,e),t>>>0;if(Array.isArray(e)){t=Dr(t,5),t=_r(t,e.length);for(let n=0;n<e.length;n++)t=_r(t,Lr(e[n]));return t>>>0}t=Dr(t,6);const r=Object.keys(e).sort();t=_r(t,r.length);for(const n of r)t=Fr(t,n),t=_r(t,Lr(e[n]));return t>>>0}function zr(e,t){if(e===t)return!0;if(null===e||null===t)return!1;if(typeof e!=typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!zr(e[n],t[n]))return!1;return!0}if("object"!=typeof e)return!1;const n=e,r=t,a=Object.keys(n),s=Object.keys(r);if(a.length!==s.length)return!1;for(const e of a){if(!(e in r))return!1;if(!zr(n[e],r[e]))return!1}return!0}function Wr(e){if(null===e)return 4;if(void 0===e)return 9;const t=typeof e;if("boolean"===t)return e?4:5;if("number"===t)return String(e).length;if("string"===t)return e.length+2;if(Array.isArray(e)){let t=2;for(let n=0;n<e.length;n++)t+=Wr(e[n])+1;return t}const n=e,r=Object.keys(n);let a=2;for(const e of r)a+=e.length+2+1+Wr(n[e])+1;return a}function Jr(e,t,n,r){if(null===e||"object"!=typeof e)return Lr(e);if(Array.isArray(e))for(let n=0;n<e.length;n++)Jr(e[n],t,{parent:e,key:n});else{const n=e;for(const e of Object.keys(n))Jr(n[e],t,{parent:n,key:e})}const a=Lr(e),s=Wr(e);if(n&&s>=1){let r,o=t.get(a);o||(o=[],t.set(a,o));for(const t of o)if(zr(t.value,e)){r=t;break}r?r.locations.push(n):o.push({hash:a,value:Kr(e),size:s,locations:[n]})}return a}function Yr(e,t){if(null===e||"object"!=typeof e)return e;if(function(e){return null!==e&&"object"==typeof e&&"__poolRef"in e&&"number"==typeof e.__poolRef&&1===Object.keys(e).length}(e)){const n=e.__poolRef;if(!(n in t))throw new Error(`Unknown pool ref: ${n}`);return Yr(t[n],t)}if(Array.isArray(e))return e.map(e=>Yr(e,t));const n=e,r={};for(const e of Object.keys(n))r[e]=Yr(n[e],t);return r}function Kr(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>Kr(e));const t=e,n={};for(const e of Object.keys(t))n[e]=Kr(t[e]);return n}function Gr(e,t){const n=new Map;let r=0;function a(e){if(e instanceof Kt){if(n.has(e))return;n.set(e,r++);for(const t of e.getContextsRaw())for(const e of Object.values(t))a(e.value)}else if(Array.isArray(e))for(const t of e)a(t);else if(null!==e&&"object"==typeof e)for(const t of Object.values(e))a(t)}function s(e,t){if(e instanceof Kt)return{__csRef:n.get(e)};if(Array.isArray(e))return e.map((e,t)=>s(e));if(null!==e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=s(r);return t}return e}a(e),void 0!==t&&a(t);const o=Array.from(n.entries()).map(([e,t])=>({id:t,contexts:e.getContextsRaw().map((e,t)=>{const n={};for(const[t,r]of Object.entries(e))n[t]={value:s(r.value)};return n}),globalContextIndex:e.getGlobalContextIndex(),pure:e.pure})),i=s(e),l=void 0!==t?s(t):void 0;return{version:2,contextStacks:o,k:i,...void 0!==l?{meta:l}:{}}}function Xr(e,t,n,r){const a=Gr(e,r);t.length>0&&(a.snapshots=t),a.nextSnapshotIndex=n;const s=[a.contextStacks,a.k];if(void 0!==a.meta&&s.push(a.meta),a.snapshots)for(const e of a.snapshots)s.push(e);const{roots:o,pool:i}=function(e,t=200){const n=e.map(e=>Kr(e)),r=new Map;for(let e=0;e<n.length;e++)Jr(n[e],r,null);const a={};let s=0;const o=Array.from(r.values()).flat().filter(e=>e.locations.length>1&&e.size>=t).sort((e,t)=>t.size-e.size),i=new Map;for(const e of o){if(i.has(e))continue;const t=s++;a[t]=e.value,i.set(e,t);for(const n of e.locations)Array.isArray(n.parent),n.parent[n.key]={__poolRef:t}}return{roots:n,pool:a}}(s,200);let l=0;if(a.contextStacks=o[l++],a.k=o[l++],void 0!==a.meta&&(a.meta=o[l++]),a.snapshots)for(let e=0;e<a.snapshots.length;e++)a.snapshots[e]=o[l++];return Object.keys(i).length>0&&(a.pool=i),a}function Hr(e,t){let r=e;if(2!==r.version)throw new n(`Unsupported suspension blob version: ${r.version} (expected 2)`,void 0);if(r.pool&&Object.keys(r.pool).length>0){const e=r.pool;r={...r,contextStacks:Yr(r.contextStacks,e),k:Yr(r.k,e),...void 0!==r.meta?{meta:Yr(r.meta,e)}:{},...r.snapshots?{snapshots:r.snapshots.map(t=>Yr(t,e))}:{}},delete r.pool}const a=new Map;for(const e of r.contextStacks){const n=e.contexts.map(()=>({})),r=Kt.fromDeserialized({contexts:n,globalContextIndex:e.globalContextIndex,values:t?.values,modules:t?.modules,pure:e.pure});a.set(e.id,r)}function s(e){if(function(e){return null!==e&&"object"==typeof e&&"__csRef"in e&&"number"==typeof e.__csRef}(e)){const t=a.get(e.__csRef);if(!t)throw new n(`Invalid suspension blob: unknown context stack ref ${e.__csRef}`,void 0);return t}if(Array.isArray(e))return e.map(s);if(null!==e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=s(r);return t}return e}for(const e of r.contextStacks){const t=a.get(e.id),n=e.contexts.map(e=>{const t=e,n={};for(const[e,r]of Object.entries(t))n[e]={value:s(r.value)};return n});t.setContextsFromDeserialized(n,e.globalContextIndex)}return{k:s(r.k),meta:void 0!==r.meta?s(r.meta):void 0,snapshots:r.snapshots??[],nextSnapshotIndex:r.nextSnapshotIndex??0}}function Zr(){return"undefined"!=typeof process&&"function"==typeof process.stdout?.write}function Qr(e){return"string"==typeof e?e:null===e?"null":"number"==typeof e||"boolean"==typeof e?String(e):w(e)?"Builtin"===e.functionType?`<builtin function ${e.normalBuiltinSymbolType}>`:`<function ${e.n??"λ"}>`:T(e)?`<effect ${e.name}>`:R(e)?`/${e.s}/${e.f}`:"object"==typeof e&&e instanceof RegExp?`${e}`:JSON.stringify(ea(e),null,2)}function ea(e){if(e===Number.POSITIVE_INFINITY)return"∞";if(e===Number.NEGATIVE_INFINITY)return"-∞";if(w(e))return Qr(e);if(T(e))return Qr(e);if(R(e))return Qr(e);if(Array.isArray(e))return e.map(ea);if("object"==typeof e&&null!==e){const t={};for(const[n,r]of Object.entries(e))t[n]=ea(r);return t}return e}const ta={"dvala.io.print":{handler:function(e,t){const n=e[0],r=Qr(n);return Zr()?process.stdout.write(r):console.log(r),{type:"Value",value:n,k:t}},arity:G(1),docs:{category:"effect",description:"Writes a value to stdout without a trailing newline. Accepts any value — strings are printed as-is, other values are auto-formatted. In Node.js uses `process.stdout.write(str)`, in browsers uses `console.log(str)`. Resumes with the original value (identity).",returns:{type:"any"},args:{value:{type:"any",description:"Value to print."}},variants:[{argumentNames:["value"]}],examples:['perform(effect(dvala.io.print), "hello")',"perform(effect(dvala.io.print), 42)"],seeAlso:["-effect-dvala.io.println","-effect-dvala.io.error","-effect-dvala.io.read-line","perform","effect"]}},"dvala.io.println":{handler:function(e,t){const n=e[0],r=Qr(n);return Zr()?process.stdout.write(`${r}\n`):"function"==typeof globalThis.alert?globalThis.alert(r):console.log(r),{type:"Value",value:n,k:t}},arity:G(1),docs:{category:"effect",description:'Writes a value to stdout followed by a newline. Accepts any value — strings are printed as-is, other values are auto-formatted. In Node.js uses `process.stdout.write(str + "\\n")`, in browsers uses `alert(str)`. Resumes with the original value (identity).',returns:{type:"any"},args:{value:{type:"any",description:"Value to print."}},variants:[{argumentNames:["value"]}],examples:['perform(effect(dvala.io.println), "hello")',"perform(effect(dvala.io.println), [1, 2, 3])"],seeAlso:["-effect-dvala.io.print","-effect-dvala.io.error","-effect-dvala.io.read-line","perform","effect"]}},"dvala.io.error":{handler:(e,t)=>{const n=e[0],r=Qr(n);return Zr()?process.stderr.write(`${r}\n`):console.error(r),{type:"Value",value:n,k:t}},arity:G(1),docs:{category:"effect",description:'Writes a value to stderr followed by a newline. Accepts any value — strings are printed as-is, other values are auto-formatted. In Node.js uses `process.stderr.write(str + "\\n")`, in browsers uses `console.error(str)`. Resumes with the original value (identity).',returns:{type:"any"},args:{value:{type:"any",description:"Value to write to stderr."}},variants:[{argumentNames:["value"]}],examples:['perform(effect(dvala.io.error), "something went wrong")'],seeAlso:["-effect-dvala.io.print","-effect-dvala.io.println","perform","effect"]}},"dvala.io.read-line":{handler:(e,t,r)=>{const a="string"==typeof e[0]?e[0]:"";if("function"==typeof globalThis.prompt){return{type:"Value",value:globalThis.prompt(a)??null,k:t}}throw new n('dvala.io.read-line is not supported in this environment. In Node.js, register a "dvala.io.read-line" host handler.',r)},arity:{min:0,max:1},docs:{category:"effect",description:"Reads one line of user input. In browsers uses `window.prompt()`. In Node.js uses `readline`. Resumes with the user's input string, or `null` on cancel.",returns:{type:["string","null"]},args:{message:{type:"string",description:"Optional prompt message to display."}},variants:[{argumentNames:[]},{argumentNames:["message"]}],examples:["effect(dvala.io.read-line)"],seeAlso:["-effect-dvala.io.read-stdin","-effect-dvala.io.print","-effect-dvala.io.println","perform","effect"]}},"dvala.io.read-stdin":{handler:(e,t,r)=>{if(!Zr()||!process.stdin)throw new n("dvala.io.read-stdin is not supported in this environment. Node.js is required.",r);return new Promise((e,n)=>{const r=[];process.stdin.setEncoding("utf-8"),process.stdin.on("data",e=>r.push(e)),process.stdin.on("end",()=>e({type:"Value",value:r.join(""),k:t})),process.stdin.on("error",e=>n(e)),process.stdin.resume()})},arity:G(0),docs:{category:"effect",description:"Reads all of stdin until EOF (Node.js only). Resumes with the full stdin content as a string.",returns:{type:"string"},args:{},variants:[{argumentNames:[]}],examples:["effect(dvala.io.read-stdin)"],seeAlso:["-effect-dvala.io.read-line","perform","effect"]}},"dvala.random":{handler:(e,t)=>({type:"Value",value:Math.random(),k:t}),arity:G(0),docs:{category:"effect",description:"Returns a random floating-point number in the range [0, 1). Equivalent to `Math.random()` in JavaScript.",returns:{type:"number"},args:{},variants:[{argumentNames:[]}],examples:["perform(effect(dvala.random))"],seeAlso:["-effect-dvala.random.int","-effect-dvala.random.uuid","-effect-dvala.random.item","-effect-dvala.random.shuffle","perform","effect"]}},"dvala.random.uuid":{handler:(e,t)=>({type:"Value",value:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),k:t}),arity:G(0),docs:{category:"effect",description:"Generates a UUID v4 string.",returns:{type:"string"},args:{},variants:[{argumentNames:[]}],examples:["perform(effect(dvala.random.uuid))"],seeAlso:["-effect-dvala.random","perform","effect"]}},"dvala.random.int":{handler:(e,t,r)=>{const a=e[0],s=e[1];if("number"!=typeof a||!Number.isInteger(a))throw new n(`dvala.random.int: min must be an integer, got ${"number"==typeof a?a:typeof a}`,r);if("number"!=typeof s||!Number.isInteger(s))throw new n(`dvala.random.int: max must be an integer, got ${"number"==typeof s?s:typeof s}`,r);if(s<=a)throw new n(`dvala.random.int: max (${s}) must be greater than min (${a})`,r);return{type:"Value",value:Math.floor(Math.random()*(s-a))+a,k:t}},arity:G(2),docs:{category:"effect",description:"Returns a random integer in the range [min, max).",returns:{type:"integer"},args:{min:{type:"integer",description:"Minimum value (inclusive)."},max:{type:"integer",description:"Maximum value (exclusive). Must be greater than min."}},variants:[{argumentNames:["min","max"]}],examples:["perform(effect(dvala.random.int), 1, 100)"],seeAlso:["-effect-dvala.random","-effect-dvala.random.item","perform","effect"]}},"dvala.random.item":{handler:(e,t,r)=>{const a=e[0];if(!Array.isArray(a))throw new n("dvala.random.item: argument must be an array, got "+typeof a,r);if(0===a.length)throw new n("dvala.random.item: cannot pick from an empty array",r);return{type:"Value",value:a[Math.floor(Math.random()*a.length)],k:t}},arity:G(1),docs:{category:"effect",description:"Picks a random element from a non-empty array.",returns:{type:"any"},args:{array:{type:"array",description:"Non-empty array to pick from."}},variants:[{argumentNames:["array"]}],examples:['perform(effect(dvala.random.item), ["a", "b", "c"])'],seeAlso:["-effect-dvala.random","-effect-dvala.random.shuffle","-effect-dvala.random.int","perform","effect"]}},"dvala.random.shuffle":{handler:(e,t,r)=>{const a=e[0];if(!Array.isArray(a))throw new n("dvala.random.shuffle: argument must be an array, got "+typeof a,r);const s=Array.from(a);for(let e=s.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1)),n=s[e];s[e]=s[t],s[t]=n}return{type:"Value",value:s,k:t}},arity:G(1),docs:{category:"effect",description:"Returns a new array with the elements of the input array in random order. Uses the Fisher-Yates shuffle algorithm.",returns:{type:"array"},args:{array:{type:"array",description:"Array to shuffle."}},variants:[{argumentNames:["array"]}],examples:["perform(effect(dvala.random.shuffle), [1, 2, 3, 4, 5])"],seeAlso:["-effect-dvala.random","-effect-dvala.random.item","perform","effect"]}},"dvala.time.now":{handler:(e,t)=>({type:"Value",value:Date.now(),k:t}),arity:G(0),docs:{category:"effect",description:"Returns the current timestamp in milliseconds since the Unix epoch. Equivalent to `Date.now()` in JavaScript.",returns:{type:"number"},args:{},variants:[{argumentNames:[]}],examples:["perform(effect(dvala.time.now))"],seeAlso:["-effect-dvala.time.zone","-effect-dvala.sleep","perform","effect"]}},"dvala.time.zone":{handler:(e,t)=>({type:"Value",value:Intl.DateTimeFormat().resolvedOptions().timeZone,k:t}),arity:G(0),docs:{category:"effect",description:'Returns the current IANA timezone string, e.g. `"Europe/Stockholm"` or `"America/New_York"`.',returns:{type:"string"},args:{},variants:[{argumentNames:[]}],examples:["perform(effect(dvala.time.zone))"],seeAlso:["-effect-dvala.time.now","perform","effect"]}},"dvala.checkpoint":{handler:(e,t)=>({type:"Value",value:null,k:t}),arity:{min:0,max:1},docs:{category:"effect",description:"Captures a snapshot of the current program state (continuation stack). The snapshot is stored in an in-memory list accessible via `ctx.snapshots` in host handlers. Optionally accepts a metadata value for domain context (e.g., step labels, timestamps). The standard fallback resumes with `null`, but host handlers can override the resume value. The snapshot is always captured regardless of whether a handler intercepts.",returns:{type:"null"},args:{meta:{type:"any",description:"Optional metadata to attach to the snapshot."}},variants:[{argumentNames:[]},{argumentNames:["meta"]}],examples:["perform(effect(dvala.checkpoint))",'perform(effect(dvala.checkpoint), { step: "analysis-done" })'],seeAlso:["perform","effect"]}},"dvala.sleep":{handler:(e,t,r)=>{const a=e[0];if("number"!=typeof a||a<0)throw new n(`dvala.sleep requires a non-negative number argument, got ${"number"==typeof a?a:typeof a}`,r);return new Promise(e=>{setTimeout(()=>e({type:"Value",value:null,k:t}),a)})},arity:G(1),docs:{category:"effect",description:"Waits for the specified number of milliseconds before resuming. Resumes with `null`. Only works in async execution (`run`) — `runSync` will throw when a Promise surfaces.",returns:{type:"null"},args:{ms:{type:"number",description:"The number of milliseconds to sleep. Must be a non-negative number."}},variants:[{argumentNames:["ms"]}],examples:["effect(dvala.sleep)"],seeAlso:["-effect-dvala.time.now","perform","effect"]}}};function na(e,t){switch(e[0]){case o.Number:case o.String:return e[1];case o.NormalBuiltinSymbol:case o.SpecialBuiltinSymbol:case o.UserDefinedSymbol:return t.evaluateSymbol(e);case o.ReservedSymbol:return ua(e);case o.NormalExpression:{const r=function(e,t){const r=e[2];return et(function(e,t){const r=[],a=[],s=at(e,(e,s)=>Yt(e)?et(na(e[1],t),t=>{if(!Array.isArray(t))throw new n(`Spread operator requires an array, got ${y(e)}`,e[2]);r.push(...t)}):e[0]!==o.ReservedSymbol||"_"!==e[1]?et(na(e,t),e=>{r.push(e)}):void a.push(s));return et(s,()=>({params:r,placeholders:a}))}(e[1][1],t),({params:a,placeholders:o})=>{if(Jt(e)){const i=e[1][0];if(o.length>0){return et(na(i,t),e=>({[u]:!0,function:M(e,r),functionType:"Partial",params:a,placeholders:o,sourceCodeInfo:r,arity:G(o.length)}))}if(zt(i)){const r=i[1],s=Bt.allNormalExpressions[r];if(t.pure&&!1===s.pure)throw new n(`Cannot call impure function '${s.name}' in pure mode`,e[2]);return s.dvalaImpl?sa(s.dvalaImpl,a,t,e[2]):s.evaluate(a,e[2],t,{executeFunction:ra})}{const n=t.getValue(i[1]);if(void 0!==n)return ra(M(n,r),a,t,r);throw new s(i[1],e[2])}}return et(na(e[1][0],t),e=>{const n=M(e,r);if(o.length>0){return{[u]:!0,function:n,functionType:"Partial",params:a,placeholders:o,sourceCodeInfo:r,arity:G(o.length)}}return ra(n,a,t,r)})})}(e,t);return et(r,t=>{if("number"==typeof t&&Number.isNaN(t))throw new n("Number is NaN",e[2]);return be(t)})}case o.SpecialExpression:{const r={type:"Eval",node:e,env:t,k:[]};try{return be(Ta(r))}catch(r){if(r instanceof n&&r.message.includes("Unexpected async operation")){return Oa({type:"Eval",node:e,env:t,k:[]}).then(e=>be(e))}throw r}}default:throw new n(`${l(e[0])}-node cannot be evaluated`,e[2])}}function ra(e,t,r,a){if(w(e))return aa(e,t,r,a);if(Array.isArray(e))return ia(e,t,a);if(I(e))return oa(e,t,a);if("string"==typeof e)return la(e,t,a);if(W(e))return ca(e,t,a);throw new n("Unexpected function type",a)}function aa(e,t,r,a){switch(e.functionType){case"UserDefined":return sa(e,t,r,a);case"Partial":return function(e,t,r,a){const s=[...e.params];if(t.length!==e.placeholders.length)throw new n(`(partial) expects ${e.placeholders.length} arguments, got ${t.length}.`,a);const o=[...t];for(const t of e.placeholders)s.splice(t,0,o.shift());return ra(e.function,s,r,a)}(e,t,r,a);case"Comp":return function(e,t,r,a){const{params:s}=e;if(0===s.length){if(1!==t.length)throw new n(`(comp) expects one argument, got ${y(t.length)}.`,a);return E(t[0],a)}let o=t;for(let e=s.length-1;e>=0;e--){const t=s[e];o=et(o,e=>et(ra(M(t,a),e,r,a),e=>[e]))}return et(o,e=>E(e[0],a))}(e,t,r,a);case"Constantly":return e.value;case"Juxt":return function(e,t,n,r){return function(e,t){const n=[];for(let r=0;r<e.length;r++){const a=t(e[r],r);if(a instanceof Promise)return tt(a,n,e,t,r);n.push(a)}return n}(e.params,e=>ra(M(e,r),t,n,r))}(e,t,r,a);case"Complement":return et(ra(e.function,t,r,a),e=>!e);case"EveryPred":return function(e,t,n,r){const a=[];for(const s of e.params)for(const e of t)a.push(()=>ra(M(s,r),[e],n,r));return nt(a,(e,t)=>!!e&&et(t(),e=>!!e),!0)}(e,t,r,a);case"SomePred":return function(e,t,n,r){const a=[];for(const s of e.params)for(const e of t)a.push(()=>ra(M(s,r),[e],n,r));return nt(a,(e,t)=>!!e||et(t(),e=>!!e),!1)}(e,t,r,a);case"Fnull":return function(e,t,n,r){const a=t.map((t,n)=>null===t?te(e.params[n]):t);return ra(M(e.function,r),a,n,r)}(e,t,r,a);case"EffectMatcher":return function(e,t,n){K({min:1,max:1},t.length,e.sourceCodeInfo??n);const r=t[0];O(r,n);const a=r.name;if("string"===e.matchType)return Rr(a,e.pattern);const s=new RegExp(e.pattern,e.flags);return s.test(a)}(e,t,a);case"Builtin":{const s=Bt.allNormalExpressions[e.normalBuiltinSymbolType];return s.dvalaImpl?sa(s.dvalaImpl,t,r,a):function(e,t,r,a){const s=v(Bt.allNormalExpressions[e.normalBuiltinSymbolType],a);if(r.pure&&!1===s.pure)throw new n(`Cannot call impure function '${e.name}' in pure mode`,a);if(s.dvalaImpl)return sa(s.dvalaImpl,t,r,a);return s.evaluate(t,a,r,{executeFunction:ra})}(e,t,r,a)}case"SpecialBuiltin":return function(e,t,r,a){const s=v(Bt.specialExpressions[e.specialBuiltinSymbolType],a);if(s.evaluateAsNormalExpression)return s.evaluateAsNormalExpression(t,a,r,{executeFunction:ra});throw new n(`Special builtin function ${e.specialBuiltinSymbolType} is not supported as normal expression.`,a)}(e,t,r,a);case"Module":return function(e,t,r,a){const s=r.getModule(e.moduleName);if(!s)throw new n(`Module '${e.moduleName}' not found.`,a);const o=s.functions[e.functionName];if(!o)throw new n(`Function '${e.functionName}' not found in module '${e.moduleName}'.`,a);if(r.pure&&!1===o.pure)throw new n(`Cannot call impure function '${e.functionName}' in pure mode`,a);if(K(o.arity,t.length,a),o.dvalaImpl)return sa(o.dvalaImpl,t,r,a);return o.evaluate(t,a,r,{executeFunction:ra})}(e,t,r,a)}}function sa(e,r,a,s){function o(r){if(!Y(e.arity,r.length))throw new n(`Expected ${e.arity} arguments, got ${r.length}.`,s);const i=e.evaluatedfunction,l=i[0],c=l.filter(e=>e[0]!==Ge).length,u=a.create(e.evaluatedfunction[2]),p={self:{value:e}},f=[];let d,m;for(let e=0;e<r.length;e+=1)if(e<c){const t=e;d=et(d,()=>{const e=te(r[t]);return et(it(l[t],e,e=>na(e,u.create(p))),e=>{Object.entries(e).forEach(([e,t])=>{p[e]={value:t}})})})}else f.push(te(r[e]));for(let e=r.length;e<c;e++){const t=e;m=et(m,()=>{const e=l[t];return et(na(e[1][1],a.create(p)),t=>et(it(e,t,e=>na(e,a.create(p))),e=>{Object.entries(e).forEach(([e,t])=>{p[e]={value:t}})}))})}return et(d,()=>et(m,()=>{const e=l.find(e=>e[0]===Ge),n=void 0!==e?et(it(e,f,e=>na(e,a.create(p))),e=>{Object.entries(e).forEach(([e,t])=>{p[e]={value:t}})}):void 0;return et(n,()=>{const e=u.create(p),n=nt(i[1],(t,n)=>na(n,e),null);return n instanceof Promise?n.catch(e=>{if(e instanceof t)return o(e.params);throw e}):n})}))}for(;;)try{return o(r)}catch(e){if(e instanceof t){r=e.params;continue}throw e}}function oa(e,t,r){if(1!==t.length)throw new n("Object as function requires one string parameter.",r);const a=t[0];return B(a,r),te(e[a])}function ia(e,t,r){if(1!==t.length)throw new n("Array as function requires one non negative integer parameter.",r);const a=t[0];return J(a,r,{integer:!0,nonNegative:!0}),te(e[a])}function la(e,t,r){if(1!==t.length)throw new n("String as function requires one Obj parameter.",r);const a=te(t[0]);if(I(a))return te(a[e]);if(W(a,{integer:!0}))return te(e[a]);throw new n(`string as function expects Obj or integer parameter, got ${y(a)}`,r)}function ca(e,t,r){if(J(e,void 0,{integer:!0}),1!==t.length)throw new n("Number as function requires one Arr parameter.",r);const a=t[0];return S(a,r),te(a[e])}function ua(e){const t=e[1];if(!["true","false","null"].includes(t))throw new n(`Reserved symbol ${t} cannot be evaluated`,e[2]);return v(rr[t],e[2])}function pa(e,t,r){switch(e[0]){case o.Number:case o.String:return{type:"Value",value:e[1],k:r};case o.NormalBuiltinSymbol:case o.SpecialBuiltinSymbol:case o.UserDefinedSymbol:return{type:"Value",value:t.evaluateSymbol(e),k:r};case o.ReservedSymbol:return{type:"Value",value:ua(e),k:r};case o.NormalExpression:return function(e,t,n){const r=e[1][1],a=e[2],s={type:"NanCheck",sourceCodeInfo:a},i={type:"EvalArgs",node:e,index:0,params:[],placeholders:[],env:t,sourceCodeInfo:a};let l=0;for(;l<r.length;){const e=r[l];if(e[0]!==o.ReservedSymbol||"_"!==e[1])break;i.placeholders.push(i.params.length),l++}if(i.index=l,l>=r.length)return fa(i,[s,...n]);const c=r[l],u=[i,s,...n];if(Yt(c))return{type:"Eval",node:c[1],env:t,k:u};return{type:"Eval",node:c,env:t,k:u}}(e,t,r);case o.SpecialExpression:return function(e,t,r){const a=e[2],s=e[1][0];switch(s){case Ut.if:case Ut.unless:{const[n,o,i]=e[1][1];return{type:"Eval",node:n,env:t,k:[{type:"IfBranch",thenNode:o,elseNode:i,inverted:s===Ut.unless,env:t,sourceCodeInfo:a},...r]}}case Ut["&&"]:{const n=e[1][1];if(0===n.length)return{type:"Value",value:!0,k:r};const s={type:"And",nodes:n,index:1,env:t,sourceCodeInfo:a};return 1===n.length?{type:"Eval",node:n[0],env:t,k:r}:{type:"Eval",node:n[0],env:t,k:[s,...r]}}case Ut["||"]:{const n=e[1][1];if(0===n.length)return{type:"Value",value:!1,k:r};const s={type:"Or",nodes:n,index:1,env:t,sourceCodeInfo:a};return 1===n.length?{type:"Eval",node:n[0],env:t,k:r}:{type:"Eval",node:n[0],env:t,k:[s,...r]}}case Ut["??"]:{const n=e[1][1];if(0===n.length)return{type:"Value",value:null,k:r};const s=n[0];if(Ft(s)&&null===t.lookUp(s)){if(1===n.length)return{type:"Value",value:null,k:r};const e={type:"Qq",nodes:n,index:2,env:t,sourceCodeInfo:a},s=n[1];return Ft(s)&&null===t.lookUp(s)?function(e,t){return ha(e,t)}(e,r):2===n.length?{type:"Eval",node:s,env:t,k:r}:{type:"Eval",node:s,env:t,k:[e,...r]}}const o={type:"Qq",nodes:n,index:1,env:t,sourceCodeInfo:a};return 1===n.length?{type:"Eval",node:s,env:t,k:r}:{type:"Eval",node:s,env:t,k:[o,...r]}}case Ut.cond:{const n=e[1][1];if(0===n.length)return{type:"Value",value:null,k:r};const s={type:"Cond",phase:"test",cases:n,index:0,env:t,sourceCodeInfo:a};return{type:"Eval",node:n[0][0],env:t,k:[s,...r]}}case Ut.match:{const n=e[1][1],s=e[1][2];return{type:"Eval",node:n,env:t,k:[{type:"Match",phase:"matchValue",matchValue:null,cases:s,index:0,bindings:{},env:t,sourceCodeInfo:a},...r]}}case Ut.block:{const n=e[1][1],s=e[1][2],o={},i=t.create(o);let l=r;if(s&&s.length>0){l=[{type:"TryWith",handlers:s.map(([e,n])=>({effectRef:na(e,t),handlerNode:n})),env:t,sourceCodeInfo:a},...r]}if(0===n.length)return{type:"Value",value:null,k:l};if(1===n.length)return{type:"Eval",node:n[0],env:i,k:l};const c={type:"Sequence",nodes:n,index:1,env:i,sourceCodeInfo:a};return{type:"Eval",node:n[0],env:i,k:[c,...l]}}case Ut.let:{const n=e[1][1],s=n[1][0];return{type:"Eval",node:n[1][1],env:t,k:[{type:"LetBind",target:s,env:t,sourceCodeInfo:a},...r]}}case Ut.loop:{const n=e[1][1],s=e[1][2];if(0===n.length){const e={},o={type:"LoopIterate",bindingNodes:n,bindingContext:e,body:s,env:t.create(e),sourceCodeInfo:a};return{type:"Eval",node:s,env:t.create(e),k:[o,...r]}}const o={type:"LoopBind",phase:"value",bindingNodes:n,index:0,context:{},body:s,env:t,sourceCodeInfo:a};return{type:"Eval",node:n[0][1][1],env:t,k:[o,...r]}}case Ut.for:case Ut.doseq:{const n=e[1][1],o=e[1][2],i=s===Ut.for;if(0===n.length)return{type:"Value",value:i?[]:null,k:r};const l={},c=t.create(l),u={type:"ForLoop",returnResult:i,bindingNodes:n,body:o,result:[],phase:"evalCollection",bindingLevel:0,levelStates:[],context:l,env:c,sourceCodeInfo:a};return{type:"Eval",node:n[0][0][1][1],env:c,k:[u,...r]}}case Ut.recur:{const n=e[1][1];if(0===n.length)return Ea([],r,a);const s={type:"Recur",nodes:n,index:1,params:[],env:t,sourceCodeInfo:a};if(1===n.length){const e={...s,index:1};return{type:"Eval",node:n[0],env:t,k:[e,...r]}}return{type:"Eval",node:n[0],env:t,k:[s,...r]}}case Ut.array:{const n=e[1][1];if(0===n.length)return{type:"Value",value:[],k:r};const s=n[0],o=Yt(s),i={type:"ArrayBuild",nodes:n,index:0,result:[],isSpread:o,env:t,sourceCodeInfo:a};return{type:"Eval",node:o?s[1]:s,env:t,k:[i,...r]}}case Ut.object:{const n=e[1][1];if(0===n.length)return{type:"Value",value:{},k:r};const s=n[0],o=Yt(s),i={type:"ObjectBuild",nodes:n,index:0,result:{},currentKey:null,isSpread:o,env:t,sourceCodeInfo:a};return{type:"Eval",node:o?s[1]:s,env:t,k:[i,...r]}}case Ut["0_lambda"]:{const n=e[1][1],a=e[1][2]??"",s=function(e,t){const n={},r=e[0].reduce((e,t)=>(Object.keys(ct(t)).forEach(t=>{e[t]={value:null}}),e),{});return Zt(e[1],t.new(r),Bt,na).forEach(e=>{const r=t.getValue(e);A(r)&&(n[e]={value:r})}),[e[0],e[1],n]}(n,t),o=s[0].filter(e=>e[0]!==Ge&&void 0===e[1][1]).length,i={min:o>0?o:void 0,max:s[0].some(e=>e[0]===Ge)?void 0:s[0].length};return{type:"Value",value:{[u]:!0,sourceCodeInfo:e[2],functionType:"UserDefined",name:void 0,evaluatedfunction:s,arity:i,docString:a},k:r}}case Ut["defined?"]:{const n=e[1][1];if(!Ft(n))return{type:"Value",value:!0,k:r};return{type:"Value",value:null!==t.lookUp(n),k:r}}case Ut.import:{const s=e[1][1],o=t.getValueModule(s);if(o.found)return{type:"Value",value:o.value,k:r};const i=t.getModule(s);if(!i)throw new n(`Unknown module: '${s}'`,a);const l={};for(const[e,t]of Object.entries(i.functions))l[e]={[u]:!0,sourceCodeInfo:a,functionType:"Module",moduleName:s,functionName:e,arity:t.arity};if(i.source){const e=fr(dr(jr(i.source,!1,void 0),{removeWhiteSpace:!0})),n=t.create({}),o={type:"ImportMerge",tsFunctions:l,moduleName:s,module:i,env:t,sourceCodeInfo:a};if(1===e.length)return{type:"Eval",node:e[0],env:n,k:[o,...r]};const c={type:"Sequence",nodes:e,index:1,env:n};return{type:"Eval",node:e[0],env:n,k:[c,o,...r]}}return t.registerValueModule(s,l),{type:"Value",value:l,k:r}}case Ut.effect:return{type:"Value",value:Br(e[1][1]),k:r};case Ut.perform:{const n=[e[1][1],...e[1][2]];if(1===n.length){const e={type:"PerformArgs",argNodes:n,index:1,params:[],env:t,sourceCodeInfo:a};return{type:"Eval",node:n[0],env:t,k:[e,...r]}}const s={type:"PerformArgs",argNodes:n,index:1,params:[],env:t,sourceCodeInfo:a};return{type:"Eval",node:n[0],env:t,k:[s,...r]}}case Ut.parallel:return{type:"Parallel",branches:e[1][1],env:t,k:r};case Ut.race:return{type:"Race",branches:e[1][1],env:t,k:r};default:throw new n(`Unknown special expression type: ${s}`,a)}}(e,t,r);default:throw new n(`${l(e[0])}-node cannot be evaluated`,e[2])}}function fa(e,t){const{node:r,params:a,placeholders:o,env:i,sourceCodeInfo:l}=e;if(Jt(r)){const e=r[1][0];if(o.length>0){const n=i.evaluateSymbol(e);return{type:"Value",value:{[u]:!0,function:M(n,l),functionType:"Partial",params:a,placeholders:o,sourceCodeInfo:l,arity:G(o.length)},k:t}}if(zt(e)){const r=e[1],s=Bt.allNormalExpressions[r];if(i.pure&&!1===s.pure)throw new n(`Cannot call impure function '${s.name}' in pure mode`,l);if(s.dvalaImpl)return ma(s.dvalaImpl,a,i,l,t);return Ra(s.evaluate(a,l,i,{executeFunction:ra}),t)}const c=i.getValue(e[1]);if(void 0!==c)return da(M(c,l),a,o,i,l,t);throw new s(e[1],l)}return{type:"Eval",node:r[1][0],env:i,k:[{type:"CallFn",params:a,placeholders:o,env:i,sourceCodeInfo:l},...t]}}function da(e,t,r,a,s,o){if(r.length>0){return{type:"Value",value:{[u]:!0,function:e,functionType:"Partial",params:t,placeholders:r,sourceCodeInfo:s,arity:G(r.length)},k:o}}if(w(e))return function(e,t,n,r,a){switch(e.functionType){case"UserDefined":return ma(e,t,n,r,a);case"Partial":case"Comp":case"Constantly":case"Juxt":case"Complement":case"EveryPred":case"SomePred":case"Fnull":case"EffectMatcher":case"SpecialBuiltin":return Ra(aa(e,t,n,r),a);case"Module":{const s=n.getModule(e.moduleName),o=s?.functions[e.functionName];if(o?.dvalaImpl)return K(o.arity,t.length,r),ma(o.dvalaImpl,t,n,r,a);return Ra(aa(e,t,n,r),a)}case"Builtin":{const s=Bt.allNormalExpressions[e.normalBuiltinSymbolType];if(s.dvalaImpl)return ma(s.dvalaImpl,t,n,r,a);return Ra(aa(e,t,n,r),a)}}}(e,t,a,s,o);if(Array.isArray(e))return{type:"Value",value:ia(e,t,s),k:o};if(I(e))return{type:"Value",value:oa(e,t,s),k:o};if("string"==typeof e)return{type:"Value",value:la(e,t,s),k:o};if(W(e))return{type:"Value",value:ca(e,t,s),k:o};throw new n("Unexpected function type",s)}function ma(e,t,r,a,s){if(!Y(e.arity,t.length))throw new n(`Expected ${e.arity} arguments, got ${t.length}.`,a);const o=e.evaluatedfunction,i=o[0],l=i.filter(e=>e[0]!==Ge).length,c=r.create(e.evaluatedfunction[2]),u={self:{value:e}},p=[];for(let n=0;n<t.length;n+=1)if(n<l){const o=te(t[n]),l=it(i[n],o,e=>na(e,c.create(u)));if(l instanceof Promise){return Ra(sa(e,t,r,a),s)}Object.entries(l).forEach(([e,t])=>{u[e]={value:t}})}else p.push(te(t[n]));for(let n=t.length;n<l;n++){const o=i[n],l=na(o[1][1],c.create(u));if(l instanceof Promise){return Ra(sa(e,t,r,a),s)}const p=it(o,l,e=>na(e,c.create(u)));if(p instanceof Promise){return Ra(sa(e,t,r,a),s)}Object.entries(p).forEach(([e,t])=>{u[e]={value:t}})}const f=i.find(e=>e[0]===Ge);if(f){const n=it(f,p,e=>na(e,c.create(u)));if(n instanceof Promise){return Ra(sa(e,t,r,a),s)}Object.entries(n).forEach(([e,t])=>{u[e]={value:t}})}const d=o[1],m=c.create(u);if(0===d.length)return{type:"Value",value:null,k:s};const y={type:"FnBody",fn:e,bodyIndex:1,env:m,outerEnv:r,sourceCodeInfo:a};return d.length,{type:"Eval",node:d[0],env:m,k:[y,...s]}}function ya(e,t,r){switch(e.type){case"Sequence":return function(e,t,n){const{nodes:r,index:a,env:s}=e;if(a>=r.length)return{type:"Value",value:t,k:n};const o={...e,index:a+1};if(a===r.length-1)return{type:"Eval",node:r[a],env:s,k:n};return{type:"Eval",node:r[a],env:s,k:[o,...n]}}(e,t,r);case"IfBranch":return function(e,t,n){const{thenNode:r,elseNode:a,inverted:s,env:o}=e,i=s?!t:t;if(i)return{type:"Eval",node:r,env:o,k:n};if(a)return{type:"Eval",node:a,env:o,k:n};return{type:"Value",value:null,k:n}}(e,t,r);case"Cond":return function(e,t,n){const{cases:r,index:a,env:s}=e;if("test"===e.phase){if(t)return{type:"Eval",node:r[a][1],env:s,k:n};const o=a+1;if(o>=r.length)return{type:"Value",value:null,k:n};const i={...e,index:o};return{type:"Eval",node:r[o][0],env:s,k:[i,...n]}}return{type:"Value",value:t,k:n}}(e,t,r);case"Match":return function(e,t,n){const{cases:r,env:a}=e;if("matchValue"===e.phase){const r=t;return ga({...e,matchValue:r,phase:"guard"},n)}if("guard"===e.phase){if(!t){return ga({...e,index:e.index+1,bindings:{}},n)}const s={};for(const[t,n]of Object.entries(e.bindings))s[t]={value:n};const o=a.create(s);return{type:"Eval",node:r[e.index][1],env:o,k:n}}return{type:"Value",value:t,k:n}}(e,t,r);case"And":return function(e,t,n){if(!t)return{type:"Value",value:t,k:n};const{nodes:r,index:a,env:s}=e;if(a>=r.length)return{type:"Value",value:t,k:n};if(a===r.length-1)return{type:"Eval",node:r[a],env:s,k:n};const o={...e,index:a+1};return{type:"Eval",node:r[a],env:s,k:[o,...n]}}(e,t,r);case"Or":return function(e,t,n){if(t)return{type:"Value",value:t,k:n};const{nodes:r,index:a,env:s}=e;if(a>=r.length)return{type:"Value",value:t,k:n};if(a===r.length-1)return{type:"Eval",node:r[a],env:s,k:n};const o={...e,index:a+1};return{type:"Eval",node:r[a],env:s,k:[o,...n]}}(e,t,r);case"Qq":return function(e,t,n){if(null!==t)return{type:"Value",value:t,k:n};return ha(e,n)}(e,t,r);case"ArrayBuild":return function(e,t,r){const{nodes:a,result:s,env:o,sourceCodeInfo:i}=e;if(e.isSpread){if(!Array.isArray(t))throw new n("Spread value is not an array",i);s.push(...t)}else s.push(t);const l=e.index+1;if(l>=a.length)return{type:"Value",value:s,k:r};const c=a[l],u=Yt(c),p={...e,index:l,isSpread:u};return{type:"Eval",node:u?c[1]:c,env:o,k:[p,...r]}}(e,t,r);case"ObjectBuild":return function(e,t,r){const{nodes:a,result:s,env:o,sourceCodeInfo:i}=e;if(e.isSpread){if(!x(t))throw new n("Spread value is not an object",i);Object.assign(s,t);const l=e.index+1;if(l>=a.length)return{type:"Value",value:s,k:r};const c=a[l],u=Yt(c),p={...e,index:l,currentKey:null,isSpread:u};return{type:"Eval",node:u?c[1]:c,env:o,k:[p,...r]}}if(null===e.currentKey){B(t,i);const s=a[e.index+1];if(void 0===s)throw new n("Missing value for key",i);return{type:"Eval",node:s,env:o,k:[{...e,currentKey:t},...r]}}{s[e.currentKey]=t;const n=e.index+2;if(n>=a.length)return{type:"Value",value:s,k:r};const i=a[n],l=Yt(i),c={...e,index:n,currentKey:null,isSpread:l};return{type:"Eval",node:l?i[1]:i,env:o,k:[c,...r]}}}(e,t,r);case"LetBind":return function(e,t,n){const{target:r,env:a,sourceCodeInfo:s}=e,o=it(r,t,e=>na(e,a));return et(o,e=>(a.addValues(e,s),{type:"Value",value:t,k:n}))}(e,t,r);case"LoopBind":return function(e,t,n){const{bindingNodes:r,index:a,context:s,body:o,env:i,sourceCodeInfo:l}=e,c=r[a],u=it(c[1][0],t,e=>na(e,i.create(s)));return et(u,t=>{Object.entries(t).forEach(([e,t])=>{s[e]={value:t}});const c=a+1;if(c>=r.length){const e=i.create(s);return{type:"Eval",node:o,env:e,k:[{type:"LoopIterate",bindingNodes:r,bindingContext:s,body:o,env:e,sourceCodeInfo:l},...n]}}const u={...e,index:c};return{type:"Eval",node:r[c][1][1],env:i.create(s),k:[u,...n]}})}(e,t,r);case"LoopIterate":return function(e,t,n){return{type:"Value",value:t,k:n}}(0,t,r);case"ForLoop":return function(e,t,r){const{returnResult:a,bindingNodes:s,result:o,env:i,sourceCodeInfo:l,context:c}=e,{asColl:u,isSeq:p}={asColl:(e,t)=>{if("string"==typeof e||Array.isArray(e)||I(e))return e;throw new n(`Expected collection, got ${y(e)}`,t)},isSeq:e=>"string"==typeof e||Array.isArray(e)};switch(e.phase){case"evalCollection":{const n=u(t,l),a=p(n)?n:Object.entries(n);if(0===a.length)return va(e,r);const o=[...e.levelStates];o[e.bindingLevel]={collection:a,index:0};const f=s[e.bindingLevel];return et(it(f[0][1][0],E(a[0],l),e=>na(e,i)),t=>{Object.entries(t).forEach(([e,t])=>{c[e]={value:t}});const n=f[1];return n.length>0?xa(e,o,n,0,r):wa(e,o,r)})}case"evalLet":throw new n("ForLoop evalLet should not reach applyFrame",l);case"evalWhen":{if(!t)return ba(e,r);const n=s[e.bindingLevel][3];if(n){const t={...e,phase:"evalWhile"};return{type:"Eval",node:n,env:i,k:[t,...r]}}return ka(e,r)}case"evalWhile":if(!t){const t=[...e.levelStates];return t[e.bindingLevel]={...t[e.bindingLevel],index:Number.POSITIVE_INFINITY},ba({...e,levelStates:t},r)}return ka(e,r);case"evalBody":return a&&o.push(t),ba(e,r);case"evalElement":throw new n(`Unexpected ForLoop phase: ${e.phase}`,l)}return{type:"Value",value:null,k:r}}(e,t,r);case"Recur":return function(e,t,n){const{nodes:r,index:a,params:s,env:o}=e;if(s.push(t),a>=r.length)return Ea(s,n,e.sourceCodeInfo);const i={...e,index:a+1};return{type:"Eval",node:r[a],env:o,k:[i,...n]}}(e,t,r);case"PerformArgs":return function(e,t,n){const{argNodes:r,index:a,params:s,env:o}=e;if(s.push(t),a>=r.length){const t=s[0];O(t,e.sourceCodeInfo);return{type:"Perform",effect:t,args:s.slice(1),k:n,sourceCodeInfo:e.sourceCodeInfo}}const i={...e,index:a+1};return{type:"Eval",node:r[a],env:o,k:[i,...n]}}(e,t,r);case"TryWith":return function(e,t){return{type:"Value",value:e,k:t}}(t,r);case"EffectResume":return function(e,t){return{type:"Value",value:t,k:e.resumeK}}(e,t);case"ParallelResume":return function(e,t,n){return{type:"ParallelResume",value:t,branchCount:e.branchCount,completedBranches:e.completedBranches,suspendedBranches:e.suspendedBranches,k:n}}(e,t,r);case"EvalArgs":return function(e,t,r){const{node:a,params:s,placeholders:i,env:l}=e,c=a[1][1],u=c[e.index];if(Yt(u)){if(!Array.isArray(t))throw new n(`Spread operator requires an array, got ${y(t)}`,u[2]);s.push(...t)}else s.push(t);let p=e.index+1;for(;p<c.length;){const e=c[p];if(e[0]!==o.ReservedSymbol||"_"!==e[1])break;i.push(s.length),p++}if(p>=c.length)return fa({...e,index:p},r);const f={...e,index:p},d=c[p];if(Yt(d))return{type:"Eval",node:d[1],env:l,k:[f,...r]};return{type:"Eval",node:d,env:l,k:[f,...r]}}(e,t,r);case"CallFn":return function(e,t,n){const r=M(t,e.sourceCodeInfo);return da(r,e.params,e.placeholders,e.env,e.sourceCodeInfo,n)}(e,t,r);case"FnBody":return function(e,t,n){const{fn:r,bodyIndex:a,env:s}=e,o=r.evaluatedfunction[1];if(a>=o.length)return{type:"Value",value:t,k:n};const i={...e,bodyIndex:a+1};return{type:"Eval",node:o[a],env:s,k:[i,...n]}}(e,t,r);case"BindingDefault":return function(e,t,r){const{target:a,record:s,env:o,sourceCodeInfo:i}=e,l=it(a,t,e=>na(e,o));if(l instanceof Promise)throw new n("Async binding default evaluation not supported in trampoline yet",i);return Object.assign(s,l),{type:"Value",value:t,k:r}}(e,t,r);case"NanCheck":return function(e,t,r){if("number"==typeof t&&Number.isNaN(t))throw new n("Number is NaN",e.sourceCodeInfo);return{type:"Value",value:be(t),k:r}}(e,t,r);case"DebugStep":return function(e,t,n){if("awaitValue"===e.phase){const r={expression:e.sourceCodeInfo?.code??"",value:t,location:e.sourceCodeInfo?{line:e.sourceCodeInfo.position.line,column:e.sourceCodeInfo.position.column}:{line:0,column:0},env:Ca(e.env)},a={type:"DebugStep",phase:"awaitPerform",sourceCodeInfo:e.sourceCodeInfo,env:e.env};return{type:"Perform",effect:Br("dvala.debug.step"),args:[r],k:[a,...n]}}return{type:"Value",value:t,k:n}}(e,t,r);case"ImportMerge":{const n=I(t)?t:{};for(const[t,r]of Object.entries(n)){const n=e.module.functions[t];n&&k(r)&&(n.dvalaImpl=r)}const a={};for(const[t,r]of Object.entries(n))e.module.functions[t]||(a[t]=r);const s={...e.tsFunctions,...a};return e.env.registerValueModule(e.moduleName,s),{type:"Value",value:s,k:r}}default:throw new n(`Unhandled frame type: ${e.type}`,void 0)}}function ga(e,t){const{matchValue:r,cases:a,index:s,env:o,sourceCodeInfo:i}=e;for(let l=s;l<a.length;l++){const[s,c,u]=a[l],p=pt(s,r,e=>na(e,o));if(p instanceof Promise)throw new n("Async pattern matching not supported in trampoline yet",i);if(null===p)continue;if(u){const n={};for(const[e,t]of Object.entries(p))n[e]={value:t};return{type:"Eval",node:u,env:o.create(n),k:[{...e,phase:"guard",index:l,bindings:p},...t]}}const f={};for(const[e,t]of Object.entries(p))f[e]={value:t};return{type:"Eval",node:c,env:o.create(f),k:t}}return{type:"Value",value:null,k:t}}function ha(e,t){const{nodes:n,env:r}=e;let{index:a}=e;for(;a<n.length;){const e=n[a];if(!Ft(e)||null!==r.lookUp(e))break;a++}if(a>=n.length)return{type:"Value",value:null,k:t};if(a===n.length-1)return{type:"Eval",node:n[a],env:r,k:t};const s={...e,index:a+1};return{type:"Eval",node:n[a],env:r,k:[s,...t]}}function va(e,t){return{type:"Value",value:e.returnResult?e.result:null,k:t}}function ba(e,t){const{bindingNodes:n,env:r,sourceCodeInfo:a,context:s}=e,o=[...e.levelStates],i=e.bindingLevel,l=o[i],c=l.index+1;if(c>=l.collection.length)return 0===i?va(e,t):ba({...e,bindingLevel:i-1},t);o[i]={...l,index:c};const u=n[i];return et(it(u[0][1][0],E(l.collection[c],a),e=>na(e,r)),n=>{Object.entries(n).forEach(([e,t])=>{s[e]={value:t}});const r=u[1];return r.length>0?xa({...e,levelStates:o,bindingLevel:i},o,r,0,t):wa({...e,levelStates:o,bindingLevel:i},o,t)})}function xa(e,t,n,r,a){const{env:s,context:o}=e;let i;for(let e=r;e<n.length;e++){const t=e;i=et(i,()=>{const e=n[t],[r,a]=e[1];return et(na(a,s),e=>et(it(r,e,e=>na(e,s)),e=>{Object.entries(e).forEach(([e,t])=>{o[e]={value:t}})}))})}return et(i,()=>wa({...e,levelStates:t},t,a))}function wa(e,t,n){const{bindingNodes:r,env:a}=e,s=r[e.bindingLevel],o=s[2],i=s[3];if(o){return{type:"Eval",node:o,env:a,k:[{...e,levelStates:t,phase:"evalWhen"},...n]}}if(i){return{type:"Eval",node:i,env:a,k:[{...e,levelStates:t,phase:"evalWhile"},...n]}}return ka({...e,levelStates:t},n)}function ka(e,t){const{bindingNodes:n,body:r,env:a}=e,s=e.bindingLevel+1;if(s<n.length){return{type:"Eval",node:n[s][0][1][1],env:a,k:[{...e,phase:"evalCollection",bindingLevel:s},...t]}}const o={...e,phase:"evalBody"};return{type:"Eval",node:r,env:a.create(e.context),k:[o,...t]}}function Aa(e,t,n,r,a){const s=Br("dvala.error"),o=[e.shortMessage];for(let n=0;n<t.length;n++){const r=t[n];if("TryWith"===r.type)for(const a of r.handlers)if(Na(a,s,r.env,e.sourceCodeInfo))return $a(a,r,o,t,n,e.sourceCodeInfo)}const i=Pr("dvala.error",n);return i.length>0?Ia("dvala.error",i,o,t,r,e.sourceCodeInfo,a):null}function Ea(e,t,r){for(let a=0;a<t.length;a++){const s=t[a];if("LoopIterate"===s.type){const{bindingNodes:o,bindingContext:i,body:l,env:c}=s,u=t.slice(a+1);if(e.length!==o.length)throw new n(`recur expected ${o.length} parameters, got ${e.length}`,r);const p=at(o,(t,n)=>et(it(t[1][0],te(e[n]),e=>na(e,c)),e=>{Object.entries(e).forEach(([e,t])=>{i[e]={value:t}})}));return et(p,()=>{const e=c.getContextsRaw()[0];if(e!==i)for(const[t,n]of Object.entries(i))e[t]=n;const t={type:"LoopIterate",bindingNodes:o,bindingContext:i,body:l,env:c,sourceCodeInfo:s.sourceCodeInfo};return{type:"Eval",node:l,env:c,k:[t,...u]}})}if("FnBody"===s.type){const{fn:n,outerEnv:r}=s,o=t.slice(a+1);return ma(n,e,r,s.sourceCodeInfo,o)}}throw new n("recur called outside of loop or function body",r)}function Na(e,t,r,a){if(T(e.effectRef))return e.effectRef.name===t.name;if(w(e.effectRef)){const s=ra(e.effectRef,[t],r,a);if(s instanceof Promise)throw new n("Effect handler predicates must be synchronous",a);return!!s}return!1}function $a(e,t,n,r,a,s){const o=[{type:"EffectResume",resumeK:r,sourceCodeInfo:s},...r.slice(a+1)];return da(M(na(e.handlerNode,t.env),t.sourceCodeInfo),[n],[],t.env,s,o)}function Sa(e,t,a,s,o,i,l){if("dvala.checkpoint"===e.name&&l){const e=t[0],n={continuation:Gr(a),timestamp:Date.now(),index:l.nextSnapshotIndex++,runId:l.runId,...void 0!==e?{meta:e}:{}};l.snapshots.push(n),void 0!==l.maxSnapshots&&l.snapshots.length>l.maxSnapshots&&l.snapshots.shift()}for(let n=0;n<a.length;n++){const r=a[n];if("TryWith"===r.type)for(const o of r.handlers)if(Na(o,e,r.env,s))return $a(o,r,t,a,n,s)}const c=Pr(e.name,o);if(c.length>0)return Ia(e.name,c,t,a,i,s,l);const u=function(e){const t=ta[e];if(t)return(e,n,r)=>(K(t.arity,e.length,r),t.handler(e,n,r))}(e.name);if(u)return u(t,a,s);if("dvala.error"===e.name){const e="string"==typeof t[0]?t[0]:String(t[0]??"Unknown error");throw new r(e,s)}throw new n(`Unhandled effect: '${e.name}'`,s)}function Ia(e,t,a,s,o,i,l){const c=o??(new AbortController).signal,u=Array.from(a);return function a(o){if(o>=t.length){if("dvala.error"===e){const e="string"==typeof u[0]?u[0]:String(u[0]??"Unknown error");return Promise.reject(new r(e,i))}return Promise.reject(new n(`Unhandled effect: '${e}'`,i))}const[,p]=t[o];return new Promise((t,r)=>{let f=!1;function d(e){if(f)throw new n(`Effect handler called ${e}() after already calling another operation`,i);f=!0}p({effectName:e,args:u,signal:c,resume:e=>{d("resume"),e instanceof Promise?e.then(e=>{t({type:"Value",value:e,k:s})},e=>{t({type:"Error",error:e instanceof n?e:new n(e instanceof Error?e:`${e}`,i),k:s})}):t({type:"Value",value:e,k:s})},fail:r=>{d("fail");t({type:"Error",error:new n(r??`Effect handler failed for '${e}'`,i),k:s})},suspend:e=>{d("suspend"),r(new Tr(s,l?l.snapshots:[],l?l.nextSnapshotIndex:0,e))},next:()=>{d("next"),a(o+1).then(t,r)},get snapshots(){return l?[...l.snapshots]:[]},checkpoint:e=>{if(!l)throw new n("checkpoint is not available outside effect-enabled execution",i);const t={continuation:Gr(s),timestamp:Date.now(),index:l.nextSnapshotIndex++,runId:l.runId,...void 0!==e?{meta:e}:{}};return l.snapshots.push(t),void 0!==l.maxSnapshots&&l.snapshots.length>l.maxSnapshots&&l.snapshots.shift(),t},resumeFrom:(e,t)=>{if(f)throw new n("Effect handler called resumeFrom() after already calling another operation",i);if(!l)throw new n("resumeFrom is not available outside effect-enabled execution",i);const a=l.snapshots.find(t=>t.index===e.index&&t.runId===e.runId);if(!a)throw new n(`Invalid snapshot: no snapshot with index ${e.index} found in current run`,i);f=!0,r(new Mr(a.continuation,t,a.index))}}).catch(e=>{f||(f=!0,Or(e)||Vr(e)?r(e):t({type:"Error",error:e instanceof n?e:new n(e instanceof Error?e:`${e}`,i),k:s}))})})}(0)}function ja(e,t){throw new Tr(e,[],0,t)}async function qa(e,t,n,r){return Ua({type:"Eval",node:e,env:t,k:[]},n,r)}function Ca(e){const t={},n=e.getHostValues();if(n)for(const[e,r]of Object.entries(n))t[e]=r;const r=e.getContextsRaw();for(let e=r.length-1;e>=0;e--)for(const[n,a]of Object.entries(r[e]))t[n]=a.value;return t}function Ra(e,t){return e instanceof Promise?e.then(e=>({type:"Value",value:e,k:t}),e=>({type:"Error",error:e instanceof n?e:new n(`${e}`,void 0),k:t})):{type:"Value",value:e,k:t}}function Pa(e,t,r,a){try{switch(e.type){case"Value":{if(0===e.k.length)return e;const[t,...n]=e.k;return ya(t,e.value,n)}case"Eval":return pa(e.node,e.env,e.k);case"Apply":return ya(e.frame,e.value,e.k);case"Perform":return Sa(e.effect,e.args,e.k,e.sourceCodeInfo,t,r,a);case"Parallel":return async function(e,t,r,a,s){const o=s??(new AbortController).signal,i=e.map(e=>qa(e,t,a,o)),l=await Promise.allSettled(i),c=[],u=[],p=[];for(let e=0;e<l.length;e++){const t=l[e];if("rejected"===t.status)p.push(new n(`${t.reason}`,void 0));else{const n=t.value;switch(n.type){case"completed":c.push({index:e,value:n.value});break;case"suspended":u.push({index:e,snapshot:n.snapshot});break;case"error":p.push(n.error)}}}if(p.length>0)throw p[0];if(u.length>0)return ja([{type:"ParallelResume",branchCount:e.length,completedBranches:c,suspendedBranches:u.slice(1)},...r],u[0].snapshot.meta);const f=Array.from({length:e.length});for(const{index:e,value:t}of c)f[e]=t;return{type:"Value",value:f,k:r}}(e.branches,e.env,e.k,t,r);case"Race":return async function(e,t,r,a,s){const o=s??(new AbortController).signal,i=e.map(()=>new AbortController),l=()=>{for(const e of i)e.abort(o.reason)};o.addEventListener("abort",l,{once:!0});try{let s=-1,o=null;const l=e.map(async(e,n)=>{const r=i[n].signal,l=await qa(e,t,a,r);if("completed"===l.type&&s<0){s=n,o=l.value;for(let e=0;e<i.length;e++)e!==n&&i[e].abort("race: branch lost")}return l}),c=await Promise.allSettled(l);if(s>=0)return{type:"Value",value:o,k:r};const u=[],p=[];for(let e=0;e<c.length;e++){const t=c[e];if("rejected"===t.status)p.push(new n(`${t.reason}`,void 0));else{const e=t.value;switch(e.type){case"suspended":u.push(e.snapshot.meta??null);break;case"error":p.push(e.error)}}}u.length>0&&ja(r,{type:"race",branches:u});const f=p.map(e=>e.message).join("; ");throw new n(`race: all branches failed: ${f}`,void 0)}finally{o.removeEventListener("abort",l)}}(e.branches,e.env,e.k,t,r);case"ParallelResume":return function(e){const{value:t,branchCount:n,completedBranches:r,suspendedBranches:a,k:s}=e,o=new Set(r.map(e=>e.index)),i=new Set(a.map(e=>e.index));let l=-1;for(let e=0;e<n;e++)if(!o.has(e)&&!i.has(e)){l=e;break}const c=[...r,{index:l,value:t}];if(a.length>0){const e=a[0];return ja([{type:"ParallelResume",branchCount:n,completedBranches:c,suspendedBranches:a.slice(1)},...s],e.snapshot.meta)}const u=Array.from({length:n});for(const{index:e,value:t}of c)u[e]=t;return{type:"Value",value:u,k:s}}(e);case"Error":{const n=Aa(e.error,e.k,t,r,a);if(null!==n)return n;throw e.error}}}catch(s){if(Or(s))throw s;if(s instanceof n){const n=Aa(s,"Value"===e.type?e.k.slice(1):e.k,t,r,a);if(null!==n)return n}throw s}}function Ta(e){let t=e;for(;;){if(t instanceof Promise)throw new n("Unexpected async operation in synchronous context. Use async.run() for async operations.",void 0);if("Value"===t.type&&0===t.k.length)return t.value;t=Pa(t)}}async function Oa(e){let t=e;for(;;){if(t instanceof Promise&&(t=await t),"Value"===t.type&&0===t.k.length)return t.value;t=Pa(t)}}function Ma(e,t){if(0===e.length)return{type:"Value",value:null,k:[]};if(1===e.length)return{type:"Eval",node:e[0],env:t,k:[]};const n={type:"Sequence",nodes:e,index:1,env:t};return{type:"Eval",node:e[0],env:t,k:[n]}}function Va(e,t){const r=Ma(e.body,t);try{return Ta(r)}catch(r){if(r instanceof n&&r.message.includes("Unexpected async operation")){return Oa(Ma(e.body,t))}throw r}}async function Ua(e,t,r,a,s,i){const l=null!=t&&"dvala.debug.step"in t,c={snapshots:a?a.snapshots:[],nextSnapshotIndex:a?a.nextSnapshotIndex:0,runId:"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),...void 0!==s?{maxSnapshots:s}:{}};let u=e;for(;;)try{for(;;){if(u instanceof Promise&&(u=await u),"Value"===u.type&&0===u.k.length)return{type:"completed",value:u.value};if(l&&"Eval"===u.type&&u.node[2]){const e=u.node[0];if(e===o.NormalExpression||e===o.SpecialExpression){const e={type:"DebugStep",phase:"awaitValue",sourceCodeInfo:u.node[2],env:u.env};u={...u,k:[e,...u.k]}}}u=Pa(u,t,r,c)}}catch(e){if(Vr(e)){const{k:t}=Hr(e.continuation,i),n=c.snapshots.findIndex(t=>t.index>e.trimToIndex);-1!==n&&c.snapshots.splice(n),u={type:"Value",value:e.value,k:t};continue}if(Or(e)){return{type:"suspended",snapshot:{continuation:Xr(e.k,e.snapshots,e.nextSnapshotIndex,e.meta),timestamp:Date.now(),index:c.nextSnapshotIndex++,runId:c.runId,meta:e.meta}}}return e instanceof n?{type:"error",error:e}:{type:"error",error:new n(`${e}`,void 0)}}}new Set(Object.keys(ta));const Ba={collection:'{\n map: (first-coll, ...args) -> do\n let fn = last(args);\n let other-colls = slice(args, 0, count(args) - 1);\n let all-colls = [first-coll, ...other-colls];\n\n cond\n case object?(first-coll) then do\n let expected-keys = keys(first-coll) |> sort;\n doseq (obj in other-colls) -> do\n if not(object?(obj)) then\n perform(effect(dvala.error), "Expected object")\n end;\n let obj-keys = keys(obj) |> sort;\n if not(obj-keys == expected-keys) then\n perform(effect(dvala.error), ++(\n "All objects must have the same keys. Expected: ",\n join(expected-keys, ", "),\n ". Found: ",\n join(obj-keys, ", ")\n ))\n end\n end;\n reduce(keys(first-coll), (acc, k) -> do\n let a = for (coll in all-colls) -> coll(k);\n assoc(acc, k, apply(fn, a))\n end, {})\n end\n\n case string?(first-coll) then do\n doseq (s in other-colls) -> do\n if not(string?(s)) then\n perform(effect(dvala.error), "Expected string")\n end\n end;\n let len = reduce(other-colls, (m, s) -> min(m, count(s)), count(first-coll));\n let mapped = for (i in range(len)) -> do\n let a = for (coll in all-colls) -> nth(coll, i);\n apply(fn, a)\n end;\n reduce(mapped, (acc, ch) -> do\n if not(string?(ch)) then\n perform(effect(dvala.error), "Expected string")\n end;\n ++(acc, ch)\n end, "")\n end\n\n case true then do\n doseq (x in other-colls) -> do\n if not(array?(x)) then\n perform(effect(dvala.error), "Expected array")\n end\n end;\n let len = reduce(other-colls, (m, x) -> min(m, count(x)), count(first-coll));\n for (i in range(len)) -> do\n let a = for (coll in all-colls) -> nth(coll, i);\n apply(fn, a)\n end\n end\n end\n end,\n\n filter: (coll, fn) -> do\n cond\n case array?(coll) then\n reduce(coll, (acc, elem) -> if fn(elem) then [...acc, elem] else acc end, [])\n\n case string?(coll) then\n reduce(coll, (acc, ch) -> if fn(ch) then ++(acc, ch) else acc end, "")\n\n case object?(coll) then\n reduce(keys(coll), (acc, k) -> do\n if fn(coll(k)) then\n assoc(acc, k, coll(k))\n else\n acc\n end\n end, {})\n\n case true then\n perform(effect(dvala.error), "Expected collection")\n end\n end,\n\n reduce: (coll, fn, initial) -> do\n cond\n case string?(coll) then\n loop (acc = initial, i = 0) -> do\n if i >= count(coll) then\n acc\n else\n recur(fn(acc, nth(coll, i)), i + 1)\n end\n end\n\n case array?(coll) then\n loop (acc = initial, i = 0) -> do\n if i >= count(coll) then\n acc\n else\n recur(fn(acc, nth(coll, i)), i + 1)\n end\n end\n\n case object?(coll) then do\n let values = vals(coll);\n loop (acc = initial, i = 0) -> do\n if i >= count(values) then\n acc\n else\n recur(fn(acc, nth(values, i)), i + 1)\n end\n end\n end\n\n case true then\n perform(effect(dvala.error), "Expected collection")\n end\n end\n}',sequence:'{\n some: (seq, fn) -> do\n if null?(seq) then null\n else do\n loop (i = 0) -> do\n if i >= count(seq) then\n null\n else do\n let elem = nth(seq, i);\n if fn(elem) then elem\n else recur(i + 1)\n end\n end\n end\n end\n end\n end\n end,\n\n take-while: (seq, fn) -> do\n let is-str = string?(seq);\n let len = count(seq);\n let idx = loop (i = 0) -> do\n if i >= len then\n len\n else if fn(nth(seq, i)) then\n recur(i + 1)\n else\n i\n end\n end\n end;\n slice(seq, 0, idx)\n end,\n\n drop-while: (seq, fn) -> do\n let is-str = string?(seq);\n let len = count(seq);\n let idx = loop (i = 0) -> do\n if i >= len then\n len\n else if fn(nth(seq, i)) then\n recur(i + 1)\n else\n i\n end\n end\n end;\n slice(seq, idx)\n end,\n\n sort: (seq, ...args) -> do\n let cmp = if count(args) == 0 then compare else first(args) end;\n let is-str = string?(seq);\n let arr = if is-str then split(seq, "") else seq end;\n let len = count(arr);\n\n // merge two sorted arrays\n let merge-arrays = (left, right) -> do\n let left-len = count(left);\n let right-len = count(right);\n loop (result = [], li = 0, ri = 0) -> do\n if li >= left-len then\n ++(result, slice(right, ri))\n else if ri >= right-len then\n ++(result, slice(left, li))\n else do\n let l = nth(left, li);\n let r = nth(right, ri);\n if cmp(l, r) <= 0 then\n recur(push(result, l), li + 1, ri)\n else\n recur(push(result, r), li, ri + 1)\n end\n end\n end\n end\n end\n end;\n\n // recursive merge-sort\n let merge-sort = (a) -> do\n let n = count(a);\n if n <= 1 then a\n else do\n let mid = floor(n / 2);\n let left = merge-sort(slice(a, 0, mid));\n let right = merge-sort(slice(a, mid));\n merge-arrays(left, right)\n end\n end\n end;\n\n let sorted = merge-sort(arr);\n if is-str then join(sorted, "") else sorted end\n end\n}\n',array:'{\n mapcat: (arr, fn) -> do\n flatten(map(arr, fn), 1)\n end,\n\n moving-fn: (arr, window-size, fn) -> do\n if window-size > count(arr) then\n perform(effect(dvala.error), "Expected window-size <= array length")\n end;\n for (i in range(count(arr) - window-size + 1)) -> do\n fn(slice(arr, i, i + window-size))\n end\n end,\n\n running-fn: (arr, fn) -> do\n for (i in range(count(arr))) -> do\n fn(slice(arr, 0, i + 1))\n end\n end\n}\n',functional:'{\n "|>": (a, b) -> b(a),\n\n apply: (fn, ...args) -> do\n let arr = last(args);\n let leading = slice(args, 0, count(args) - 1);\n fn(...leading, ...arr)\n end\n}\n',object:'{\n merge-with: (...args) -> do\n let fn = last(args);\n let objs = slice(args, 0, count(args) - 1);\n if not(function?(fn)) then\n perform(effect(dvala.error), str("Expected function, got: ", type(fn)))\n end;\n if count(objs) == 0 then\n perform(effect(dvala.error), "Expected at least one object argument")\n end;\n reduce(rest(objs), (result, obj) -> do\n if not(object?(obj)) then\n perform(effect(dvala.error), str("Expected object, got: ", type(obj)))\n end;\n reduce(keys(obj), (res, key) -> do\n if contains?(res, key) then\n assoc(res, key, fn(get(res, key), get(obj, key)))\n else\n assoc(res, key, get(obj, key))\n end\n end, result)\n end, do\n let f = first(objs);\n if not(object?(f)) then\n perform(effect(dvala.error), str("Expected object, got: ", type(f)))\n end;\n f\n end)\n end\n}\n'};let Da=!1;function _a(e){!function(){if(!Da){Da=!0;for(const[,e]of Object.entries(Ba)){const t=Va({body:fr(dr(jr(e,!1,void 0),{removeWhiteSpace:!0})),hasDebugData:!1},Ht());if(t instanceof Promise)throw new TypeError("Core dvala sources must be synchronous");if(!I(t))continue;const n=t;for(const[e,t]of Object.entries(n)){const n=Le[e];n&&w(t)&&"UserDefined"===t.functionType&&(n.dvalaImpl=t)}}}}();const t=[];let r=-1;const a=e?.handlers??{},s=e?.bindings,o=e?.modules,i={...a,"dvala.debug.step":async e=>{e.suspend(e.args[0])}};function l(e){if("suspended"===e.type){const n=function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return{expression:"",value:null,location:{line:0,column:0},env:{}};const t=e,n=t.location;return{expression:t.expression??"",value:t.value,location:{line:n?.line??0,column:n?.column??0},env:t.env??{}}}(e.snapshot.meta??null),a={snapshot:e.snapshot,step:n,timestamp:Date.now()};t.length=r+1,t.push(a),r=t.length-1}else e.type;return e}async function c(e,t){try{const n=o?new Map(o.map(e=>[e.name,e])):void 0,r=Hr(e.continuation,{values:s,modules:n});return await async function(e,t,n,r,a){return Ua({type:"Value",value:t,k:e},n,(new AbortController).signal,r,r?.maxSnapshots,a)}(r.k,t,i,{snapshots:r.snapshots,nextSnapshotIndex:r.nextSnapshotIndex},{values:s,modules:n})}catch(e){return e instanceof n?{type:"error",error:e}:{type:"error",error:new n(`${e}`,void 0)}}}const u={get history(){return t},get currentStep(){return r},get current(){return r>=0&&r<t.length?t[r]:void 0},async run(e){t.length=0,r=-1;try{const t=o?new Map(o.map(e=>[e.name,e])):void 0,n=Ht({bindings:s},t),r=function(e){return{body:fr(dr(jr(e,!0,void 0),{removeWhiteSpace:!0})),hasDebugData:!0}}(e),a=await async function(e,t,n,r,a){const s=(new AbortController).signal;return Ua(Ma(e.body,t),n,s,void 0,r,a)}(r,n,i,void 0,{values:s,modules:t});return l(a)}catch(e){return e instanceof n?{type:"error",error:e}:{type:"error",error:new n(`${e}`,void 0)}}},async stepForward(){if(r<t.length-1)return r++,{type:"suspended",snapshot:t[r].snapshot};if(r<0||r>=t.length)return{type:"error",error:new n("No current step to advance from",void 0)};const e=t[r];return l(await c(e.snapshot,e.step.value))},async stepBackward(){if(r<=0)return{type:"error",error:new n("Already at the beginning of execution history",void 0)};r--;return{type:"suspended",snapshot:t[r].snapshot}},async jumpTo(e){if(e<0||e>=t.length)return{type:"error",error:new n(`Step index ${e} out of range (0..${t.length-1})`,void 0)};r=e;return{type:"suspended",snapshot:t[r].snapshot}},async rerunFrom(e,a){if(e<0||e>=t.length)return{type:"error",error:new n(`Step index ${e} out of range (0..${t.length-1})`,void 0)};r=e,t.length=e+1;const s=t[e];return l(await c(s.snapshot,a))}};return u}export{_a as createDebugger};
1
+ function e(e){if(!e.position||!e.code)return"";const t=e.position.column-1,n=e.code.length-t-1;return`${" ".repeat(Math.max(t,0))}^${" ".repeat(Math.max(n,0))}`}class t extends Error{params;constructor(e){super(`recur, params: ${e}`),Object.setPrototypeOf(this,t.prototype),this.name="RecurSignal",this.params=e}}class n extends Error{sourceCodeInfo;shortMessage;constructor(t,r){const a=t instanceof Error?t.message:`${t}`;super(function(t,n){if(!n)return t;const r=`${n.position.line}:${n.position.column}`;return`${t}${n.filePath?`\n${n.filePath}:${r}`:`\nLocation ${r}`}\n${n.code}\n${e(n)}`}(a,r)),this.shortMessage=a,this.sourceCodeInfo=r,Object.setPrototypeOf(this,n.prototype),this.name="DvalaError"}getCodeMarker(){return this.sourceCodeInfo&&e(this.sourceCodeInfo)}}class r extends n{userMessage;constructor(e,t){super(e,t),this.userMessage=e,Object.setPrototypeOf(this,r.prototype),this.name="UserDefinedError"}}class a extends n{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype),this.name="AssertionError"}}class s extends n{symbol;constructor(e,t){super(`Undefined symbol '${e}'.`,t),this.symbol=e,Object.setPrototypeOf(this,s.prototype),this.name="UndefinedSymbolError"}}const o={Number:1,String:2,NormalExpression:3,SpecialExpression:4,UserDefinedSymbol:5,NormalBuiltinSymbol:6,SpecialBuiltinSymbol:7,ReservedSymbol:8,Binding:9,Spread:10},i=new Set(Object.values(o));function l(e){return Object.keys(o).find(t=>o[t]===e)}const c=new Set(["UserDefined","Partial","Comp","Constantly","Juxt","Complement","EveryPred","SomePred","Fnull","EffectMatcher","Builtin","SpecialBuiltin","Module"]);const u="^^fn^^",p="^^re^^",f="^^ef^^";function d(e){return null!==e&&"object"==typeof e&&(u in e&&"functionType"in e&&function(e){return"string"==typeof e&&c.has(e)}(e.functionType))}function m(e){return!(!Array.isArray(e)||e.length<2)&&function(e){return"number"==typeof e&&i.has(e)}(e[0])}function y(e){return d(e)?`<function ${e.name||"λ"}>`:m(e)?`${l(e[0])}-node`:null===e?"null":"object"==typeof e&&e instanceof RegExp?`${e}`:"object"==typeof e&&e instanceof Error?e.toString():JSON.stringify(e)}function g(e,t){return e?.sourceCodeInfo??t}function h(e,t,r){return new n(`Expected ${e}, got ${y(t)}.`,g(t,r))}function v(e,t){return b(e,t),e}function b(e,t){if(!function(e){return void 0!==e}(e))throw new n("Unexpected undefined",g(e,t))}function x(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function w(e){return null!==e&&"object"==typeof e&&!!e[u]}function k(e){return w(e)&&"UserDefined"===e.functionType}function A(e){return void 0!==e}function E(e,t){return N(e,t),e}function N(e,t){if(!A(e))throw h("not undefined",e,t)}function $(e){return Array.isArray(e)||"string"==typeof e}function S(e,t){if(!$(e))throw h("string or array",e,t)}function I(e){return!(null===e||"object"!=typeof e||Array.isArray(e)||e instanceof RegExp||w(e)||R(e)||T(e))}function j(e,t){if(!I(e))throw h("object",e,t)}function q(e){return $(e)||I(e)}function C(e,t){if(!q(e))throw h("string, array or object",e,t)}function R(e){return null!==e&&"object"==typeof e&&!!e[p]}function P(e,t){if(!function(e){return R(e)||"string"==typeof e}(e))throw h("string or RegularExpression",e,t)}function T(e){return null!==e&&"object"==typeof e&&!!e[f]}function O(e,t){if(!T(e))throw h("Effect",e,t)}function M(e,t){return V(e,t),e}function V(e,t){if(!function(e){return"number"==typeof e||!!q(e)||!!w(e)}(e))throw h("FunctionLike",e,t)}function U(e,t={}){return"string"==typeof e&&((!t.nonEmpty||0!==e.length)&&(!t.char||1===e.length))}function B(e,t,n={}){if(!U(e,n))throw h(""+(n.nonEmpty?"non empty string":n.char?"character":"string"),e,t)}function D(e,t,n={}){return B(e,t,n),e}function _(e){return"string"==typeof e||"number"==typeof e}function F(e,t){return L(e,t),e}function L(e,t){if(!_(e))throw h("string or number",e,t)}const z={assert:{evaluate:(e,t)=>{const n=e[0],r=2===e.length?e[1]:`${n}`;if(B(r,t),!n)throw new a(r,t);return E(n,t)},arity:{min:1,max:2},docs:{category:"assertion",description:"If $value is falsy it throws `AssertionError` with $message. If no $message is provided, message is set to $value.",returns:{type:"any"},args:{value:{type:"any"},message:{type:"string"}},variants:[{argumentNames:["value"]},{argumentNames:["value","message"]}],examples:['do assert(0, "Expected a positive value") with case effect(dvala.error) then ([msg]) -> msg end'],seeAlso:["assertion.assert-truthy","assertion.assert-true"],hideOperatorForm:!0}}};function W(e,t={}){return"number"==typeof e&&(!Number.isNaN(e)&&(!(t.integer&&!Number.isInteger(e))&&(!(t.finite&&!Number.isFinite(e))&&((!t.zero||0===e)&&((!t.nonZero||0!==e)&&(!(t.positive&&e<=0)&&(!(t.negative&&e>=0)&&(!(t.nonPositive&&e>0)&&(!(t.nonNegative&&e<0)&&(!("number"==typeof t.gt&&e<=t.gt)&&(!("number"==typeof t.gte&&e<t.gte)&&(!("number"==typeof t.lt&&e>=t.lt)&&!("number"==typeof t.lte&&e>t.lte)))))))))))))}function J(e,t,r={}){if(!W(e,r))throw new n(`Expected ${function(e){if(e.zero)return"zero";const t=function(e){return e.positive?"positive":e.negative?"negative":e.nonNegative?"non negative":e.nonPositive?"non positive":e.nonZero?"non zero":""}(e),n=e.integer?"integer":"number",r=e.finite?"finite":"",a=function(e){return"number"!=typeof e.gt&&"number"!=typeof e.gte||"number"!=typeof e.lt&&"number"!=typeof e.lte?"number"==typeof e.gt||"number"==typeof e.gte?"number"==typeof e.gt?`n > ${e.gt}`:`n >= ${e.gte}`:"number"==typeof e.lt||"number"==typeof e.lte?"number"==typeof e.lt?`n < ${e.lt}`:`n <= ${e.lte}`:"":`${"number"==typeof e.gt?`${e.gt} < n `:`${e.gte} <= n `}${"number"==typeof e.lt?`< ${e.lt}`:`<= ${e.lte}`}`}(e);return[t,r,n,a].filter(e=>!!e).join(" ")}(r)}, got ${y(e)}.`,g(e,t))}function Y(e,t){const{min:n}=e;return!("number"==typeof n&&t<n)}function K(e,t,r){const{min:a,max:s}=e;if("number"==typeof a&&t<a)throw new n(`Wrong number of arguments, expected at least ${a}, got ${y(t)}.`,r);if("number"==typeof s&&t>s)throw new n(`Wrong number of arguments, expected at most ${s}, got ${y(t)}.`,r)}function G(e){return{min:e,max:e}}function X(e,t){return{a:{type:e},b:{type:t}}}const H={"<<":{evaluate:([e,t],n)=>(J(e,n,{integer:!0}),J(t,n,{integer:!0,nonNegative:!0}),e<<t),arity:G(2),docs:{category:"bitwise",returns:{type:"integer"},args:{...X("integer","integer")},variants:[{argumentNames:["a","b"]}],description:"Shifts $a arithmetically left by $b bit positions.",seeAlso:[">>",">>>"],examples:["1 << 10","<<(1, 10)","<<(-4, 2)"]}},">>":{evaluate:([e,t],n)=>(J(e,n,{integer:!0}),J(t,n,{integer:!0,nonNegative:!0}),e>>t),arity:G(2),docs:{category:"bitwise",returns:{type:"integer"},args:{...X("integer","integer")},variants:[{argumentNames:["a","b"]}],description:"Shifts $a arithmetically right by $b bit positions.",seeAlso:["<<",">>>"],examples:["2048 >> 10",">>(2048, 10)",">>>(-16, 2)",">>(4, 10)"]}},">>>":{evaluate:([e,t],n)=>(J(e,n,{integer:!0}),J(t,n,{integer:!0,nonNegative:!0}),e>>>t),arity:G(2),docs:{category:"bitwise",returns:{type:"integer"},args:{...X("integer","integer")},variants:[{argumentNames:["a","b"]}],description:"Shifts $a arithmetically right by $b bit positions without sign extension.",seeAlso:["<<",">>"],examples:["-16 >>> 2",">>>(2048, 10)",">>>(-16, 2)",">>>(4, 10)",">>>(-1, 10)"]}},"&":{evaluate:([e,...t],n)=>(J(e,n,{integer:!0}),t.reduce((e,t)=>(J(t,n,{integer:!0}),e&t),e)),arity:{min:2},docs:{category:"bitwise",returns:{type:"integer"},args:{...X("integer","integer"),c:{type:"integer",rest:!0}},variants:[{argumentNames:["a","b"]},{argumentNames:["a","b","c"]}],description:"Returns bitwise `and` of all arguments.",seeAlso:["|","xor","bitwise.bit-not","bitwise.bit-and-not"],examples:["0b0011 & 0b0110","&(0b0011, 0b0110)","&(0b0011, 0b0110, 0b1001)"]}},"|":{evaluate:([e,...t],n)=>(J(e,n,{integer:!0}),t.reduce((e,t)=>(J(t,n,{integer:!0}),e|t),e)),arity:{min:2},docs:{category:"bitwise",returns:{type:"integer"},args:{...X("integer","integer"),c:{type:"integer",rest:!0}},variants:[{argumentNames:["a","b"]},{argumentNames:["a","b","c"]}],description:"Returns bitwise `or` of all arguments.",seeAlso:["&","xor","bitwise.bit-not","bitwise.bit-and-not"],examples:["0b0011 | 0b0110","|(0b0011, 0b0110)","|(0b1000, 0b0100, 0b0010)"]}},xor:{evaluate:([e,...t],n)=>(J(e,n,{integer:!0}),t.reduce((e,t)=>(J(t,n,{integer:!0}),e^t),e)),arity:{min:2},docs:{category:"bitwise",returns:{type:"integer"},args:{...X("integer","integer"),c:{type:"integer",rest:!0}},variants:[{argumentNames:["a","b"]},{argumentNames:["a","b","c"]}],description:"Returns bitwise `xor` of all arguments.",seeAlso:["&","|","bitwise.bit-not","bitwise.bit-and-not"],examples:["0b0011 xor 0b0110","xor(0b0011, 0b0110)","xor(0b11110000, 0b00111100, 0b10101010)"]}}};function Z(e,t){return!!q(e)&&("string"==typeof e||Array.isArray(e)?!!W(t,{integer:!0})&&(t>=0&&t<e.length):!!Object.getOwnPropertyDescriptor(e,t))}function Q(e,t,r){if(L(e,r),L(t,r),"string"==typeof e&&"string"==typeof t)return e<t?-1:e>t?1:0;if("number"==typeof e&&"number"==typeof t)return Math.sign(e-t);throw new n(`Cannot compare values of different types: ${typeof e} and ${typeof t}`,r)}function ee(e,t,n){if(e===t)return!0;if("number"==typeof e&&"number"==typeof t)return function(e,t,n=ae){if(e===t)return!0;const r=Math.abs(e-t);if(0===e||0===t||r<n)return r<n;const a=Math.abs(e),s=Math.abs(t);return r/(a+s)<n}(e,t);if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(!ee(E(e[r],n),E(t[r],n),n))return!1;return!0}if(R(e)&&R(t))return e.s===t.s&&e.f===t.f;if(x(e)&&x(t)){const r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(let a=0;a<r.length;a+=1){const s=D(r[a],n);if(!ee(e[s],t[s],n))return!1}return!0}return!1}function te(e){return e??null}function ne(...e){const t=new Set;for(const n of e)n.forEach(e=>t.add(e));return t}function re(e,t){t.forEach(t=>e.add(t))}const ae=1e-10;function se(e,t=0){const n=e.split("\n");for(;n[0]?.match(/^\s*$/);)n.shift();for(;n[n.length-1]?.match(/^\s*$/);)n.pop();const r=n.reduce((e,t)=>{if(t.match(/^\s*$/))return e;const n=t.match(/^\s*/)[0].length;return Math.min(e,n)},1/0);return n.map(e=>" ".repeat(t)+e.slice(r)).join("\n").trimEnd()}function oe(e,t){if(!Array.isArray(e))throw h("array",e,t)}function ie(e,t){if(!function(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}(e))throw h("array of strings",e,t)}function le(e,t){if(!function(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e&&1===e.length)}(e))throw h("array of strings",e,t)}const ce={filter:{evaluate:()=>{throw new Error("filter is implemented in Dvala")},arity:G(2),docs:{category:"collection",returns:{type:"collection"},args:{a:{type:"collection"},b:{type:"function"},coll:{type:"collection"},fun:{type:"function"}},variants:[{argumentNames:["coll","fun"]}],description:"Creates a new collection with all elements that pass the test implemented by $fun.",seeAlso:["collection.filteri","map","sequence.remove"],examples:['\nfilter(\n ["Albert", "Mojir", 160, [1, 2]],\n string?\n)',"\nfilter(\n [5, 10, 15, 20],\n -> $ > 10\n)","\nfilter(\n { a: 1, b: 2 },\n odd?\n)"]}},map:{evaluate:()=>{throw new Error("map is implemented in Dvala")},arity:{min:2},docs:{category:"collection",returns:{type:"collection"},args:{a:{type:"collection"},b:{type:"function"},colls:{type:"collection",rest:!0,description:"At least one."},fun:{type:"function"}},variants:[{argumentNames:["colls","fun"]}],description:"Creates a new collection populated with the results of calling $fun on every element in $colls.",seeAlso:["collection.mapi","filter","reduce","mapcat","grid.cell-map","grid.cell-mapi"],examples:["[1, 2, 3] map -","[1, 2, 3] map -> -($)",'map(["Albert", "Mojir", 42], str)',"map([1, 2, 3], inc)","map([1, 2, 3], [1, 10, 100], *)","map({ a: 1, b: 2 }, inc)","map({ a: 1, b: 2 }, { a: 10, b: 20 }, +)"]}},reduce:{evaluate:()=>{throw new Error("reduce is implemented in Dvala")},arity:G(3),docs:{category:"collection",returns:{type:"any"},args:{fun:{type:"function"},coll:{type:"collection"},initial:{type:"any"}},variants:[{argumentNames:["coll","fun","initial"]}],description:"Runs $fun function on each element of the $coll, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the $coll is a single value.",seeAlso:["collection.reduce-right","collection.reducei","collection.reductions","map","grid.cell-reduce","grid.cell-reducei"],examples:["reduce([1, 2, 3], +, 0)","reduce([], +, 0)","reduce({ a: 1, b: 2 }, +, 0)","\nreduce(\n [1, 2, 3, 4, 5, 6, 7, 8, 9],\n (result, value) -> result + (even?(value) ? value : 0),\n 0)"]}},get:{evaluate:(e,t)=>{const[n,r]=e,a=te(e[2]);if(L(r,t),null===n)return a;C(n,t);const s=function(e,t){if(I(e)){if("string"==typeof t&&Z(e,t))return te(e[t])}else if(W(t,{nonNegative:!0,integer:!0})&&t>=0&&t<e.length)return te(e[t])}(n,r);return void 0===s?a:s},arity:{min:2,max:3},docs:{category:"collection",returns:{type:"any"},args:{a:{type:"collection"},b:{type:["string","integer"]},"not-found":{type:"any",description:"Default value to return if $b is not found."}},variants:[{argumentNames:["a","b"]},{argumentNames:["a","b","not-found"]}],description:"Returns value in $a mapped at $b.",seeAlso:["collection.get-in","contains?","find","nth"],examples:["[1, 2, 3] get 1",'{ a: 1 } get "a"','"Albert" get "3"',"\nget(\n [1, 2, 3],\n 1, // Optional comma after last argument\n)","\nget(\n [],\n 1\n)",'\nget(\n [],\n 1,\n "default"\n)','\nget(\n { a: 1 },\n "a"\n)','\nget(\n { a: 1 },\n "b"\n)','\nget(\n { a: 1 },\n "b",\n "default"\n)','\nget(\n null,\n "a"\n)','\nget(\n null,\n "b",\n "default"\n)']}},count:{evaluate:([e],t)=>null===e?0:"string"==typeof e?e.length:(C(e,t),Array.isArray(e)?e.length:Object.keys(e).length),arity:G(1),docs:{category:"collection",returns:{type:"number"},args:{coll:{type:["collection","null"]}},variants:[{argumentNames:["coll"]}],description:"Returns number of elements in $coll.",seeAlso:["empty?"],examples:["count([1, 2, 3])","count([])","count({ a: 1 })",'count("")','count("Albert")',"count(null)"]}},"contains?":{evaluate:([e,t],n)=>null!==e&&(C(e,n),U(e)?(B(t,n),e.includes(t)):$(e)?(N(t,n),!!e.find(e=>ee(E(e),t,n))):(B(t,n),t in e)),arity:G(2),docs:{category:"collection",returns:{type:"boolean"},args:{a:{type:["collection","null"]},b:{type:["string","integer"]}},variants:[{argumentNames:["a","b"]}],description:"Returns `true` if $a contains $b, otherwise returns `false`. For strings, it checks if substring is included.",seeAlso:["get","find","index-of"],examples:["[1, 2, 3] contains? 1","null contains? 1",'{ a: 1, b: 2 } contains? "a"',"\ncontains?(\n [],\n 1\n)","\ncontains?(\n [1],\n 1\n)","\ncontains?(\n [1, 2, 3],\n 1\n)",'\ncontains?(\n {},\n "a"\n)','\ncontains?(\n { a: 1, b: 2 },\n "a"\n)']}},assoc:{evaluate:([e,t,n],r)=>(C(e,r),L(t,r),N(n,r),function(e,t,n,r){if(C(e,r),L(t,r),Array.isArray(e)||"string"==typeof e){if(J(t,r,{integer:!0}),J(t,r,{gte:0}),J(t,r,{lte:e.length}),"string"==typeof e)return B(n,r,{char:!0}),`${e.slice(0,t)}${n}${e.slice(t+1)}`;const a=[...e];return a[t]=n,a}B(t,r);const a={...e};return a[t]=n,a}(e,t,n,r)),arity:G(3),docs:{category:"collection",returns:{type:"collection"},args:{coll:{type:"collection"},key:{type:["string","number"]},value:{type:"any"},kvs:{type:"any",description:"Key-value pairs to associate.",rest:!0}},variants:[{argumentNames:["coll","key","value"]},{argumentNames:["coll","key","value","kvs"]}],description:"\nAdd or replace the value of element $key to $value in $coll. Repeated for all key-value pairs in $kvs.\nIf $coll is an 'array', $key must be `number` satisfying `0 <=` $key `<= length`.",seeAlso:["collection.assoc-in","dissoc","merge","collection.update"],examples:['\nassoc(\n [1, 2, 3],\n 1,\n "Two"\n)','\nassoc(\n [1, 2, 3],\n 3,\n "Four"\n)','\nassoc(\n { a: 1, b: 2 },\n "a",\n "One")','\nassoc(\n { a: 1, b: 2 },\n "c",\n "Three")','\nassoc(\n "Albert",\n 6,\n "a")']}},"++":{evaluate:(e,t)=>(W(e[0])||C(e[0],t),Array.isArray(e[0])?e.reduce((e,n)=>(oe(n,t),e.concat(n)),[]):_(e[0])?e.reduce((e,n)=>(L(n,t),`${e}${n}`),""):e.reduce((e,n)=>(j(n,t),Object.assign(e,n)),{})),arity:{min:1},docs:{category:"collection",returns:{type:"collection"},args:{a:{type:"collection"},b:{type:"collection"},colls:{type:"collection",rest:!0}},variants:[{argumentNames:["a"]},{argumentNames:["a","colls"]}],description:"Concatenates collections into one collection.",seeAlso:["mapcat","str","join","push","sequence.unshift"],examples:['"Albert" ++ " " ++ "Mojir"','"Albert" ++ "Mojir"','++("Albert", "-", "Mojir")','++("Albert")','++("A", "l", "b", "e", "r", "t")',"++([1, 2], [3, 4])","++([], [3, 4])","++([1, 2], [])","++([1, 2], [3, 4], [5, 6])","++([])","++({ a: 1, b: 2 }, { b: 1, c: 2 })","++({}, { a: 1 })"]}}},ue={range:{evaluate:(e,t)=>{const[n,r,a]=e;let s,o,i;J(n,t,{finite:!0}),1===e.length?(s=0,o=n,i=o>=0?1:-1):2===e.length?(J(r,t,{finite:!0}),s=n,o=r,i=o>=s?1:-1):(J(r,t,{finite:!0}),J(a,t,{finite:!0}),s=n,o=r,i=a,J(i,t,o>s?{positive:!0}:o<s?{negative:!0}:{nonZero:!0}));const l=[];for(let e=s;i<0?e>o:e<o;e+=i)l.push(e);return l},arity:{min:1,max:3},docs:{category:"array",returns:{type:"number",array:!0},args:{a:{type:"number"},b:{type:"number"},step:{type:"number"}},variants:[{argumentNames:["b"]},{argumentNames:["a","b"]},{argumentNames:["a","b","step"]}],description:"$range creates an array with a range of numbers from $a to $b (exclusive), by $step.\n\n$a defaults to 0.\n$step defaults to 1.",seeAlso:["repeat","vector.linspace"],examples:["range(4)","range(1, 4)","1 range 10","range(0.4, 4.9)","\nrange(\n 0.25, // start value\n 1, // end value (exclusive)\n 0.25, // step value\n)"]}},repeat:{evaluate:([e,t],n)=>{J(t,n,{integer:!0,nonNegative:!0});const r=[];for(let n=0;n<t;n+=1)r.push(e);return r},arity:G(2),docs:{category:"array",returns:{type:"any",array:!0},args:{a:{type:"any"},b:{type:"integer"}},variants:[{argumentNames:["a","b"]}],description:"Returns an array with $a repeated $b times.",seeAlso:["range","string.string-repeat"],examples:["repeat(10, 3)","repeat(10, 0)",'"Albert" repeat 5']}},flatten:{evaluate:([e,t],n)=>{oe(e,n);const r=void 0===t||t===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:function(e,t,n={}){return J(e,t,n),e}(t,n,{integer:!0,nonNegative:!0});return e.flat(r)},arity:{min:1,max:2},docs:{category:"array",returns:{type:"any",array:!0},args:{x:{type:["array","any"],description:"If $x is not an array, `[ ]` is returned."},depth:{type:"integer",description:"The depth level specifying how deep a nested array structure should be flattened. Defaults to `Infinity`."}},variants:[{argumentNames:["x"]},{argumentNames:["x","depth"]}],description:"Takes a nested array $x and flattens it.",seeAlso:["mapcat"],examples:["flatten([1, 2, [3, 4], 5])","flatten([1, [2, [3, [4]]]], 1)","flatten([1, [2, [3, [4]]]], 2)",'\nlet foo = "bar";\nflatten([\n 1,\n " 2 A ",\n [foo, [4, ["ABC"]]],\n 6,\n])'],hideOperatorForm:!0}},mapcat:{evaluate:()=>{throw new Error("mapcat is implemented in Dvala")},arity:G(2),docs:{category:"array",returns:{type:"collection"},args:{a:{type:"collection"},b:{type:"function"},colls:{type:"collection",array:!0},fun:{type:"function"}},variants:[{argumentNames:["colls","fun"]}],description:"Returns the result of applying concat to the result of applying map to $fun and $colls.",seeAlso:["flatten","map","++"],examples:["[[3, 2, 1, 0], [6, 5, 4], [9, 8, 7]] mapcat reverse","mapcat([[3, 2, 1, 0], [6, 5, 4], [9, 8, 7]], reverse)","[[3, 2, 1, 0,], [6, 5, 4,], [9, 8, 7]] mapcat reverse","\nlet foo = (n) -> do\n [n - 1, n, n + 1]\nend;\n[1, 2, 3] mapcat foo","\nmapcat(\n [[1, 2], [2, 2], [2, 3]],\n -> $ filter odd?\n)"]}},"moving-fn":{evaluate:()=>{throw new Error("moving-fn is implemented in Dvala")},arity:G(3),docs:{category:"array",returns:{type:"array"},args:{arr:{type:"array"},windowSize:{type:"number",description:"The size of the moving window."},fn:{type:"function"}},variants:[{argumentNames:["arr","windowSize","fn"]}],description:"Returns the result of applying $fn to each moving window of size $windowSize in $arr.",seeAlso:["running-fn","vector.moving-mean"],examples:["moving-fn([1, 2, 3], 2, sum)","moving-fn([1, 2, 3], 1, sum)","moving-fn([1, 2, 3], 3, sum)"]}},"running-fn":{evaluate:()=>{throw new Error("running-fn is implemented in Dvala")},arity:G(2),docs:{category:"array",returns:{type:"array"},args:{a:{type:"array"},b:{type:"function"}},variants:[{argumentNames:["a","b"]}],description:"Returns the result of applying $b to each element of $a.",seeAlso:["moving-fn","vector.running-mean"],examples:["running-fn([1, 2, 3], sum)","running-fn([1, 2, 3], max)","running-fn([1, 2, 3], min)"]}}},pe={nth:{evaluate:(e,t)=>{const[n,r]=e,a=te(e[2]);if(J(r,t,{integer:!0}),null===n)return a;if(S(n,t),r>=0&&r<n.length){return te(n[r])}return a},arity:{min:2,max:3},docs:{category:"sequence",returns:{type:"any"},args:{a:{type:"sequence"},b:{type:"integer"},seq:{type:["sequence","null"]},n:{type:"integer"},"not-found":{type:"any"}},variants:[{argumentNames:["seq","n"]},{argumentNames:["seq","n","not-found"]}],description:"Accesses element $n of $seq. Accessing out-of-bounds indices returns $not-found, if present, else `null`.",seeAlso:["first","second","last","get","slice"],examples:["[1, 2, 3] nth 1",'"A string" nth 3',"nth([1, 2, 3], 1)","nth([1, 2, 3], 3)","nth([1, 2, 3], -1)","nth([1, 2, 3], 3, 99)",'nth("A string", 1)','nth("A string", 3)','nth("A string", -3)','nth("A string", 30, "X")',"nth(null, 1)",'nth(null, 1, "Default value")']}},first:{evaluate:([e],t)=>{if(null===e)return null;S(e,t);return te(e[0])},arity:G(1),docs:{category:"sequence",returns:{type:"any"},args:{seq:{type:["sequence","null"]}},variants:[{argumentNames:["seq"]}],description:"Returns the first element of $seq. If $seq is empty or `null`, `null` is returned.",seeAlso:["second","last","nth","rest","next"],examples:['first(["Albert", "Mojir", 160, [1, 2]])',"first([])","first(null)"]}},last:{evaluate:([e],t)=>{if(null===e)return null;S(e,t);return te(e.at(-1))},arity:G(1),docs:{category:"sequence",returns:{type:"any"},args:{seq:{type:["sequence","null"]}},variants:[{argumentNames:["seq"]}],description:"Returns the last element of $seq. If $seq is empty, `null` is returned.",seeAlso:["first","second","nth","pop"],examples:['last(["Albert", "Mojir", 160, [1, 2]])',"last([1, 2])","last([1])","last([])","last(null)"]}},pop:{evaluate:([e],t)=>(S(e,t),"string"==typeof e?e.substring(0,e.length-1):e.slice(0,e.length-1)),arity:G(1),docs:{category:"sequence",returns:{type:["sequence","null"],rest:!0},args:{seq:{type:"sequence"}},variants:[{argumentNames:["seq"]}],description:"Returns a copy of $seq with last element removed. If $seq is empty `null` is returned.",seeAlso:["push","last"],examples:["pop([1, 2, 3])","pop([])"]}},"index-of":{evaluate:([e,t],n)=>{if(N(t,n),null===e)return null;if(S(e,n),"string"==typeof e){B(t,n);const r=e.indexOf(t);return-1!==r?r:null}{const r=e.findIndex(e=>ee(E(e,n),t),n);return-1!==r?r:null}},arity:G(2),docs:{category:"sequence",returns:{type:["number","null"]},args:{a:{type:"sequence"},b:{type:"any"},seq:{type:["sequence","null"]},x:{type:"any"}},variants:[{argumentNames:["seq","x"]}],description:"Returns the index of $x in $seq. If element is not present in $seq `null` is returned.",seeAlso:["sequence.last-index-of","sequence.position","contains?"],examples:["[[1], [2], [1], [2]] index-of [1]",'index-of(["Albert", "Mojir", 160, [1, 2]], "Mojir")',"index-of([5, 10, 15, 20], 15)","index-of([5, 10, 15, 20], 1)","index-of(null, 1)"]}},push:{evaluate:([e,...t],n)=>(S(e,n),"string"==typeof e?(le(t,n),[e,...t].join("")):[...e,...t]),arity:{min:2},docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"any"},seq:{type:"sequence"},values:{type:"any",rest:!0,description:"At least one."}},variants:[{argumentNames:["seq","values"]}],description:"Returns copy of $seq with $values added to the end of it.",seeAlso:["sequence.unshift","pop","++"],examples:["[1, 2, 3] push 4",'"Albert" push "!"',"push([1, 2, 3], 4)","push([1, 2, 3], 4, 5, 6)","\nlet l = [1, 2, 3];\npush(l, 4);\nl"]}},rest:{evaluate:([e],t)=>(S(e,t),Array.isArray(e)?e.length<=1?[]:e.slice(1):e.substring(1)),arity:G(1),docs:{category:"sequence",returns:{type:["sequence","null"]},args:{seq:{type:"sequence"}},variants:[{argumentNames:["seq"]}],description:"If $seq is an array, returns a new array with all but the first element from $seq.\nIf $seq has less than two elements, an empty array is returned.\nFor string $seq returns all but the first characters in $seq.",seeAlso:["next","first"],examples:['rest(["Albert", "Mojir", 160, [1, 2]])','rest(["Albert"])',"rest([])",'rest("Albert")','rest("A",)','rest("")']}},next:{evaluate:([e],t)=>(S(e,t),Array.isArray(e)?e.length<=1?null:e.slice(1):e.length<=1?null:e.substring(1)),arity:G(1),docs:{category:"sequence",returns:{type:["sequence","null"]},args:{seq:{type:"sequence"}},variants:[{argumentNames:["seq"]}],description:"If $seq is an array, returns a new array with all but the first element from $seq. If $seq has less than two elements, `null` is returned. For string $seq returns all but the first characters in $seq. If length of string $seq is less than two, `null` is returned.",seeAlso:["rest","first"],examples:['next(["Albert", "Mojir", 160, [1, 2]])','next(["Albert"])',"next([])",'next("Albert")','next("A",)','next("")']}},reverse:{evaluate:([e],t)=>null===e?null:(S(e,t),Array.isArray(e)?[...e].reverse():e.split("").reverse().join("")),arity:G(1),docs:{category:"sequence",returns:{type:["sequence","null"]},args:{seq:{type:["sequence","null"]}},variants:[{argumentNames:["seq"]}],description:"If $seq is an array, creates a new array with the elements from $seq in reversed order. If $seq is a string, returns new reversed string.",seeAlso:["sort"],examples:['reverse(["Albert", "Mojir", 160, [1, 2]])',"reverse([])",'reverse("Albert")',"reverse(null)"]}},second:{evaluate:([e],t)=>null===e?null:(S(e,t),te(e[1])),arity:G(1),docs:{category:"sequence",returns:{type:"any"},args:{seq:{type:["sequence","null"]}},variants:[{argumentNames:["seq"]}],description:"Returns the second element of $seq. If $seq has less than two elements or is `null`, `null` is returned.",seeAlso:["first","last","nth"],examples:['second(["Albert", "Mojir", 160, [1, 2]])',"second([1])","second([])","second(null)"]}},slice:{evaluate:(e,t)=>{const[n,r,a]=e;return S(n,t),J(r,t,{integer:!0}),2===e.length?(Array.isArray(n),n.slice(r)):(J(a,t,{integer:!0}),Array.isArray(n),n.slice(r,a))},arity:{min:2,max:3},docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"integer"},seq:{type:"sequence"},start:{type:"integer",description:"Defaults to `0`."},stop:{type:"integer",description:"Defaults to length of sequence + 1."}},variants:[{argumentNames:["seq","start"]},{argumentNames:["seq","start","stop"]}],description:"Returns a copy of a portion of $seq from index $start (inclusive) to $stop (exclusive).",seeAlso:["take","drop","sequence.splice","nth"],examples:["[1, 2, 3, 4, 5] slice 2","slice([1, 2, 3, 4, 5], 2, 4)","slice([1, 2, 3, 4, 5], 2)"]}},some:{evaluate:()=>{throw new Error("some is implemented in Dvala")},arity:G(2),docs:{category:"sequence",returns:{type:"any"},args:{a:{type:"sequence"},b:{type:"function"},seq:{type:["sequence","null"]},fun:{type:"function"}},variants:[{argumentNames:["seq","fun"]}],description:"Returns the first element that passes the test implemented by $fun. I no element was found, `null` is returned.",seeAlso:["sequence.position","collection.any?","find"],examples:['\nsome(\n ["Albert", "Mojir", 160, [1, 2]],\n string?\n)',"\nsome(\n [5, 10, 15, 20],\n -> $ > 10\n)","\nsome(\n [1, 2, 3, 4],\n -> $ > 10\n)","\nsome(\n [],\n -> $ > 10\n)","\nsome(\n null,\n -> $ > 10\n)"]}},sort:{evaluate:()=>{throw new Error("sort is implemented in Dvala")},arity:{min:1,max:2},docs:{category:"sequence",returns:{type:"any",rest:!0},args:{a:{type:"sequence"},b:{type:"function"},seq:{type:"sequence"},fun:{type:"function"}},variants:[{argumentNames:["seq"]},{argumentNames:["seq","fun"]}],description:"Returns a new sequence with the elements from $seq sorted according to $fun. If no $fun is supplied, builtin `compare` will be used.",seeAlso:["sequence.sort-by","compare","reverse","vector.sort-indices"],examples:["[3, 1, 2] sort (a, b) -> b - a","sort([3, 1, 2])","\nsort(\n [3, 1, 2],\n (a, b) -> cond case a < b then -1 case a > b then 1 case true then -1 end\n)","\nsort(\n [3, 1, 2],\n (a, b) -> cond case a > b then -1 case a < b then 1 case true then -1 end\n)"]}},take:{evaluate:([e,t],n)=>{J(t,n),S(e,n);const r=Math.max(Math.ceil(t),0);return e.slice(0,r)},arity:G(2),docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"integer"},n:{type:"integer"},seq:{type:"sequence"}},variants:[{argumentNames:["seq","n"]}],description:"Constructs a new array/string with the $n first elements from $seq.",seeAlso:["take-last","take-while","drop","slice","sequence.split-at"],examples:["take([1, 2, 3, 4, 5], 3)","[1, 2, 3, 4, 5] take 3","take([1, 2, 3, 4, 5], 0)",'take("Albert", 2)','take("Albert", 50)']}},"take-last":{evaluate:([e,t],n)=>{S(e,n),J(t,n);const r=Math.max(Math.ceil(t),0),a=e.length-r;return e.slice(a)},arity:G(2),docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"integer"},n:{type:"integer"},seq:{type:"sequence"}},variants:[{argumentNames:["seq","n"]}],description:"Constructs a new array with the $n last elements from $seq.",seeAlso:["take","drop-last"],examples:["take-last([1, 2, 3, 4, 5], 3)","[1, 2, 3, 4, 5] take-last 3","take-last([1, 2, 3, 4, 5], 0)"]}},drop:{evaluate:([e,t],n)=>{J(t,n);const r=Math.max(Math.ceil(t),0);return S(e,n),e.slice(r)},arity:G(2),docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"integer"},seq:{type:"sequence"},n:{type:"integer"}},variants:[{argumentNames:["seq","n"]}],description:"Constructs a new array/string with the $n first elements dropped from $seq.",seeAlso:["drop-last","drop-while","take","slice","sequence.split-at"],examples:["drop([1, 2, 3, 4, 5], 3)","[1, 2, 3, 4, 5] drop 0",'drop("Albert", 2)','drop("Albert", 50)']}},"drop-last":{evaluate:([e,t],n)=>{S(e,n),J(t,n);const r=Math.max(Math.ceil(t),0),a=e.length-r;return e.slice(0,a)},arity:G(2),docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"integer"},seq:{type:"sequence"},n:{type:"integer"}},variants:[{argumentNames:["seq","n"]}],description:"Constructs a new array with the $n last elements dropped from $seq.",seeAlso:["drop","take-last"],examples:["drop-last([1, 2, 3, 4, 5], 3)","[1, 2, 3, 4, 5] drop-last 3","drop-last([1, 2, 3, 4, 5], 0)"]}},"take-while":{evaluate:()=>{throw new Error("take-while is implemented in Dvala")},arity:G(2),docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"function"},seq:{type:"sequence"},fun:{type:"function"}},variants:[{argumentNames:["seq","fun"]}],description:"Returns the members of $seq in order, stopping before the first one for which `predicate` returns a falsy value.",seeAlso:["take","drop-while","sequence.split-with"],examples:["take-while(\n [1, 2, 3, 2, 1],\n -> $ < 3\n)","take-while(\n [1, 2, 3, 2, 1],\n -> $ > 3\n)"]}},"drop-while":{evaluate:()=>{throw new Error("drop-while is implemented in Dvala")},arity:G(2),docs:{category:"sequence",returns:{type:"sequence"},args:{a:{type:"sequence"},b:{type:"function"},seq:{type:"sequence"},fun:{type:"function"}},variants:[{argumentNames:["seq","fun"]}],description:"Returns the members of $seq in order, skipping the fist elements for witch the `predicate` returns a truethy value.",seeAlso:["drop","take-while","sequence.split-with"],examples:["drop-while(\n [1, 2, 3, 2, 1],\n -> $ < 3\n)","drop-while(\n [1, 2, 3, 2, 1],\n -> $ > 3\n)"]}}},fe=new WeakSet,de=new WeakSet,me=new WeakSet,ye=new WeakSet,ge=new WeakSet,he=new WeakSet,ve=new WeakSet;function be(e){return Array.isArray(e)?(fe.has(e)||(xe(e),Ee(e)||Ae(e)),e):e}function xe(e){return!!Array.isArray(e)&&(!!de.has(e)||!me.has(e)&&(e.every(e=>W(e))?(fe.add(e),de.add(e),!0):(me.add(e),!1)))}function we(e,t){if(!xe(e))throw new n(`Expected a vector, but got ${e}`,t)}function ke(e,t){if(we(e,t),0===e.length)throw new n(`Expected a non empty vector, but got ${e}`,t)}function Ae(e,t){if(!Array.isArray(e))return!1;if(he.has(e))return!0;if(ve.has(e))return!1;if(0===e.length)return ve.add(e),!1;if(!Array.isArray(e[0]))return ve.add(e),!1;const n=e[0].length;if(0===n)return ve.add(e),!1;for(const r of e){if(!Array.isArray(r))return ve.add(e),!1;if(r.length!==n)return ve.add(e),!1;if(t&&r.some(e=>!t(e)))return!1}return fe.add(e),he.add(e),!0}function Ee(e){return Ae(e,W)?(ye.add(e),!0):(Array.isArray(e)&&ge.add(e),!1)}function Ne(e,t){let r=!1,a=!1;for(const s of e)if(xe(s))r=!0;else if(Ee(s))a=!0;else if(!W(s))throw new n("Invalid parameter type: "+typeof s,t);if(a){if(r)throw new n("Cannot mix vector and matrix types",t);let a=null,s=null;for(const r of e)if(Ee(r))if(null===a)a=r.length,s=r[0].length;else if(r.length!==a||r[0].length!==s)throw new n("Matrix dimensions do not match",t);return["matrix",e.map(e=>Ee(e)?e:Array.from({length:a},()=>Array.from({length:s},()=>e)))]}if(r){let r=null;for(const a of e)if(xe(a))if(null===r)r=a.length;else if(a.length!==r)throw new n("Vector lengths do not match",t);return["vector",e.map(e=>xe(e)?e:Array.from({length:r},()=>e))]}return["number",e]}function $e(e){return(t,n)=>{const[r,a]=Ne(t,n);return"number"===r?e(a[0]):"vector"===r?a[0].map(t=>e(t)):a[0].map(t=>t.map(t=>e(t)))}}function Se(e){return(t,n)=>{const[r,a]=Ne(t,n);return"number"===r?e(a[0],a[1]):"vector"===r?a[0].map((t,n)=>e(t,a[1][n])):a[0].map((t,n)=>t.map((t,r)=>e(t,a[1][n][r])))}}function Ie(e,t){return(n,r)=>{if(0===n.length)return e;const[a,s]=Ne(n,r);if("number"===a)return s.reduce((e,n)=>t(e,n),e);if("vector"===a){const[e,...n]=s;return n.reduce((e,n)=>e.map((e,r)=>t(e,n[r])),e)}{const[e,...n]=s;return n.reduce((e,n)=>e.map((e,r)=>e.map((e,a)=>t(e,n[r][a]))),e)}}}const je={inc:{evaluate:$e(e=>e+1),arity:G(1),docs:{category:"math",returns:{type:"number"},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `inc` function increments its argument by 1, working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it increases each element by 1 while preserving the original structure.",seeAlso:["dec","+"],examples:["inc(0)","inc(1)","inc(100.1)","inc([1, 2, 3])","inc([[1, 2], [3, 4]])"]}},dec:{evaluate:$e(e=>e-1),arity:G(1),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `dec` function decrements its argument by 1, working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it decreases each element by 1 while preserving the original structure.",seeAlso:["inc","-"],examples:["dec(0)","dec(1)","dec(100.1)","dec([1, 2, 3])","dec([[1, 2], [3, 4]])"]}},"+":{evaluate:Ie(0,(e,t)=>e+t),arity:{},docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]},xs:{type:["number","vector","matrix"],rest:!0}},variants:[{argumentNames:["xs"]}],description:"The `+` function performs addition of numbers and element-wise addition of `vectors` and `matrices` of compatible dimensions, returning the same type as its inputs. When used with mixed types, it adds the scalar to each element of the collection.",seeAlso:["-","*","/","inc"],examples:["1 + 2","1 + 20 + 30","+(1, 2, 3, 4)","+()","+(1)","[1, 2, 3] + 2","[1, 2, 3] + [4, 5, 6]","[[1, 2, 3], [4, 5, 6]] + [[7, 8, 9], [10, 11, 12]]","[[1, 2, 3], [4, 5, 6]] + 2"]}},"*":{evaluate:Ie(1,(e,t)=>e*t),arity:{},docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]},xs:{type:["number","vector","matrix"],rest:!0}},variants:[{argumentNames:["xs"]}],description:"The `*` function performs multiplication of `numbers` and element-wise multiplication of `vectors` and `matrices` of compatible dimensions, returning the same type as its inputs. When used with mixed types, it multiplies each element of the collection by the scalar.",seeAlso:["/","+","-","^"],examples:["6 * 7","-1 * 4","*(4, 7)","*(1, 2, 3, 4, 5)","*()","*(8)","[1, 2, 3] * 2","[1, 2, 3] * [4, 5, 6]","[[1, 2, 3], [4, 5, 6]] * [[7, 8, 9], [10, 11, 12]]","[[1, 2, 3], [4, 5, 6]] * 2"]}},"/":{evaluate:(e,t)=>{if(0===e.length)return 1;const[n,r]=Ne(e,t);if("number"===n){const[e,...t]=r;return 0===t.length?1/e:t.reduce((e,t)=>e/t,e)}if("vector"===n){const e=r[0];return r.slice(1).reduce((e,t)=>e.map((e,n)=>e/t[n]),e)}{const e=r[0];return r.slice(1).reduce((e,t)=>e.map((e,n)=>e.map((e,r)=>e/t[n][r])),e)}},arity:{},docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]},xs:{type:["number","vector","matrix"],rest:!0}},variants:[{argumentNames:["xs"]}],description:"The `/` function performs division of `numbers` and element-wise division of `vectors` and `matrices` of compatible dimensions, returning the same type as its inputs. When used with mixed types, it divides each element of the collection by the scalar.",seeAlso:["*","+","-","quot","mod","%"],examples:["12 / 100","-1 / 4","/(7, 4)","/(1, 2, 4, 8)","/()","/(8)","[1, 2, 3] / 2","[1, 2, 3] / [4, 5, 6]","[[1, 2, 3], [4, 5, 6]] / [[7, 8, 9], [10, 11, 12]]","[[1, 2, 3], [4, 5, 6]] / 2"]}},"-":{evaluate:(e,t)=>{if(0===e.length)return 0;const[n,r]=Ne(e,t);if("number"===n){const[e,...t]=r;return 0===t.length?-e:t.reduce((e,t)=>e-t,e)}if("vector"===n){const e=r[0];return r.slice(1).reduce((e,t)=>e.map((e,n)=>e-t[n]),e)}{const e=r[0];return r.slice(1).reduce((e,t)=>e.map((e,n)=>e.map((e,r)=>e-t[n][r])),e)}},arity:{},docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]},xs:{type:["number","vector","matrix"],rest:!0}},variants:[{argumentNames:["xs"]}],description:"Computes difference between first value and sum of the rest. When called with only one argument, it does negation.",seeAlso:["+","*","/","dec","abs"],examples:["50 - 8","1 - 1 - 1","-()","-(4, 2)","-(4, 3, 2, 1,)","[1, 2, 3] - 2","[1, 2, 3] - [4, 5, 6]","[[1, 2, 3], [4, 5, 6]] - [[7, 8, 9], [10, 11, 12]]","[[1, 2, 3], [4, 5, 6]] - 2"]}},quot:{evaluate:Se((e,t)=>Math.trunc(e/t)),arity:G(2),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]}},variants:[{argumentNames:["a","b"]}],description:"The `quot` function performs integer division truncated toward zero, working on `numbers` and element-wise on `vectors` and `matrices` of compatible dimensions. When used with mixed types, it applies integer division between each element of the collection and the scalar.",seeAlso:["mod","%","/","trunc"],examples:["quot(5, 3)","quot(5.2, 3.1)","quot(-5, 3)","5 quot -3","-5 quot -3","quot(5, 0)","quot(0, 5)","[1, 2, 3] quot 2","2 quot [1, 2, 3]","quot([1, 2, 3], [4, 5, 6])","[[1, 2, 3], [4, 5, 6]] quot [[7, 8, 9], [10, 11, 12]]","quot([[1, 2, 3], [4, 5, 6]], 2)","[[1, 2, 3], [4, 5, 6]] quot [[7, 8, 9], [10, 11, 12]]"]}},mod:{evaluate:Se((e,t)=>e-t*Math.floor(e/t)),arity:G(2),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]}},variants:[{argumentNames:["a","b"]}],description:"The `mod` function computes the modulo of division with the same sign as the divisor, working on `numbers` and element-wise on `vectors` and `matrices` of compatible dimensions. When used with mixed types, it applies the modulo operation between each element of the collection and the scalar.",seeAlso:["%","quot","/"],examples:["mod(5, 3)","mod(5.2, 3.1)","mod(-5, 3)","5 mod -3","-5 mod -3","[1, 2, 3] mod 2","2 mod [1, 2, 3]","mod([1, 2, 3], [4, 5, 6])","[[1, 2, 3], [4, 5, 6]] mod [[7, 8, 9], [10, 11, 12]]","mod([[1, 2, 3], [4, 5, 6]], 2)"]}},"%":{evaluate:Se((e,t)=>e%t),arity:G(2),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]}},variants:[{argumentNames:["a","b"]}],description:"The `%` function computes the remainder of division with the same sign as the dividend, working on `numbers` and element-wise on `vectors` and `matrices` of compatible dimensions. When used with mixed types, it applies the remainder operation between each element of the collection and the scalar.",seeAlso:["mod","quot","/"],examples:["5 % 3","5.2 % 3.1","-5 % 3","%(5, -3)","%(-5, -3)","[1, 2, 3] % 2","2 % [1, 2, 3]","%([1, 2, 3], [4, 5, 6])","[[1, 2, 3], [4, 5, 6]] % [[7, 8, 9], [10, 11, 12]]","%([[1, 2, 3], [4, 5, 6]], 2)"]}},sqrt:{evaluate:$e(e=>Math.sqrt(e)),arity:G(1),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `sqrt` function calculates the square root of `numbers` and computes element-wise square roots of `vectors` and `matrices`. When applied to collections, it returns the square root of each element while preserving the original structure.",seeAlso:["cbrt","^"],examples:["sqrt(0)","sqrt(9)","sqrt(2)","sqrt(0)","sqrt(9)","sqrt(2)","sqrt([1, 4, 9])","sqrt([[1, 4], [9, 16]])"]}},cbrt:{evaluate:$e(e=>Math.cbrt(e)),arity:G(1),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `cbrt` function calculates the cube root of `numbers` and computes element-wise cube roots of `vectors` and `matrices`. When applied to collections, it returns the cube root of each element while preserving the original structure.",seeAlso:["sqrt","^"],examples:["cbrt(0)","cbrt(27)","cbrt(2)","cbrt(1)","cbrt(0)","cbrt(27)","cbrt(2)","cbrt(1)","cbrt([1, 8, 27])","cbrt([[1, 8], [27, 64]])"]}},"^":{evaluate:Se((e,t)=>e**t),arity:G(2),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:["number","vector","matrix"]}},variants:[{argumentNames:["a","b"]}],description:"The ^ function computes exponentiation, raising the first argument to the power of the second, working on `numbers` and element-wise on `vectors` and `matrices` of compatible dimensions. When used with mixed types, it applies the power operation between each element of the collection and the scalar.",seeAlso:["sqrt","cbrt","*","math.ln"],examples:["2 ^ 3","2 ^ 0","2 ^ -3","^(-2, 3)","^(-2, -3)","[1, 2, 3] ^ 2","2 ^ [1, 2, 3]","^([1, 2, 3], [4, 5, 6])","[[1, 2, 3], [4, 5, 6]] ^ [[7, 8, 9], [10, 11, 12]]","^([[1, 2, 3], [4, 5, 6]], 2)"]}},round:{evaluate:([e,t],n)=>{const[r,a]=Ne([e],n);if("number"===r){if(void 0===t||0===t)return Math.round(a[0]);{J(t,n,{integer:!0,positive:!0});const e=10**t;return Math.round(a[0]*e)/e}}if("vector"===r){const e=a[0];if(void 0===t||0===t)return e.map(e=>Math.round(e));{J(t,n,{integer:!0,positive:!0});const r=10**t;return e.map(e=>Math.round(e*r)/r)}}{const e=a[0];if(void 0===t||0===t)return e.map(e=>e.map(e=>Math.round(e)));{J(t,n,{integer:!0,positive:!0});const r=10**t;return e.map(e=>e.map(e=>Math.round(e*r)/r))}}},arity:{min:1,max:2},docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{a:{type:["number","vector","matrix"]},b:{type:"integer"}},variants:[{argumentNames:["a"]},{argumentNames:["a","b"]}],description:"The `round` function rounds a `number` to the nearest `integer` or to a specified number of `decimal` places, working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it rounds each element while preserving the original structure.",seeAlso:["floor","ceil","trunc"],examples:["round(2)","round(2.49)","round(2.5)","round(-2.49)","round(-2.5)","round(-2.501)","round(1.23456789, 4)","1.123456789 round 2","round([1.23456789, 2.3456789], 1)","[1.23456789, 2.3456789] round 4","[[1.23456789, 2.3456789], [3.456789, 4.56789]] round 4","round([[1.23456789, 2.3456789], [3.456789, 4.56789]], 2)"]}},trunc:{evaluate:$e(e=>Math.trunc(e)),arity:G(1),docs:{category:"math",returns:{type:["integer","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `trunc` function truncates `numbers` toward zero (removing decimal portions without rounding), working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it truncates each element while preserving the original structure.",seeAlso:["round","floor","ceil","quot"],examples:["trunc(2)","trunc(2.49)","trunc(2.5)","trunc(-2.49)","trunc(-2.5)","trunc(-2.501)","trunc([1.23456789, 2.3456789])","trunc([[1.23456789, 2.3456789], [3.456789, 4.56789]])"]}},floor:{evaluate:$e(e=>Math.floor(e)),arity:G(1),docs:{category:"math",returns:{type:["integer","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `floor` function returns the largest `integer` less than or equal to a `number`, working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it returns the floor of each element while preserving the original structure.",seeAlso:["ceil","round","trunc"],examples:["floor(2)","floor(2.49)","floor(2.5)","floor(-2.49)","floor(-2.5)","floor(-2.501)","floor([1.23456789, 2.3456789])","floor([[1.23456789, 2.3456789], [3.456789, 4.56789]])"]}},ceil:{evaluate:$e(e=>Math.ceil(e)),arity:G(1),docs:{category:"math",returns:{type:["integer","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `ceil` function returns the smallest `integer` greater than or equal to a `number`, working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it returns the ceiling of each element while preserving the original structure.",seeAlso:["floor","round","trunc"],examples:["ceil(2)","ceil(2.49)","ceil(2.5)","ceil(-2.49)","ceil(-2.5)","ceil(-2.501)","ceil([1.23456789, 2.3456789])","ceil([[1.23456789, 2.3456789], [3.456789, 4.56789]])"]}},min:{evaluate:(e,t)=>{if(1===e.length&&xe(e[0])){const n=e[0];return ke(n,t),n.reduce((e,t)=>Math.min(e,t),1/0)}const[n,...r]=e;return J(n,t),r.reduce((e,n)=>(J(n,t),Math.min(e,n)),n)},arity:{min:1},docs:{category:"math",returns:{type:"number"},args:{a:{type:"number"},b:{type:"number"},xs:{type:"number",rest:!0},vector:{type:"vector"}},variants:[{argumentNames:["xs"]},{argumentNames:["vector"]}],description:"Returns the smallest value. Accepts either multiple numbers or a single vector of numbers.",seeAlso:["max","vector.span","vector.min-index"],examples:["2 min 3","min(2, 0, 1)","min(2, -1, 1)","min([2, 0, -1])","12 min 14"]}},max:{evaluate:(e,t)=>{if(1===e.length&&xe(e[0])){const n=e[0];return ke(n,t),n.reduce((e,t)=>Math.max(e,t),-1/0)}const[n,...r]=e;return J(n,t),r.reduce((e,n)=>(J(n,t),Math.max(e,n)),n)},arity:{min:1},docs:{category:"math",returns:{type:"number"},args:{a:{type:"number"},b:{type:"number"},xs:{type:"number",rest:!0},vector:{type:"vector"}},variants:[{argumentNames:["xs"]},{argumentNames:["vector"]}],description:"Returns the largest value. Accepts either multiple numbers or a single vector of numbers.",seeAlso:["min","vector.span","vector.max-index"],examples:["2 max 3","max(2, 0, 1)","max(2, -1, 1)","max([2, 0, -1])","4 max 2"]}},abs:{evaluate:$e(e=>Math.abs(e)),arity:G(1),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The abs function returns the absolute value (magnitude) of a `number`, working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it returns the absolute value of each element while preserving the original structure.",seeAlso:["sign","-"],examples:["abs(-2.3)","abs(0)","abs(2.5)","abs([1, -2, 3])","abs([[1, -2], [3, -4]])"]}},sign:{evaluate:$e(e=>Math.sign(e)),arity:G(1),docs:{category:"math",returns:{type:["number","vector","matrix"]},args:{x:{type:["number","vector","matrix"]}},variants:[{argumentNames:["x"]}],description:"The `sign` function returns the `sign` of a `number` (-1 for negative, 0 for zero, 1 for positive), working on `numbers` and element-wise on `vectors` and `matrices`. When applied to collections, it returns the sign of each element while preserving the original structure.",seeAlso:["abs"],examples:["sign(-2.3)","sign(-0)","sign(0)","sign(12312)","sign([1, -2, 3])","sign([[1, -2], [3, -4]])"]}}};function qe([e,...t],n){const r=E(e,n);for(const e of t)if(!ee(r,E(e,n),n))return!1;return!0}const Ce={"==":{evaluate:(e,t)=>qe(e,t),arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:"any"},b:{type:"any"},x:{type:"any"},ys:{type:"any",rest:!0}},variants:[{argumentNames:["x"]},{argumentNames:["x","ys"]}],description:"Returns `true` if all `values` are structaul equal to each other, otherwise result is `false`.",seeAlso:["!=","identical?"],examples:["1 == 1","[1, 2] == [1, 2]","\n{\n a: 1,\n b: 2,\n} == {\n b: 2,\n a: 1,\n}","==(1, 1)","==(1.01, 1)",'==("1", 1)','==("2", "2", "2", "2")',"==(2, 2, 1, 2)","==([1, 2], [1, 2])","==({ a: 1, b: 2 }, { b: 2, a: 1 })"]}},"!=":{evaluate:(e,t)=>!qe(e,t),arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:"any"},b:{type:"any"},x:{type:"any"},ys:{type:"any",rest:!0}},variants:[{argumentNames:["x"]},{argumentNames:["x","ys"]}],description:"Returns `true` if all `values` are not equal to each other, otherwise result is `false`. `(!= a b c)` is same as `(not (== a b c))`.",seeAlso:["==","identical?"],examples:["1 != 2","3 != 3","!=(3)","!=(3, 3, 2)",'!=("3", "2", "1", "0",)',"!=(0, -0)"]}},"identical?":{evaluate:e=>function([e,...t]){for(const n of t)if(n!==e)return!1;return!0}(e),arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:"any"},b:{type:"any"}},variants:[{argumentNames:["a","b"]}],description:"Returns true if $a and $b are referential equal.",seeAlso:["==","!="],examples:["identical?({ a: 10, b: 20 }, { b: 20, a: 10 })","identical?([1, true, null], [1, true, null])","identical?(0.3, 0.1 + 0.2)"]}},">":{evaluate:([e,...t],n)=>{let r=F(e);for(const e of t){if(Q(r,F(e),n)<=0)return!1;r=F(e)}return!0},arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:["number","string"]},b:{type:["number","string"]},x:{type:["number","string"]},ys:{type:["number","string"],rest:!0}},variants:[{argumentNames:["x"]},{argumentNames:["x","ys"]}],description:"Returns `true` if $x and $ys are in decreasing order, `false` otherwise.",seeAlso:["<",">=","<=","compare"],examples:[">(1, 0)",">(1.01, 1)",">(1, 1)",">(4, 3, 2, 1)",">(3, 2, 2, 1)"]}},"<":{evaluate:([e,...t],n)=>{let r=F(e);for(const e of t){if(Q(r,F(e),n)>=0)return!1;r=F(e)}return!0},arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:["number","string"]},b:{type:["number","string"]},x:{type:["number","string"]},ys:{type:["number","string"],rest:!0}},variants:[{argumentNames:["x"]},{argumentNames:["x","ys"]}],description:"Returns `true` if $x and $ys are in increasing order, `false` otherwise.",seeAlso:[">",">=","<=","compare"],examples:["<(0, 1)","<(1, 1.01)","<(1, 1)","<(1, 2, 2, 3)",'<("a", "b")']}},">=":{evaluate:([e,...t],n)=>{let r=F(e);for(const e of t){if(Q(r,F(e),n)<0)return!1;r=F(e)}return!0},arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:["number","string"]},b:{type:["number","string"]},x:{type:["number","string"]},ys:{type:["number","string"],rest:!0}},variants:[{argumentNames:["x"]},{argumentNames:["x","ys"]}],description:"Returns `true` if $x and $ys are in non increasing order, `false` otherwise.",seeAlso:[">","<","<=","compare"],examples:["1 >= 1","0 >= 1",">=(1, 0)",">=(1.01, 1)",">=(1, 1)",">=(4, 3, 2, 1)",">=(3, 2, 2, 1)"]}},"<=":{evaluate:([e,...t],n)=>{let r=F(e);for(const e of t){if(Q(r,F(e),n)>0)return!1;r=F(e)}return!0},arity:{min:1},docs:{category:"misc",returns:{type:"boolean"},args:{a:{type:["number","string"]},b:{type:["number","string"]},x:{type:["number","string"]},ys:{type:["number","string"],rest:!0}},variants:[{argumentNames:["x"]},{argumentNames:["x","ys"]}],description:"Returns `true` if $x and $ys are in non decreasing order, `false` otherwise.",seeAlso:[">","<",">=","compare"],examples:["1 <= 1","<=(0, 1)","<=(1, 1.01)","<=(1, 1)","<=(1, 2, 3, 4)","<=(1, 2, 2, 3)"]}},not:{evaluate:([e])=>!e,arity:G(1),docs:{category:"misc",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Computes logical negation. Note that any other $x than `false`, `0`, `null` and `''` is truthy.",seeAlso:["boolean"],examples:["not(3)","not(true)",'not("A string")',"not(0)","not(false)","not(null)",'not("")']}},"epoch->iso-date":{evaluate:([e],t)=>(J(e,t),new Date(e).toISOString()),arity:G(1),docs:{category:"misc",returns:{type:"string"},args:{ms:{type:"number"}},variants:[{argumentNames:["ms"]}],description:"Returns IOS date time string from `ms` (milliseconds elapsed since the UNIX epoch).",seeAlso:["iso-date->epoch"],examples:["epoch->iso-date(1649756230899)","epoch->iso-date(0)"]}},"iso-date->epoch":{evaluate:([e],t)=>{B(e,t);const n=new Date(e).valueOf();return J(n,t,{finite:!0}),n},arity:G(1),docs:{category:"misc",returns:{type:"number"},args:{iso:{type:"string"}},variants:[{argumentNames:["iso"]}],description:"Returns milliseconds elapsed since the UNIX epoch to `iso`.",seeAlso:["epoch->iso-date"],examples:['iso-date->epoch("2022-04-12T09:37:10.899Z")','iso-date->epoch("1980-01-01")']}},boolean:{evaluate:([e])=>!!e,arity:G(1),docs:{category:"misc",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Coerces $x to boolean.",seeAlso:["not","boolean?","true?","false?"],examples:["boolean(0)","boolean(1)","boolean(null)",'boolean("Albert")']}},compare:{evaluate:([e,t],n)=>(L(e,n),L(t,n),Q(e,t,n)),arity:G(2),docs:{category:"misc",returns:{type:"number"},args:{a:{type:["number","string"]},b:{type:["number","string"]}},variants:[{argumentNames:["a","b"]}],description:"Compares two values. Returns `-1` if $a < $b, `1` if $a > $b and `0` if $a and $b have the same sort order.",seeAlso:["<",">","<=",">=","sort","sequence.sort-by"],examples:["compare(0, 1)","compare(0, 0)","compare(1, 0)",'compare("Albert", "Mojir")']}},"json-parse":{evaluate:([e],t)=>(B(e,t),JSON.parse(e)),arity:G(1),docs:{category:"misc",returns:{type:"any"},args:{x:{type:"string"}},variants:[{argumentNames:["x"]}],description:"Returns `JSON.parse(`$x`)`.",seeAlso:["json-stringify"],examples:['json-parse("[1, 2, 3]")']}},"json-stringify":{evaluate:([e,t],n)=>(N(e,n),void 0===t?JSON.stringify(e):(J(t,n),JSON.stringify(e,null,t))),arity:{min:1,max:2},docs:{category:"misc",returns:{type:"string"},args:{x:{type:"any"},indent:{type:"integer",description:"Number of spaces to use for indentation."}},variants:[{argumentNames:["x"]},{argumentNames:["x","indent"]}],description:"Returns `JSON.stringify(`$x`)`. If second argument is provided, returns `JSON.stringify(`$x`, null, `$indent`)`.",seeAlso:["json-parse"],examples:["json-stringify([1, 2, 3])","json-stringify({ a: { b: 10 }}, 2)"],hideOperatorForm:!0}},"effect-name":{evaluate:([e],t)=>function(e,t){return O(e,t),e}(e,t).name,arity:G(1),docs:{category:"meta",returns:{type:"string"},args:{e:{type:"any",description:"An effect reference."}},variants:[{argumentNames:["e"]}],description:"Returns the name of an effect reference as a string.",seeAlso:["effect-matcher","effect?"],examples:["effect-name(effect(dvala.error))","effect-name(effect(llm.complete))"]}},"effect-matcher":{evaluate:([e],t)=>{if("string"==typeof e)return{[u]:!0,sourceCodeInfo:t,functionType:"EffectMatcher",matchType:"string",pattern:e,flags:"",arity:G(1)};if(R(e))return{[u]:!0,sourceCodeInfo:t,functionType:"EffectMatcher",matchType:"regexp",pattern:e.s,flags:e.f,arity:G(1)};throw new n("effect-matcher expects a string or regexp pattern",t)},arity:G(1),docs:{category:"meta",returns:{type:"function"},args:{pattern:{type:["string","regexp"],description:"A wildcard pattern or regexp to match against effect names."}},variants:[{argumentNames:["pattern"]}],description:"Returns a predicate function that matches effects by name. If $pattern is a string, uses wildcard matching: no wildcard means exact match, `.*` suffix matches the prefix and all descendants (dot boundary enforced), and `*` alone matches everything. If $pattern is a regexp, tests the effect name against the regexp.",seeAlso:["effect-name","effect?"],examples:['let pred = effect-matcher("dvala.*"); pred(effect(dvala.error))','let pred = effect-matcher("dvala.*"); pred(effect(custom.foo))','let pred = effect-matcher("*"); pred(effect(anything))']}},"type-of":{evaluate:([e])=>null==e?"null":"boolean"==typeof e?"boolean":"number"==typeof e?"number":"string"==typeof e?"string":T(e)?"effect":R(e)?"regexp":w(e)?"function":Array.isArray(e)?"array":"object",arity:G(1),docs:{category:"misc",returns:{type:"string"},args:{x:{type:"any",description:"The value to inspect."}},variants:[{argumentNames:["x"]}],description:'Returns a string representing the type of $x. Possible return values are `"number"`, `"string"`, `"boolean"`, `"null"`, `"array"`, `"object"`, `"function"`, `"regexp"`, and `"effect"`.',seeAlso:["number?","string?","boolean?","null?","array?","object?","function?","regexp?","effect?"],examples:["type-of(42)",'type-of("hello")',"type-of(true)","type-of(null)","type-of([1, 2, 3])","type-of({ a: 1 })","type-of((x) -> x + 1)",'type-of(regexp("^start"))',"type-of(effect(dvala.io.println))"]}}},Re={keys:{evaluate:([e],t)=>(j(e,t),Object.keys(e)),arity:G(1),docs:{category:"object",returns:{type:"any",array:!0},args:{obj:{type:"object"}},variants:[{argumentNames:["obj"]}],description:"Returns array of all keys in $obj.",seeAlso:["vals","entries","zipmap","select-keys"],examples:["keys({})",'keys({ x: 10, y: true, z: "A string" })','keys(object("x", 10, "y", true, "z", "A string"))']}},vals:{evaluate:([e],t)=>(j(e,t),Object.values(e)),arity:G(1),docs:{category:"object",returns:{type:"any",array:!0},args:{obj:{type:"object"}},variants:[{argumentNames:["obj"]}],description:"Returns array of all values in $obj.",seeAlso:["keys","entries","zipmap"],examples:["vals({})",'vals({ x: 10, y: true, z: "A string" })','vals(object("x", 10, "y", true, "z", "A string"))']}},entries:{evaluate:([e],t)=>(j(e,t),Object.entries(e)),arity:G(1),docs:{category:"object",returns:{type:"array"},args:{obj:{type:"object"}},variants:[{argumentNames:["obj"]}],description:"Returns nested array of all key - value pairs in $obj.",seeAlso:["keys","vals","zipmap","find"],examples:["entries({})",'entries({ x: 10, y: true, z: "A string" })','entries(object("x", 10, "y", true, "z", "A string"))']}},find:{evaluate:([e,t],n)=>(j(e,n),B(t,n),Z(e,t)?[t,e[t]]:null),arity:G(2),docs:{category:"object",returns:{type:["array","null"]},args:{a:{type:"object"},b:{type:"string"},obj:{type:"object"},key:{type:"string"}},variants:[{argumentNames:["obj","key"]}],description:"Returns entry (key-value pair) for $key, or `null` if $key not present in $obj.",seeAlso:["get","contains?","entries","sequence.position","some"],examples:['{ a: 1, "b": 2 } find "a"','find(object("a", 1, "b", 2), "b")','find(object("a", 1, "b", 2), "c")']}},dissoc:{evaluate:([e,t],n)=>{j(e,n),B(t,n);const r={...e};return delete r[t],r},arity:G(2),docs:{category:"object",returns:{type:"object"},args:{a:{type:"object"},b:{type:"string"},obj:{type:"object"},key:{type:"string"}},variants:[{argumentNames:["obj","key"]}],description:"Return shallow copy of $obj with $key deleted.",seeAlso:["assoc","select-keys"],examples:['{ x: 10, y: 20 } dissoc "y"','dissoc({ x: 10, y: 20 }, "x")','dissoc({ x: 10 }, "y")','\nlet o = { a: 5 };\ndissoc(o, "a");\no']}},merge:{evaluate:(e,t)=>{if(0===e.length)return null;const[n,...r]=e;return j(n,t),r.reduce((e,n)=>(j(n,t),{...e,...n}),{...n})},arity:{min:0},docs:{category:"object",returns:{type:"object"},args:{a:{type:"object"},b:{type:"object"},objs:{type:"object",rest:!0}},variants:[{argumentNames:["objs"]}],description:"Returns a new object created by merging together all arguments.\n\nIf two keys appears in more than one object the value from the last object is used.\nIf no arguments are provided `null` is returned.",seeAlso:["merge-with","assoc"],examples:["{ x: 10 } merge { y: 20 }",'merge(object("x", 10), object("y", 20))','merge(object("x", 10), object("x", 15, "y", 20))']}},"merge-with":{evaluate:()=>{throw new Error("merge-with is implemented in Dvala")},arity:{min:2},docs:{category:"object",returns:{type:"object"},args:{objs:{type:"object",rest:!0},fun:{type:"function"}},variants:[{argumentNames:["objs","fun"]}],description:"\nReturns a new object created by merging together all arguments.\nIf two keys appears in more than one object $fun is used to calculate the new value.\n\nIf no arguments are provided `null` is returned.",seeAlso:["merge"],examples:['merge-with(object("x", 10), object("y", 20), +)','merge-with(object("x", 10), object("x", 15, "y", 20), +)',"merge-with({ x: 10 }, { x: 20 }, { x: 30 }, { x: 40 }, -)"],hideOperatorForm:!0}},zipmap:{evaluate:([e,t],n)=>{ie(e,n),oe(t,n);const r=Math.min(e.length,t.length),a={};for(let s=0;s<r;s+=1){a[D(e[s],n)]=te(t[s])}return a},arity:G(2),docs:{category:"object",returns:{type:"object"},args:{a:{type:"array"},b:{type:"array"}},variants:[{argumentNames:["a","b"]}],description:"Returns a new object created by mapping $a to $b.",seeAlso:["entries","keys","vals","sequence.interleave"],examples:['["a", "b", "c"] zipmap [1, 2, 3]','zipmap(["a", "b", "c"], [10, null, [1, 2, 3]])','zipmap(["a", "b", "c"], [1])',"zipmap([], [10, null, [1, 2, 3]])"]}},"select-keys":{evaluate:([e,t],n)=>(ie(t,n),j(e,n),t.reduce((t,n)=>(Z(e,n)&&(t[n]=te(e[n])),t),{})),arity:G(2),docs:{category:"object",returns:{type:"object"},args:{a:{type:"object"},b:{type:"array"}},variants:[{argumentNames:["a","b"]}],description:"Returns an object containing only those entries in $a whose key is in $b.",seeAlso:["dissoc","keys"],examples:['{ a: 1, b: 2, c: 3 } select-keys ["a", "b"]','select-keys({ a: 1, b: 2, c: 3 }, ["a", "b"])','select-keys({ a: 1 }, ["a", "b"])']}}},Pe={"function?":{evaluate:([e])=>w(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a function, otherwise `false`.",seeAlso:["string?","number?","boolean?","null?","array?","object?","regexp?","type-of"],examples:["function?(+)","function?(/)","function?((x, y) -> x + y)","function?(false)",'function?("false")',"function?([1, 2, 3])"]}},"string?":{evaluate:([e])=>"string"==typeof e,arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a string, otherwise `false`.",seeAlso:["blank?","number?","boolean?","null?","array?","object?","regexp?","function?","collection?","sequence?","type-of"],examples:['string?("")','string?("A string")','string?(true ? "A string" : false)',"string?(false)","string?([1, 2, 3])","string?(100)"]}},"number?":{evaluate:([e])=>"number"==typeof e,arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a number, otherwise `false`.",seeAlso:["integer?","zero?","pos?","neg?","finite?","number","string?","boolean?","null?","function?","type-of"],examples:["number?(0)","number?(2)","number?(-0.12)","number?(false)","number?([1, 2, 3])",'number?("A string")']}},"integer?":{evaluate:([e])=>"number"==typeof e&&W(e,{integer:!0}),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is an integer, otherwise `false`.",seeAlso:["number?","number","even?","odd?"],examples:["integer?(0)","integer?(-12)","integer?(42)","integer?(10.1)","integer?((x, y) -> x + y)","integer?(false)",'integer?("false")',"integer?([1, 2, 3])"]}},"boolean?":{evaluate:([e])=>"boolean"==typeof e,arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a `boolean`, otherwise `false`.",seeAlso:["true?","false?","boolean","string?","number?","null?","function?","type-of"],examples:["boolean?(true)","boolean?(false)","boolean?([1, 2, 3])","boolean?(0)",'boolean?("A string")']}},"null?":{evaluate:([e])=>null==e,arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is `null`, otherwise `false`.",seeAlso:["empty?","not-empty?","string?","number?","boolean?","function?","type-of"],examples:["null?(null)","null?(false)","null?([1, 2, 3])","null?(0)",'null?("A string")']}},"zero?":{evaluate:([e],t)=>(J(e,t,{finite:!0}),Math.abs(e)<ae),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is `0`, otherwise `false`.",seeAlso:["pos?","neg?","even?","number?"],examples:["zero?(0)","zero?(-0.0)","zero?(1)","zero?(0.1)"]}},"pos?":{evaluate:([e],t)=>(J(e,t,{finite:!0}),e>0),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is greater than `0`, otherwise `false`.",seeAlso:["neg?","zero?","number?"],examples:["pos?(0)","pos?(-0.0)","pos?(1)","pos?(-0.1)"]}},"neg?":{evaluate:([e],t)=>(J(e,t,{finite:!0}),e<0),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is less than `0`, otherwise `false`.",seeAlso:["pos?","zero?","number?"],examples:["neg?(0)","neg?(-0.0)","neg?(1)","neg?(-0.1)"]}},"even?":{evaluate:([e],t)=>(J(e,t,{finite:!0}),e%2==0),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is even, otherwise `false`.",seeAlso:["odd?","integer?","zero?"],examples:["even?(0)","even?(-0.0)","even?(-1)","even?(2.1)"]}},"odd?":{evaluate:([e],t)=>(J(e,t,{finite:!0}),W(e,{integer:!0})&&e%2!=0),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is odd, otherwise `false`.",seeAlso:["even?","integer?"],examples:["odd?(1.0)","odd?(1.001)","odd?(-1)","odd?(2.1)"]}},"array?":{evaluate:([e])=>Array.isArray(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is an array, otherwise `false`.",seeAlso:["sequence?","collection?","object?","string?","vector?","matrix?","grid?","function?","type-of"],examples:["array?([])","array?([1, 2, 3])",'array?(object("a", 10))',"array?(42)","array?(10.1)","array?((x, y) -> x + y)"]}},"collection?":{evaluate:([e])=>q(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a collection i.e. an array, an object or a string, otherwise `false`.",seeAlso:["sequence?","array?","object?","string?"],examples:["collection?([])","collection?([1, 2, 3])",'collection?(object("a", 10))','collection?("Albert")',"collection?(42)","collection?(10.1)","collection?((x, y) -> x + y)"]}},"sequence?":{evaluate:([e])=>$(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a sequence i.e. an array or a string, otherwise `false`.",seeAlso:["collection?","array?","string?"],examples:["sequence?([])","sequence?([1, 2, 3])",'sequence?(object("a", 10))','sequence?("Albert")',"sequence?(42)","sequence?(10.1)","sequence?((x, y) -> x + y)"]}},"object?":{evaluate:([e])=>I(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is an object, otherwise `false`.",seeAlso:["collection?","array?","string?","function?","type-of"],examples:['object?(object("a", 10))',"object?(42)","object?(10.1)","object?((x, y) -> x + y)",'object?(#"^start")','object?("false")',"object?([1, 2, 3])"]}},"regexp?":{evaluate:([e])=>R(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is a regexp, otherwise `false`.",seeAlso:["regexp","re-match","string?","function?","type-of"],examples:['regexp?(regexp("^start"))','regexp?(#"^start")',"regexp?(-12)","regexp?({})","regexp?(10.1)","regexp?((x, y) -> x + y)","regexp?(false)",'regexp?("false")',"regexp?([1, 2, 3])"]}},"effect?":{evaluate:([e])=>T(e),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is an effect, otherwise `false`.",seeAlso:["effect","effect-name","effect-matcher","perform","type-of"],examples:["effect?(effect(dvala.io.println))","effect?(42)",'effect?("hello")',"effect?(null)","effect?({})","effect?([1, 2, 3])"]}},"finite?":{evaluate:([e],t)=>(J(e,t),Number.isFinite(e)),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is finite, otherwise `false`.",seeAlso:["positive-infinity?","negative-infinity?","number?"],examples:["finite?(1.0)","finite?(1 / 0)","finite?(-1 / 0)"]}},"positive-infinity?":{evaluate:([e],t)=>(J(e,t),e===Number.POSITIVE_INFINITY),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x equals positive infinity, otherwise `false`.",seeAlso:["negative-infinity?","finite?"],examples:["positive-infinity?(1.0)","positive-infinity?(1 / 0)","positive-infinity?(-1 / 0)"]}},"negative-infinity?":{evaluate:([e],t)=>(J(e,t),e===Number.NEGATIVE_INFINITY),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"number"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x equals negative infinity, otherwise `false`.",seeAlso:["positive-infinity?","finite?"],examples:["negative-infinity?(1.0)","negative-infinity?(1 / 0)","negative-infinity?(-1 / 0)"]}},"true?":{evaluate:([e])=>!0===e,arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is `true`, otherwise `false`.",seeAlso:["false?","boolean?","boolean"],examples:["true?(false)","true?(true)","true?(1)","true?(0)"]}},"false?":{evaluate:([e])=>!1===e,arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is `true`, otherwise `false`.",seeAlso:["true?","boolean?","boolean"],examples:["false?(false)","false?(true)","false?(1)","false?(0)"]}},"empty?":{evaluate:([e],t)=>null===e||(C(e,t),"string"==typeof e||Array.isArray(e)?0===e.length:0===Object.keys(e).length),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:["collection","string","null"]}},variants:[{argumentNames:["x"]}],description:"Returns `true` if $x is empty or `null`, otherwise `false`.",seeAlso:["not-empty?","collection.not-empty","null?","blank?","count"],examples:["empty?([])","empty?([1, 2, 3])","empty?({})","empty?({ a: 2 })",'empty?("")','empty?("Albert")',"empty?(null)"]}},"not-empty?":{evaluate:([e],t)=>null!==e&&(C(e,t),"string"==typeof e||Array.isArray(e)?e.length>0:Object.keys(e).length>0),arity:G(1),docs:{category:"predicate",returns:{type:"boolean"},args:{x:{type:["collection","string","null"]}},variants:[{argumentNames:["x"]}],description:"Returns `false` if $x is empty or `null`, otherwise `true`.",seeAlso:["empty?","collection.not-empty","null?"],examples:["not-empty?([])","not-empty?([1, 2, 3])","not-empty?({})","not-empty?({ a: 2 })",'not-empty?("")','not-empty?("Albert")',"not-empty?(null)"]}},"vector?":{evaluate:([e])=>xe(e),arity:G(1),docs:{category:"predicate",description:"Checks if a value is a `vector`. A `vector` is an array of `numbers`.",seeAlso:["matrix?","grid?","array?"],returns:{type:"boolean"},args:{value:{type:"any",description:"The value to check."}},variants:[{argumentNames:["value"]}],examples:["vector?(1)","vector?([1, 2, 3])",'vector?([1, 2, "3"])']}},"matrix?":{evaluate:([e])=>Ee(e),arity:G(1),docs:{category:"predicate",description:"Checks if a value is a `matrix`. A `matrix` is an array of arrays of `numbers`.",seeAlso:["vector?","grid?","array?"],returns:{type:"boolean"},args:{value:{type:"any",description:"The value to check."}},variants:[{argumentNames:["value"]}],examples:["matrix?(1)","matrix?([1, 2, 3])","matrix?([[1, 2], [3, 4]])",'matrix?([[1, 2], [3, "4"]])',"matrix?([[1, 2], [3]])"]}},"grid?":{evaluate:([e])=>Ae(e),arity:G(1),docs:{category:"predicate",description:"Checks if a `value` is a `grid`. A `grid` is an `array` of `arrays` where all inner `arrays` have the same length.",seeAlso:["vector?","matrix?","array?"],returns:{type:"boolean"},args:{value:{type:"any",description:"The value to check."}},variants:[{argumentNames:["value"]}],examples:['grid?("1")','grid?(["1", 2, 3])','grid?([["1", 2], [3, 4]])','grid?([["1", 2], [3, "4"]])','grid?([["1", 2], [3]])']}}},Te={regexp:{evaluate:([e,t],r)=>{B(e,r);const a=e||"(?:)",s="string"==typeof t?t:"";try{new RegExp(a,s)}catch(e){throw new n(`Invalid regular expression: ${a} ${s}`,r)}return{[p]:!0,sourceCodeInfo:r,s:a,f:s}},arity:{min:1,max:2},docs:{category:"regular-expression",returns:{type:"regexp"},args:{pattern:{type:"string"},flags:{type:"string",description:"Optional flags for the regular expression. Possible values are the same as Javascript RegExp takes."}},variants:[{argumentNames:["pattern"]},{argumentNames:["pattern","flags"]}],description:"Creates a RegExp from $pattern and $flags.",examples:['regexp("^\\s*(.*)$")','#"^\\s*(.*)$"','regexp("albert", "ig")','#"albert"ig'],seeAlso:["-short-regexp","re-match","replace","replace-all","regexp?"],hideOperatorForm:!0}},"re-match":{evaluate:([e,t],n)=>{if(function(e,t){if(!R(e))throw h("RegularExpression",e,t)}(t,n),!U(e))return null;const r=new RegExp(t.s,t.f).exec(e);return r?[...r]:null},arity:G(2),docs:{category:"regular-expression",returns:{type:"any"},args:{a:{type:"regexp"},b:{type:"string"}},variants:[{argumentNames:["a","b"]}],description:"Matches $b against regular expression $a.\nIf $b is a string and matches the regular expression, a `re-match`-array is returned, otherwise `null` is returned.",seeAlso:["regexp","replace","replace-all","-short-regexp","regexp?"],examples:['re-match(" A string", regexp("^\\\\s*(.*)$"))','re-match(" A string", #"^\\s*(.*)$")','re-match("My name is Albert", #"albert"i)','re-match("My name is Ben", #"albert"i)','re-match(null, #"albert"i)','re-match(1, #"albert"i)','re-match({}, #"albert"i)']}},replace:{evaluate:([e,t,n],r)=>{B(e,r),P(t,r),B(n,r);const a=R(t)?new RegExp(t.s,`${t.f}`):t;return e.replace(a,n)},arity:G(3),docs:{category:"regular-expression",returns:{type:"string"},args:{a:{type:"string"},b:{type:["regexp","string"]},x:{type:"string"}},variants:[{argumentNames:["a","b","x"]}],description:"Returns a new string with first match of regular expression $b replaced by $x.",seeAlso:["replace-all","regexp","re-match","-short-regexp"],examples:['replace("Duck duck", "u", "i")','replace("Duck duck", #"u", "i")','replace("abcABC", regexp("a", "i"), "-")','replace("abcABC", regexp("a", "gi"), "-")','replace("abcABC", #"a"i, "-")','replace("abcABC", #"a"gi, "-")']}},"replace-all":{evaluate:([e,t,n],r)=>{B(e,r),P(t,r),B(n,r);const a=R(t)?new RegExp(t.s,`${t.f.includes("g")?t.f:`${t.f}g`}`):t;return e.replaceAll(a,n)},arity:G(3),docs:{category:"regular-expression",returns:{type:"string"},args:{a:{type:"string"},b:{type:["regexp","string"]},x:{type:"string"}},variants:[{argumentNames:["a","b","x"]}],description:"Returns a new string with all matches of regular expression $b replaced by $x.",seeAlso:["replace","regexp","re-match","-short-regexp"],examples:['replace-all("Duck duck", "u", "i")','replace-all("Duck duck", regexp("u"), "i")','replace-all("abcABC", regexp("a", "i"), "-")','replace-all("abcABC", regexp("a", "gi"), "-")','replace-all("abcABC", #"a"i, "-")','replace-all("abcABC", #"a"gi, "-")']}}},Oe=/^\s*$/,Me={str:{evaluate:e=>e.reduce((e,t)=>e+(null==t?"":I(t)||Array.isArray(t)?JSON.stringify(t):`${t}`),""),arity:{},docs:{category:"string",returns:{type:"string"},args:{values:{type:"any",rest:!0}},variants:[{argumentNames:["values"]}],description:"Concatenats $values into one string. If `value` equals `null` empty string is returned.",seeAlso:["++","join","string.template","string.string-repeat","number"],examples:['str("A string", ", and another string", " ...and more")','str("Just one string")',"str()",'str(0, false, true, null, #"^kalle", [1, 2, 3], {a: "a"})'],hideOperatorForm:!0}},number:{evaluate:([e],t)=>{B(e,t);const r=Number(e);if(Number.isNaN(r))throw new n(`Could not convert '${e}' to a number.`,t);return r},arity:G(1),docs:{category:"string",returns:{type:"number"},args:{s:{type:"string"}},variants:[{argumentNames:["s"]}],description:"Parses $s to a number.",seeAlso:["str","number?","integer?"],examples:['number("10")','number("010")','number("-1.01")']}},"lower-case":{evaluate:([e],t)=>(B(e,t),e.toLowerCase()),arity:G(1),docs:{category:"string",returns:{type:"string"},args:{s:{type:"string"}},variants:[{argumentNames:["s"]}],description:"Returns $s converted to lower case.",seeAlso:["upper-case","string.capitalize"],examples:['lower-case("Albert")','lower-case("")']}},"upper-case":{evaluate:([e],t)=>(B(e,t),e.toUpperCase()),arity:G(1),docs:{category:"string",returns:{type:"string"},args:{s:{type:"string"}},variants:[{argumentNames:["s"]}],description:"Returns $s converted to upper case.",seeAlso:["lower-case","string.capitalize"],examples:['upper-case("Albert")','upper-case("")']}},trim:{evaluate:([e],t)=>(B(e,t),e.trim()),arity:G(1),docs:{category:"string",returns:{type:"string"},args:{s:{type:"string"}},variants:[{argumentNames:["s"]}],description:"Returns a new string with leading and trailing whitespaces removed.",seeAlso:["string.trim-left","string.trim-right","blank?"],examples:['trim(" Albert ")','trim(" ")','trim("")']}},join:{evaluate:([e,t],n)=>(oe(e,n),e.forEach(e=>L(e,n)),B(t,n),e.join(t)),arity:G(2),docs:{category:"string",returns:{type:"string"},args:{a:{type:"array"},b:{type:"string"},arr:{type:"array"},delimiter:{type:"string"}},variants:[{argumentNames:["arr","delimiter"]}],description:"Returns a new string by concatenating all of the elements in $arr, separated by $delimiter.",seeAlso:["split","str","++","sequence.interpose"],examples:['map([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], str) join ", "','([0, 1, 2, 3, 4, 5, 6, 7, 8, 9] map str) join ", "','join(["Albert", 10], ", ")','join(["Albert", "Mojir"], " ")','join(map([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], str), ", ")']}},split:{evaluate:([e,t,n],r)=>{B(e,r),P(t,r),void 0!==n&&J(n,r,{integer:!0,nonNegative:!0});const a="string"==typeof t?t:new RegExp(t.s,t.f);return e.split(a,n)},arity:{min:2,max:3},docs:{category:"string",returns:{type:"string",array:!0},args:{a:{type:"string"},b:{type:"string"},s:{type:"string"},delimiter:{type:"string"},limit:{type:"integer"}},variants:[{argumentNames:["s","delimiter"]},{argumentNames:["s","delimiter","limit"]}],description:"Divides $s into an array of substrings. The division is done by searching for `delimiter`. If `limit` as provided, at most `limit` number of substrings are returned.",seeAlso:["join","string.split-lines"],examples:['"Albert Mojir" split " "','split("Albert Mojir", " ")','split("abcdefghijklmnopqrstuvw", #"[aoueiy]")','split("0123456789", "")','split("0123456789", "", 5) map number']}},"blank?":{evaluate:([e],t)=>null===e||(B(e,t),Oe.test(e)),arity:G(1),docs:{category:"string",returns:{type:"boolean"},args:{s:{type:["string","null"]}},variants:[{argumentNames:["s"]}],description:"Returns true if $s is null or only contains whitespace characters.",seeAlso:["trim","empty?","string?"],examples:['blank?("")',"blank?(null)",'blank?("\n")','blank?(" ")','blank?(".")']}}},Ve={"|>":{evaluate:()=>{throw new Error("|> is implemented in Dvala")},arity:G(2),docs:{category:"functional",returns:{type:"any"},args:{a:{type:"any"},b:{type:"function"}},variants:[{argumentNames:["a","b"]}],description:"Takes a value $a and a function $b, and returns the result of applying $b to $a.",seeAlso:["apply","comp"],examples:["\n1 |> inc |> inc","range(10)\n |> map(_, -> $ ^ 2) // [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n |> filter(_, odd?) // [1, 9, 25, 49, 81]\n |> reduce(_, +, 0) // 165\n |> sqrt // 12.84523257866513\n |> round(_, 2)"]}},apply:{evaluate:()=>{throw new Error("apply is implemented in Dvala")},arity:{min:2},docs:{category:"functional",returns:{type:"any"},args:{a:{type:"function"},b:{type:"array"},fun:{type:"function"},args:{type:"array"}},variants:[{argumentNames:["fun","args"]}],description:"Call supplied function $fun with specified arguments $args.",seeAlso:["|>"],examples:["\napply(+, [1, 2, 3])","\napply(\n (x, y) -> sqrt(x ^ 2 + y ^ 2),\n [3, 4]\n)","\n(x, y) -> sqrt(x ^ 2 + y ^ 2) apply [3, 4]"]}},identity:{evaluate:([e])=>te(e),arity:G(1),docs:{category:"functional",returns:{type:"any"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns $x.",seeAlso:["constantly","functional.fnull"],examples:["identity(1)",'identity("Albert")',"identity({ a: 1 })","identity(null)"]}},comp:{evaluate:(e,t)=>{return e.forEach(e=>V(e,t)),{[u]:!0,sourceCodeInfo:t,functionType:"Comp",params:e,arity:e.length>0?(n=e.at(-1),"number"==typeof n||q(n)?G(1):n.arity):{min:1,max:1}};var n},arity:{},docs:{category:"functional",returns:{type:"function"},args:{a:{type:"function"},b:{type:"function"},fns:{type:"function",rest:!0}},variants:[{argumentNames:["fns"]}],description:"Takes a variable number of functions and returns a function that is the composition of those.\n\n The returned function takes a variable number of arguments,\n applies the rightmost function to the args,\n the next function (right-to-left) to the result, etc.",seeAlso:["|>","functional.juxt","functional.complement"],examples:["\nlet negative-quotient = comp(-, /);\nnegative-quotient(9, 3)",'\nlet x = { bar: { foo: 42 } };\ncomp("foo", "bar")(x)']}},constantly:{evaluate:([e],t)=>({[u]:!0,sourceCodeInfo:t,functionType:"Constantly",value:te(e),arity:{}}),arity:G(1),docs:{category:"functional",returns:{type:"function"},args:{x:{type:"any"}},variants:[{argumentNames:["x"]}],description:"Returns a function that takes any number of arguments and always returns $x.",seeAlso:["identity","functional.fnull"],examples:["\nlet always-true = constantly(true);\nalways-true(9, 3)"]}}};function Ue(e){return se(`\n ${e.title}\n\n ${e.description.replace(/`(.+?)`/g,"$1").replace(/\$(\w+)/g,"$1").replace(/\*\*\*(.+)\*\*\*/g,"$1").replace(/\*\*(.+)\*\*/g,"$1")}\n\n Signature:\n ${function(e){const{title:t,variants:n,args:r,returns:a}=e,s=!Be(e)&&e._isOperator,o=n.map(n=>{if(Be(e)){const e=n.argumentNames.length>0?`, ${n.argumentNames.map(e=>{let t="";return r[e].rest&&(t+="..."),t+=e,t}).join(", ")}`:"";return` perform(effect(${t})${e}) -> ${De(a)}`}return`${` ${t}(${n.argumentNames.map(e=>{let t="";return r[e].rest&&(t+="..."),t+=e,t}).join(", ")})`} -> ${De(a)}`}),i=s?["","Operator:",` a ${t} b -> ${De(a)}`]:[];return[...o,...i]}(e).join("\n ")}\n\n Arguments:\n ${function(e){return Object.entries(e.args).map(([e,t])=>`${e}: ${De(t)}`)}(e).join("\n ")}\n\n Examples:\n${e.examples.map(e=>se(e,4)).join("\n\n")}`)}function Be(e){return"effect"in e}function De(e){const t=e.type,n=(Array.isArray(t)?t:[t]).join(" | ");return e.array||e.rest?`Array<${n}>`:n}const _e={sum:{evaluate:([e],t)=>(we(e,t),e.reduce((e,t)=>e+t,0)),arity:G(1),docs:{category:"vector",returns:{type:"number"},args:{vector:{type:"vector",description:"The vector to sum."}},variants:[{argumentNames:["vector"]}],description:"Returns the **sum** of all elements in the `vector`. Returns `0` for an empty vector.",seeAlso:["prod","mean","median","vector.moving-sum","vector.centered-moving-sum","vector.running-sum","vector.cumsum"],examples:["sum([1, 2, 3, 4, 5])","sum([1, -2, 3])","sum([])"]}},prod:{evaluate:([e],t)=>(we(e,t),e.reduce((e,t)=>e*t,1)),arity:G(1),docs:{category:"vector",returns:{type:"number"},args:{vector:{type:"vector",description:"The vector to multiply."}},variants:[{argumentNames:["vector"]}],description:"Returns the **product** of all elements in the `vector`. Returns `1` for an empty vector.",seeAlso:["sum","mean","median","vector.moving-prod","vector.centered-moving-prod","vector.running-prod","vector.cumprod"],examples:["prod([1, 2, 3, 4, 5])","prod([1, -2, 3])","prod([])"]}},mean:{evaluate:([e],t)=>(ke(e,t),e.reduce((e,t)=>e+t,0)/e.length),arity:G(1),docs:{category:"vector",returns:{type:"number"},args:{vector:{type:"vector",description:"The vector to calculate the mean of."}},variants:[{argumentNames:["vector"]}],description:"Returns the arithmetic **mean** of all elements in the `vector`. Throws for an empty vector.",seeAlso:["median","sum","prod","vector.moving-mean","vector.centered-moving-mean","vector.running-mean","vector.geometric-mean","vector.harmonic-mean","vector.rms","vector.mode"],examples:["mean([1, 2, 3, 4, 5])","mean([1, -2, 3])"]}},median:{evaluate:([e],t)=>(ke(e,t),function(e){const t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2==0?(t[n-1]+t[n])/2:t[n]}(e)),arity:G(1),docs:{category:"vector",returns:{type:"number"},args:{vector:{type:"vector",description:"The vector to calculate the median of."}},variants:[{argumentNames:["vector"]}],description:"Returns the **median** of all elements in the `vector`. For even-length vectors, returns the average of the two middle values. Throws for an empty vector.",seeAlso:["mean","sum","prod","vector.moving-median","vector.centered-moving-median","vector.running-median","vector.mode","vector.quartiles","vector.percentile","vector.iqr","vector.medad"],examples:["median([1, 2, 3, 4, 5])","median([1, 2, 3, 4])","median([3, 1, 4, 1, 5])"]}}},Fe={...z,...H,...ce,...ue,...pe,...je,...function(e,t){return{doc:{evaluate:([n],r)=>{if(b(e),T(n)){const e=`-effect-${n.name}`,r=t[e];return r?Ue(r):""}if(V(n,r),!w(n))return"";if("Builtin"===n.functionType){const t=e[n.name];return t?Ue(t):""}return"UserDefined"===n.functionType?n.docString:""},arity:G(1),docs:{category:"meta",returns:{type:"string"},args:{value:{type:["function","effect"]}},variants:[{argumentNames:["value"]}],description:"Returns documentation string of the $value. Works on functions and effects.",seeAlso:["arity","with-doc"],examples:["doc(+)","doc(effect(dvala.io.println))",'let add = (x, y) -> x + y with-doc "Adds two numbers.";\ndoc(add)']}},"with-doc":{evaluate:([e,t],n)=>{if(V(e,n),B(t,n),!w(e)||"UserDefined"!==e.functionType)throw new Error("with-doc can only be used with user-defined functions");return{...e,[u]:!0,docString:t}},arity:G(2),docs:{category:"meta",returns:{type:"function"},args:{a:{type:"function"},b:{type:"string"}},variants:[{argumentNames:["a","b"]}],description:"Returns a new function with the documentation string $b attached. The original function is not modified.",seeAlso:["doc"],examples:['((x, y) -> x + y) with-doc "Adds two numbers."','let add = (x, y) -> x + y;\nadd with-doc "Adds x and y."']}},arity:{evaluate:([e],n)=>{if(T(e)){const n=`-effect-${e.name}`,r=t[n];if(!r)return{};const a=r.variants.map(e=>e.argumentNames.length);return{min:Math.min(...a),max:Math.max(...a)}}return V(e,n),w(e)?e.arity:G(1)},arity:G(1),docs:{category:"meta",returns:{type:"object"},args:{value:{type:["function","effect"]}},variants:[{argumentNames:["value"]}],description:"Returns arity of the $value. The arity is an object with the properties: `min` and `max`. If the function has fixed arity, `min` and `max` are equal to the number of required parameters. If no restrictions apply, empty object is returned. Also works on effects.",seeAlso:["doc"],examples:["arity(+)","arity(defined?)","arity(effect(dvala.random.int))","\nlet add = (x, y = 0) -> do\n x + y;\nend;\n\narity(add)","\nlet foo = (k, ...x) -> do\n k + x;\nend;\n arity(foo)"]}}}}({},{}),...Ce,...Re,...Pe,...Te,...Me,...Ve,..._e};Object.entries(Fe).forEach(([e,t])=>{t.name=e});const Le={...Fe},ze={},We=[];Object.entries(Le).forEach(([e,t],n)=>{ze[e]=n,We.push(t)});const Je={arity:{},docs:{category:"special-expression",returns:{type:"any"},args:{a:{type:"any"},b:{type:"any"},c:{type:"any",rest:!0}},variants:[{argumentNames:["a","b"]},{argumentNames:["a","b","c"]}],description:"\nComputes logical `and`. Evaluation of expressions starts from left.\nAs soon as an `expression` evaluates to a falsy value, the result is returned.\n\nIf all expressions evaluate to truthy values, the value of the last expression is returned.",examples:["true && 1","&&(1, 1)",'&&(3 > 2, "string")','&&(3 < 2, "string")',"&&(true, true, true, true)","&&(true, true, 0, true)"]},evaluateAsNormalExpression:(e,t)=>{let n=!0;for(const r of e)if(n=E(r,t),!n)break;return n},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1],t,r,a)},Ye={arity:{},docs:{category:"special-expression",customVariants:["cond cond-branch cond-branch ... end"],details:[["cond-branch","case test then body","A branch of the cond expression."],["test","expression","The condition to test."],["body","expressions","The expressions to evaluate if the test is truthy."]],description:"Used for branching. `cond-branches` are tested sequentially from the top. If no branch is tested truthy, `null` is returned.",examples:['\ncond\n case false then "FALSE"\n case true then "TRUE"\nend','\ncond\n case false then "FALSE"\n case null then "null"\nend ?? "TRUE"','\ncond\n case false then "FALSE"\n case null then "null"\nend ?? "TRUE"']},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1].flat(),t,r,a)},Ke=11,Ge=12,Xe=13,He=14,Ze=15,Qe=16;function et(e,t){return e instanceof Promise?e.then(t):t(e)}async function tt(e,t,n,r,a){t.push(await e);for(let e=a+1;e<n.length;e++)t.push(await r(n[e],e));return t}function nt(e,t,n){let r=n;for(let n=0;n<e.length;n++){const a=t(r,e[n],n);if(a instanceof Promise)return rt(a,e,t,n);r=a}return r}async function rt(e,t,n,r){let a=await e;for(let e=r+1;e<t.length;e++)a=await n(a,t[e],e);return a}function at(e,t){for(let n=0;n<e.length;n++){const r=t(e[n],n);if(r instanceof Promise)return st(r,e,t,n)}}async function st(e,t,n,r){await e;for(let e=r+1;e<t.length;e++)await n(t[e],e)}function ot(e,t){if(e[0]===Xe)Object.values(e[1][0]).forEach(e=>{e[1][1]&&t(e[1][1]),ot(e,t)});else if(e[0]===He)for(let n=0;n<e[1][0].length;n+=1){const r=e[1][0][n]??null;null!==r&&(r[1][1]&&t(r[1][1]),ot(r,t))}}function it(e,t,n){const r=e[2],a={};return et(lt(e,t,n,r,a),()=>a)}function lt(e,t,r,a,s){if(e[0]===Xe){!function(e,t){if(!x(e))throw new n(`Expected UnknownRecord, got ${y(e)}.`,g(e,t))}(t,a);const o=new Set;let i;return et(at(Object.entries(e[1][0]),([e,n])=>{if(n[0]===Ge)return void(i=n);o.add(e);const l=t[e];return et(void 0!==l?l:n[1][1]?r(n[1][1]):null,e=>{const t=e??null;return N(t,a),lt(n,t,r,a,s)})}),()=>{if(i){const e=Object.entries(t).filter(([e])=>!o.has(e)).reduce((e,[t,n])=>(e[t]=E(n),e),{});s[i[1][0]]=e}})}if(e[0]===He){let n=null;oe(t,a);const o=[];for(let t=0;t<e[1][0].length;t+=1){const r=e[1][0][t]??null;if(null!==r){if(r[0]===Ge){n=t;break}o.push({element:r,index:t})}}return et(at(o,({element:e,index:n})=>{const o=t[n];return et(void 0!==o?o:e[1][1]?r(e[1][1]):null,t=>{const n=t??null;return N(n,a),lt(e,n,r,a,s)})}),()=>{if(null!==n){const r=t.slice(n),a=e[1][0][n];s[a[1][0]]=r}})}e[0]===Ge?s[e[1][0]]=E(t):s[e[1][0][1]]=E(t)}function ct(e){const t={};return ut(e,t),t}function ut(e,t){if(null!==e)if(e[0]===He)for(const n of e[1][0])ut(n,t);else if(e[0]===Xe)for(const n of Object.values(e[1][0]))ut(n,t);else if(e[0]===Ge){if(t[e[1][0]])throw new n(`Duplicate binding name: ${e[1][0]}`,e[2]);t[e[1][0]]=!0}else if(e[0]===Ke){if(t[e[1][0][1]])throw new n(`Duplicate binding name: ${e[1][0]}`,e[2]);t[e[1][0][1]]=!0}}function pt(e,t,n){const r={};return et(ft(e,t,n,r),e=>e?r:null)}function ft(e,t,n,r){if(e[0]===Qe)return!0;if(e[0]===Ze){const r=e[1][0];return et(n(r),e=>ee(t,e))}if(e[0]===Ke){const a=e[1][0],s=e[1][1];if(null==t){if(s)return et(n(s),e=>(r[a[1]]=E(e),!0));r[a[1]]=t??null}else r[a[1]]=E(t);return!0}if(e[0]===Xe){if(!x(t))return!1;const a=new Set;let s;const o=Object.entries(e[1][0]);let i=!0;for(const[e,l]of o)i=et(i,o=>{if(!o)return!1;if(l[0]===Ge)return s=l,!0;a.add(e);const i=t[e];if(void 0===i&&l[0]===Ze)return et(n(l[1][0]),e=>ee(void 0,e));return et(void 0!==i?i:l[1]&&l[1][1]?n(l[1][1]):null,e=>ft(l,e??null,n,r))});return et(i,e=>{if(!e)return!1;if(s){const e=Object.entries(t).filter(([e])=>!a.has(e)).reduce((e,[t,n])=>(e[t]=E(n),e),{});r[s[1][0]]=e}return!0})}{const a=e;if(!Array.isArray(t))return!1;const s=a[1][0];let o=null;for(let e=0;e<s.length;e+=1){const t=s[e];if(null!==t&&t[0]===Ge){o=e;break}}if(null===o&&t.length!==s.length)return!1;if(null!==o&&t.length<o)return!1;let i=!0;for(let e=0;e<s.length;e+=1){const a=s[e];if(null===a)continue;if(a[0]===Ge){r[a[1][0]]=t.slice(e);break}const o=a;i=et(i,a=>!!a&&ft(o,E(t[e]),n,r))}return i}}const dt={arity:{},docs:{category:"special-expression",customVariants:["match value match-branch match-branch ... end"],details:[["value","any","The value to match against patterns."],["match-branch","case pattern [when guard] then body","A branch of the match expression."],["pattern","pattern","A pattern to match: literal, variable, array destructuring, object destructuring, or wildcard (_)."],["guard","expression","An optional guard expression that must be truthy for the match to succeed."],["body","expressions","The expressions to evaluate if the pattern matches."]],description:"Pattern matching expression. Matches `value` against each `pattern` sequentially. If a pattern matches (and the optional `when` guard is truthy), the corresponding `body` is evaluated and its result returned. Bound variables from the pattern are available in the guard and body. If no pattern matches, `null` is returned.",examples:['\nmatch 1\n case 1 then "One"\n case 2 then "Two"\nend','\nmatch [1, 2, 3]\n case [x] then "one element"\n case [x, y] then "two elements"\n case [x, ...xs] then "first: " ++ str(x) ++ " rest: " ++ str(xs)\nend','\nmatch { type: "click", x: 10, y: 20 }\n case { type: "click", x, y } then "Click at " ++ str(x) ++ ", " ++ str(y)\n case { type: "keydown", key } then "Key: " ++ key\n case _ then "unknown event"\nend','\nmatch { role: "admin", name: "Alice" }\n case { role: "admin", name } then "Admin: " ++ name\n case { role, name } when role == "user" then "User: " ++ name\n case _ then "Unknown role"\nend']},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>{const s=new Set;n([e[1][1]],t,r,a).forEach(e=>s.add(e));for(const[o,i,l]of e[1][2]){const e={};Object.assign(e,ct(o));const c=t.create(e);l&&n([l],c,r,a).forEach(e=>s.add(e)),n([i],c,r,a).forEach(e=>s.add(e))}return s}},mt={category:"special-expression",returns:{type:"boolean"},args:{symbol:{type:"any"}},variants:[{argumentNames:["symbol"]}],description:"Returns `true` if `symbol` is defined, `false` otherwise.\n\nBuilt-in symbols are always considered defined. For user-defined symbols, checks if the symbol exists in the current scope.",examples:["let x = 42; defined?(x)","defined?(x)","defined?(+)"]},yt={arity:G(1),docs:mt,getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n([e[1][1]],t,r,a)},gt={arity:{},docs:{category:"special-expression",customVariants:["do body end","do body with case effect(name) then handler end"],details:[["body","expressions","The expressions to evaluate."],["effect(name)","expression","An expression evaluating to an effect value."],["handler","expression","A function (args) -> result that handles the effect. Its return value resumes the perform call."]],description:"Evaluates `body`. Resulting value is the value of the last expression. Effect handlers can be installed via `with` to intercept `perform` calls.",examples:["\ndo\n let a = 1 + 2 + 3 + 4;\n let b = -> $ * ( $ + 1 );\n b(a)\nend",'\ndo\n perform(effect(dvala.io.println), "hello")\nwith\n case effect(dvala.io.println) then ([msg]) -> null\nend']},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>{const s=n(e[1][1],t.create({}),r,a),o=e[1][2];if(!o||0===o.length)return s;let i=new Set;for(const[e,s]of o){i=ne(i,n([e],t,r,a),n([s],t,r,a))}return ne(s,i)}},ht={arity:{},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>function(e,t,n,r,a){const s=new Set,o={self:{value:null}};e[0].forEach(e=>{Object.assign(o,ct(e)),ot(e,e=>{re(s,n([e],t,r,a))})});const i=t.create(o),l=n(e[1],i,r,a);return re(s,l),s}(e[1][1],t,n,r,a)};const vt={arity:{min:2,max:3},docs:{category:"special-expression",customVariants:["if test then true-expr else false-expr","if test then true-expr"],details:[["test","expression","The condition to test."],["true-expr","expression","The expression to evaluate if the test is truthy."],["false-expr","expression","The expression to evaluate if the test is falsy."]],description:"Either `true-expr` or `false-expr` branch is taken. `true-expr` is selected when $test is truthy. If $test is falsy `false-expr` is executed, if no `false-expr` exists, `null` is returned.",examples:['\nif true then\n "TRUE"\nelse\n "FALSE"\nend','if false then "TRUE" else "FALSE" end','if true then "TRUE" end','if false then "TRUE" end']},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1].filter(e=>!!e),t,r,a)},bt={arity:{},docs:{category:"special-expression",customVariants:["unless test then true-expr else false-expr end","unless test true-expr end"],details:[["test","expression","The condition to test."],["true-expr","expression","The expressions to evaluate if the test is falsy."],["false-expr","expression","The expressions to evaluate if the test is truthy."]],description:"Either `true-expr` or `false-expr` branch is taken. `true-expr` is selected when $test is falsy. If $test is truthy `false-expr` is executed, if no `false-expr` exists, `null` is returned.",examples:['\nunless true then\n "TRUE"\nelse\n "FALSE"\nend','unless false then "TRUE" else "FALSE" end','unless true then "TRUE" end','unless false then "TRUE" end']},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1].filter(e=>!!e),t,r,a)},xt={category:"special-expression",customVariants:["let s = value;"],details:[["s","symbol","The name of the variable to bind."],["value","any","The value to bind to the variable."]],description:"\n Binds local variables s to `value`. `value` can be any expression. The scope of the variables is the body of the let expression.",examples:["\nlet a = 1 + 2 + 3 + 4;\nlet b = -> $ * ( $ + 1 );\nb(a)"]},wt={arity:G(0),docs:xt,getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>{const s=e[1][1],o=s[1][0],i=s[1][1],l=n([i],t,r,a);return ot(o,e=>{re(l,n([e],t,r,a))}),t.addValues(ct(o),o[2]),l}},kt={arity:{},docs:{category:"special-expression",customVariants:["loop (bindings) -> body"],details:[["bindings","binding pairs","Comma-separated bindings with initial values, e.g. `n = 10, acc = 0`."],["body","expression","The expression to evaluate repeatedly. Use `recur` to loop back with new values."]],description:"Creates a loop with initial bindings. Use `recur` inside the body to jump back to the loop head with new binding values.\n\nIf `recur` is not called, the loop terminates and returns the value of the body expression.",examples:["loop (n = 10, acc = 0) -> do\n if n == 0 then\n acc\n else\n recur(n - 1, acc + n)\n end\nend","loop (n = 5, acc = 1) -> do\n if n <= 1 then\n acc\n else\n recur(n - 1, acc * n)\n end\nend"]},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>{const s=e[1][1],o=s.reduce((e,t)=>{const n=ct(t[1][0]);return Object.keys(n).forEach(t=>{e[t]={value:!0}}),e},{});return ne(n(s.map(e=>e[1][1]),t,r,a),n([e[1][2]],t.create(o),r,a))}};function At(e,t,n,r,a){const s=new Set,o={},[,i,l]=e[1];return i.forEach(e=>{const[i,l,c,u]=e,[p,f]=i[1];n([f],t.create(o),r,a).forEach(e=>s.add(e)),Object.assign(o,ct(p)),l&&l.forEach(e=>{const[i,l]=e[1];n([l],t.create(o),r,a).forEach(e=>s.add(e)),Object.assign(o,ct(i))}),c&&n([c],t.create(o),r,a).forEach(e=>s.add(e)),u&&n([u],t.create(o),r,a).forEach(e=>s.add(e))}),n([l],t.create(o),r,a).forEach(e=>s.add(e)),s}const Et={category:"special-expression",customVariants:["for (...binding) -> body"],details:[["binding","loop-var in collection [...let-binding] [where whereExpr] [while whileExp]","A for loop binding"],["loop-var","symbol","The name of the loop variable."],["collection","any","The collection to iterate over."],["let-binding","let binding","A let binding to create a local variable."],["whereExpr","expression","An expression that must evaluate to truthy for the loop body to be executed."],["whileExp","expression","An expression that must evaluate to truthy for the loop to continue."],["body","expressions","The expressions to evaluate for each iteration of the loop."]],returns:{type:"any",array:!0},description:"Iterates over `bindings`, evaluates `body` for each `binding` and returns an `array` of results.",examples:["\nfor (i in [1, 2, 3]) -> i * 2\n ","\nfor (\n i in range(10) let ii = i ^ 2 while ii < 40 when ii % 3 == 0,\n j in range(10) when j % 2 == 1\n) -> ii + j\n "]},Nt={arity:G(1),docs:Et,getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>At(e,t,n,r,a)},$t={category:"special-expression",customVariants:["doseq (...binding) -> body"],details:[["binding","loop-var in collection [...let-binding] [where whereExpr] [while whileExp]","A doseq loop binding"],["loop-var","symbol","The name of the loop variable."],["collection","any","The collection to iterate over."],["let-binding","let binding","A let binding to create a local variable."],["whereExpr","expression","An expression that must evaluate to truthy for the loop body to be executed."],["whileExp","expression","An expression that must evaluate to truthy for the loop to continue."],["body","expressions","The expressions to evaluate for each iteration of the loop."]],returns:{type:"null"},description:"Iterates over `bindings`, evaluates `body` for each `binding` and returns `null`. This is useful for side effects.",examples:["\ndoseq (i in [1, 2, 3]) -> perform(effect(dvala.io.println), i * 2)\n "]},St={arity:G(1),docs:$t,getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>At(e,t,n,r,a)},It={arity:{},docs:{category:"special-expression",returns:{type:"boolean"},args:{a:{type:"any"},b:{type:"any"},c:{type:"any",rest:!0}},variants:[{argumentNames:["a","b"]},{argumentNames:["a","b","c"]}],description:"\n Computes logical `or`. Evaluation of expressions evaluation starts from left.\n As soon as a `expression` evaluates to a truthy value, the result is returned.\n\n If all expressions evaluate to falsy values, the value of the last expression is returned.",examples:["false || 1","||(1, 1)",'||(3 > 2, "string")','||(3 < 2, "string")',"||(false, false, false, true)","||(1, 2, 3, 4)"]},evaluateAsNormalExpression:(e,t)=>{let n=!1;for(const r of e)if(n=E(r,t),n)break;return n},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1],t,r,a)},jt={arity:{min:1},docs:{category:"special-expression",returns:{type:"any"},args:{a:{type:"any"},b:{type:"any"},c:{type:"any",rest:!0}},variants:[{argumentNames:["a"]},{argumentNames:["a","b"]},{argumentNames:["a","b","c"]}],description:"Nullish coalescing operator. Returns the first non-`null` value.\n\nEvaluation is short-circuited — as soon as a non-`null` value is found, the remaining expressions are not evaluated.\n\nIf all values are `null`, returns `null`.\n\nAlso works with undefined symbols — if a symbol is undefined, it is treated as `null`.",examples:["1 ?? 2","null ?? 2","??(null)",'??(null, "default")','??(1, "default")','false ?? "default"',"??(null, null, 3)"]},evaluateAsNormalExpression:(e,t)=>{for(const n of e){const e=E(n,t);if(null!==e)return e}return null},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1],t,r,a)},qt={arity:{},docs:{category:"special-expression",customVariants:["recur(...recur-args)"],description:"Recursevly calls enclosing function or loop with its evaluated `recur-args`.",examples:["\nlet foo = (n) -> do\n if zero?(n) then\n 0\n else\n n + recur(n - 1)\n end\nend;\nfoo(3)","\n((n) -> do\n if zero?(n) then\n 0\n else\n n + recur(n - 1)\n end\nend)(3)","\nloop (n = 3, acc = 0) -> do\n if zero?(n) then\n acc\n else\n recur(n - 1, acc + n)\n end\nend"]},evaluateAsNormalExpression:e=>{throw new t(e)},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1],t,r,a)},Ct={arity:{},docs:{category:"special-expression",returns:{type:"any",array:!0},args:{values:{type:"any",rest:!0}},variants:[{argumentNames:["values"]}],description:"Makes new array from $values.",examples:["array(1, 2, 3)","array(array(null, false, true))","[]","[1, 2, 3]","[1, 2, ...[3, 4, 5], 6]","[[null, false, true]]","[1, 2, 3][1]"],hideOperatorForm:!0},evaluateAsNormalExpression:(e,t)=>{const n=[];for(const r of e)n.push(E(r,t));return n},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1],t,r,a)},Rt={arity:{},docs:{category:"special-expression",customVariants:["effect(name)"],details:[["name","dotted identifier","The effect name, e.g. `llm.complete` or `dvala.io.println`."]],description:"Returns the unique effect reference for the given name. Calling `effect` with the same name always returns the same reference. Effect references are first-class values that can be stored, passed, and compared with `==`.",examples:["effect(dvala.io.println)","==(effect(llm.complete), effect(llm.complete))"],seeAlso:["effect?"]},getUndefinedSymbols:()=>new Set},Pt={arity:{},docs:{category:"special-expression",returns:{type:"object"},args:{kvps:{type:"any",rest:!0,description:"key - value pairs, where key is a string"}},variants:[{argumentNames:["kvps"]}],description:"Constructs a new object. Object members are created from the $kvps key-value pairs. Requires an even number of arguments.",examples:["object()",'\nlet default = {\n type: "Person",\n name: "John Doe",\n age: 42\n};\n\n{\n ...default,\n name: "Lisa"\n}','object("x", 10, "y", true, "z", "A string")',"{}","{ a: 1, b: 2 }"],hideOperatorForm:!0},evaluateAsNormalExpression:(e,t)=>{const n={};for(let r=0;r<e.length;r+=2){const a=e[r],s=e[r+1];B(a,t),n[a]=s??null}return n},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>n(e[1][1],t,r,a)},Tt={arity:G(1),docs:{category:"special-expression",description:"Imports all functions from a module as an object. Use destructuring to pick specific functions.",customVariants:["import(module-name)"],returns:{type:"object"},examples:["let v = import(vector); v.stdev([1, 2, 3, 4])","let { linspace } = import(vector); linspace(0, 10, 5)","let g = import(grid); g.row([[1, 2], [3, 4]], 0)"]},getUndefinedSymbols:()=>new Set},Ot={arity:{min:1},docs:{category:"special-expression",customVariants:["parallel(expr1, expr2, ...)"],details:[["expr1, expr2, ...","expressions","Expressions to evaluate concurrently. Typically `perform(...)` calls."]],description:"Evaluates all branch expressions concurrently and returns an array of results in order. Each branch runs as an independent trampoline invocation. If any branch suspends, the entire `parallel` suspends with a composite blob. On resume, branches are resumed one at a time. Only available in async mode (`run()`). Requires at least one branch.",examples:[]},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>ne(...e[1][1].map(e=>n([e],t,r,a)))},Mt={arity:{min:1},docs:{category:"special-expression",customVariants:["perform(eff)","perform(eff, arg1)","perform(eff, arg1, arg2, ...)"],details:[["eff","expression","An expression evaluating to an effect value (from `effect(name)`)."],["arg1, arg2, ...","expressions","Arguments passed to the effect handler."]],description:"Invokes an effect. The nearest enclosing `do/with` handler matching the effect intercepts the call. The handler receives the arguments as an array and its return value becomes the result of `perform`. If no local handler matches, the effect is dispatched to the host.",examples:['\ndo\n perform(effect(dvala.io.println), "hello")\nwith\n case effect(dvala.io.println) then ([msg]) -> msg\nend\n'],seeAlso:["effect?"]},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>{const[,s,o]=e[1];return ne(n([s],t,r,a),n(o,t,r,a))}},Vt={arity:{min:1},docs:{category:"special-expression",customVariants:["race(expr1, expr2, ...)"],details:[["expr1, expr2, ...","expressions","Expressions to race concurrently. Typically `perform(...)` calls."]],description:"Races all branch expressions concurrently. The first branch to complete wins — its value becomes the result. Losing branches are cancelled via AbortSignal. Errored branches are silently dropped. If all branches error, throws an aggregate error. If no branch completes but some suspend, the race suspends. On resume, the host provides the winner value directly. Only available in async mode (`run()`). Requires at least one branch.",examples:[]},getUndefinedSymbols:(e,t,{getUndefinedSymbols:n,builtin:r,evaluateNode:a})=>ne(...e[1][1].map(e=>n([e],t,r,a)))},Ut={"??":0,"&&":1,"||":2,array:3,cond:4,"defined?":5,block:6,doseq:7,"0_lambda":8,for:9,if:10,let:11,loop:12,object:13,recur:14,match:15,unless:16,import:17,effect:18,perform:19,parallel:20,race:21},Bt={normalExpressions:Le,specialExpressions:[jt,Je,It,Ct,Ye,yt,gt,St,ht,Nt,vt,wt,kt,Pt,qt,dt,bt,Tt,Rt,Mt,Ot,Vt],allNormalExpressions:We},Dt=Object.keys(Le),_t=Object.keys(Ut);function Ft(e){return o.UserDefinedSymbol===e[0]}function Lt(e,t){return function(e,t){if(!Ft(e))throw h("UserDefinedSymbolNode",e,t)}(e,t),e}function zt(e){return o.NormalBuiltinSymbol===e[0]}function Wt(e){return o.SpecialBuiltinSymbol===e[0]}function Jt(e){return!!function(e){return e[0]===o.NormalExpression}(e)&&function(e){const t=e[0];return o.UserDefinedSymbol===t||o.NormalBuiltinSymbol===t||o.SpecialBuiltinSymbol===t}(e[1][0])}function Yt(e){return e[0]===o.Spread}class Kt{_contexts;globalContext;values;modules;valueModules;pure;constructor({contexts:e,values:t,modules:n,valueModules:r,pure:a}){this.globalContext=v(e[0]),this._contexts=e,this.values=t,this.modules=n??new Map,this.valueModules=r??new Map,this.pure=a??!1}getContextsRaw(){return this._contexts}getHostValues(){return this.values}getModuleScopeBindings(){const e=this._contexts[0],t={};for(const[n,r]of Object.entries(e))t[n]=r.value;return t}getGlobalContextIndex(){return this._contexts.indexOf(this.globalContext)}static fromDeserialized(e){const t=new Kt({contexts:e.contexts,values:e.values,modules:e.modules,pure:e.pure});return e.globalContextIndex>=0&&e.globalContextIndex<e.contexts.length&&(t.globalContext=e.contexts[e.globalContextIndex]),t}setContextsFromDeserialized(e,t){this._contexts=e,t>=0&&t<e.length&&(this.globalContext=e[t])}getModule(e){return this.modules.get(e)}getValueModule(e){return this.valueModules.has(e)?{value:this.valueModules.get(e),found:!0}:{value:void 0,found:!1}}registerValueModule(e,t){this.valueModules.set(e,t)}create(e){const t=this.globalContext,n=new Kt({contexts:[e,...this._contexts],values:this.values,modules:this.modules,valueModules:this.valueModules,pure:this.pure});return n.globalContext=t,n}new(e){return new Kt({contexts:[{},e],modules:this.modules,valueModules:this.valueModules,pure:this.pure})}addValues(e,t){const r=this._contexts[0];for(const[a,s]of Object.entries(e)){if(r[a])throw new n(`Cannot redefine value "${a}"`,t);const e=Gt(a);if(e)throw new n(`Cannot shadow ${e}`,t);r[a]={value:te(s)}}}getValue(e){for(const t of this._contexts){const n=t[e];if(n)return n.value}return this.values?.[e]}lookUp(e){const t=e[1];for(const e of this._contexts){const n=e[t];if(n)return n}const n=this.values?.[t];return void 0!==n?{value:te(n)}:null}evaluateSymbol(e){if(Wt(e)){const t=e[1];switch(t){case Ut["&&"]:case Ut["||"]:case Ut.array:case Ut.object:case Ut["defined?"]:case Ut.recur:case Ut["??"]:{const n=v(Bt.specialExpressions[t],e[2]);return{[u]:!0,functionType:"SpecialBuiltin",specialBuiltinSymbolType:t,sourceCodeInfo:e[2],arity:n.arity}}default:throw new n(`Unknown special builtin symbol type: ${t}`,e[2])}}if(zt(e)){const t=e[1],n=We[t],r=n.name;return{[u]:!0,functionType:"Builtin",normalBuiltinSymbolType:t,sourceCodeInfo:e[2],arity:n.arity,name:r}}const t=this.lookUp(e);if(x(r=t)&&void 0!==r.value)return t.value;var r;throw new s(e[1],e[2])}}function Gt(e){return _t.includes(e)?`special expression "${e}"`:Dt.includes(e)?`builtin function "${e}"`:"self"===e?`builtin value "${e}"`:null}function Xt(e){const t=Gt(e);if(t)throw new n(`Cannot shadow ${t}`,void 0)}function Ht(e={},t,r){const a=e.globalContext??{},s=e.contexts?[a,...e.contexts]:[a];let o;if(e.bindings)for(const[t,r]of Object.entries(e.bindings)){if(t.includes("."))throw new n(`Dots are not allowed in binding keys: "${t}"`,void 0);Xt(t),o||(o={}),o[t]=r}const i=new Kt({contexts:s,values:o,modules:t,pure:r});return e.globalModuleScope?i:i.create({})}const Zt=(e,t,n,r)=>{const a=Array.isArray(e)?e:[[o.SpecialExpression,[Ut.block,e.body,void 0]]],s=new Set;for(const e of a)Qt(e,t,n,r)?.forEach(e=>s.add(e));return s};function Qt(e,t,r,a){const s=e[0];switch(s){case o.UserDefinedSymbol:{const n=e;return null===t.lookUp(n)?new Set([n[1]]):null}case o.NormalBuiltinSymbol:case o.SpecialBuiltinSymbol:case o.String:case o.Number:case o.ReservedSymbol:case o.Binding:return null;case o.NormalExpression:{const n=e,s=new Set;if(Jt(n)){const[,[e]]=n;if(Ft(e)){null===t.lookUp(e)&&s.add(e[1])}}else{const[,[e]]=n;Qt(e,t,r,a)?.forEach(e=>s.add(e))}for(const e of n[1][1])Qt(e,t,r,a)?.forEach(e=>s.add(e));return s}case o.SpecialExpression:{const n=e,s=n[1][0];return(0,r.specialExpressions[s].getUndefinedSymbols)(n,t,{getUndefinedSymbols:Zt,builtin:r,evaluateNode:a})}case o.Spread:return Qt(e[1],t,r,a);default:throw new n(`Unhandled node type: ${s}`,e[2])}}const en=["^","*","/","%","+","-","<<",">>",">>>","++","<","<=","≤",">",">=","≥","==","!=","!=","&","xor","|","&&","||","??","|>"],tn=[...en,"?",":","->","...",".",",","=",":",";"],nn=new Set(["comment","cond","defined?","block","doseq","if","let","loop","recur","unless","while"]);function rn(e){return!nn.has(e)}const an=new Set(en);function sn(e){return an.has(e)}const on=new Set(tn);function ln(e){return on.has(e)}function cn(e,t){return"Symbol"===e?.[0]&&(!t||e[1]===t)}function un(e,t){return function(e,t){cn(e,t)||Cn("Symbol",void 0,e)}(e,t),e}function pn(e,t){return"ReservedSymbol"===e?.[0]&&(!t||e[1]===t)}function fn(e,t){pn(e,t)||Cn("ReservedSymbol",t,e)}function dn(e,t){return fn(e,t),e}function mn(e,t){return"Operator"===e?.[0]&&(!t||e[1]===t)}function yn(e,t){mn(e,t)||Cn("Operator",t,e)}function gn(e){return"Number"===e?.[0]}function hn(e){return"BasePrefixedNumber"===e?.[0]}function vn(e){return"LParen"===e?.[0]}function bn(e){vn(e)||Cn("LParen",void 0,e)}function xn(e){return"RParen"===e?.[0]}function wn(e){xn(e)||Cn("RParen",void 0,e)}function kn(e){return"LBracket"===e?.[0]}function An(e){return function(e){kn(e)||Cn("LBracket",void 0,e)}(e),e}function En(e){return"RBracket"===e?.[0]}function Nn(e){En(e)||Cn("RBracket",void 0,e)}function $n(e){return"LBrace"===e?.[0]}function Sn(e){return function(e){$n(e)||Cn("LBrace",void 0,e)}(e),e}function In(e){return"RBrace"===e?.[0]}function jn(e){return"string"===e?.[0]}function qn(e){return"Operator"===e?.[0]&&sn(e[1])}function Cn(e,t,r){const a=r?`${r[0]} '${r[1]}'`:"end of input";throw new n(`Unexpected token: ${a}, expected ${e}${t?` '${t}'`:""}`,r?.[2])}function Rn(e,t){return t&&(e[2]=t),e}function Pn(e,t){return void 0!==Ut[e]&&"fn"!==e&&"defn"!==e?Rn([o.SpecialBuiltinSymbol,Ut[e]],t):void 0!==ze[e]?Rn([o.NormalBuiltinSymbol,ze[e]],t):Rn([o.UserDefinedSymbol,e],t)}function Tn(e){return e.substring(1,e.length-1).replace(/(\\{2})|(\\')|\\(.)/g,(e,t,n,r)=>t?"\\":n?"'":`\\${r}`)}const On=Object.entries(ze).reduce((e,[t,n])=>(e[n]=t,e),[]),Mn=Object.entries(Ut).reduce((e,[t,n])=>(e[n]=t,e),[]);function Vn(e){return Ft(e)?e[1]:zt(e)?On[e[1]]:Mn[e[1]]}function Un(e,t,n){const r=Rn([o.NormalExpression,[e,t]],n);return zt(e)&&K(We[e[1]].arity,r[1][1].length,n),r}function Bn(e){if(e.isAtEnd())return!0;const t=e.tryPeek();return mn(t)?[";",",",":"].includes(t[1]):!!pn(t)&&["else","when","while","case","let","then","end","do"].includes(t[1])}function Dn(e,t,r,a,s){const i=e[1];switch(i){case"^":case"*":case"/":case"%":case"+":case"-":case"<<":case">>":case">>>":case"++":case"<":case"<=":case"≤":case">":case">=":case"≥":case"==":case"!=":case"&":case"xor":case"|":case"|>":return Un(t,[r,a],s);case"&&":case"||":case"??":return Rn([o.SpecialExpression,[Ut[i],[r,a]]],s);default:throw new n(`Unknown binary operator: ${i}`,s)}}class _n{tokens;position;storedPosition=0;parseExpression;constructor(e){this.tokens=e.tokens,this.position=0}advance(){this.position+=1}tryPeek(){return this.tokens[this.position]}peek(){const e=this.tokens[this.position];if(!e){const e=this.tokens.at(-1),t=e?e[2]:void 0;throw new n("Unexpected end of input",t)}return e}isAtEnd(){return this.position>=this.tokens.length}peekSourceCodeInfo(){const e=this.tryPeek();return e?e[2]:this.tokens.at(-1)?.[2]}storePosition(){return this.storedPosition=this.position}restorePosition(){this.position=this.storedPosition}peekAhead(e){return this.tokens[this.position+e]}getPosition(){return this.position}getTokenAt(e){return this.tokens[e]}}function Fn(e,t){switch(e){case"^":return 12;case"*":case"/":case"%":return 11;case"+":case"-":return 10;case"<<":case">>":case">>>":return 9;case"++":return 8;case"<":case"<=":case"≤":case">":case">=":case"≥":return 7;case"==":case"!=":return 6;case"&":case"xor":case"|":return 5;case"&&":case"||":case"??":return 4;case"|>":return 2;default:throw new n(`Unknown binary operator: ${e}`,t)}}function Ln(e,t){const r=[];for(;!e.isAtEnd()&&!zn(e,t);)mn(e.tryPeek(),";")?e.advance():r.push(e.parseExpression());if(function(e,t){if(!zn(e,t))throw new n(`Expected ${t.map(e=>e[1]).join(" or ")}`,e.peekSourceCodeInfo())}(e,t),0===r.length)throw new n("Expected expression",e.peekSourceCodeInfo());return 1===r.length?r[0]:Rn([o.SpecialExpression,[Ut.block,r,void 0]],e.peekSourceCodeInfo())}function zn(e,t){for(const n of t)if(pn(e.tryPeek(),n))return!0;return!1}function Wn(e){const t=dn(e.tryPeek(),"do");e.advance();const r=[];for(;!e.isAtEnd()&&!pn(e.tryPeek(),"end")&&!pn(e.tryPeek(),"with");)if(r.push(e.parseExpression()),mn(e.tryPeek(),";"))e.advance();else if(!pn(e.tryPeek(),"end")&&!pn(e.tryPeek(),"with"))throw new n("Expected end",e.peekSourceCodeInfo());let a;if(pn(e.tryPeek(),"with"))for(e.advance(),a=[];!e.isAtEnd()&&!pn(e.tryPeek(),"end");){fn(e.tryPeek(),"case"),e.advance();const t=e.parseExpression();fn(e.tryPeek(),"then"),e.advance();const n=Ln(e,["case","end"]);a.push([t,n])}return fn(e.tryPeek(),"end"),e.advance(),Rn([o.SpecialExpression,[Ut.block,r,a]],t[2])}function Jn(e){const t=e.peek();if(e.advance(),!cn(t))throw new n(`Expected symbol token, got ${t[0]}`,t[2]);return"'"===t[1][0]?Pn(Tn(t[1]),t[2]):Pn(t[1],t[2])}function Yn(e,t){e.advance();const n=t[1].substring(1,t[1].length-1).replace(/(\\{2})|(\\")|(\\n)|(\\t)|(\\r)|(\\b)|(\\f)|\\(.)/g,(e,t,n,r,a,s,o,i,l)=>t?"\\":r?"\n":a?"\t":s?"\r":o?"\b":i?"\f":n?'"':l);return Rn([o.String,n],t[2])}function Kn(e){const t=e.peek();e.advance();const n=t[1],r="-"===n[0],a=(r?n.substring(1):n).replace(/_/g,"");return Rn([o.Number,r?-Number(a):Number(a)],t[2])}function Gn(e,{requireDefaultValue:t,noRest:r,allowLiteralPatterns:a}={}){const s=e.tryPeek();if(a&&pn(s,"_"))return e.advance(),Rn([Qe,[]],s[2]);if(a&&Hn(s)){if(gn(s)||hn(s)){const t=Kn(e);return Rn([Ze,[t]],s[2])}if(jn(s)){const t=Yn(e,s);return Rn([Ze,[t]],s[2])}if(pn(s,"true")){e.advance();const t=Rn([o.ReservedSymbol,"true"],s[2]);return Rn([Ze,[t]],s[2])}if(pn(s,"false")){e.advance();const t=Rn([o.ReservedSymbol,"false"],s[2]);return Rn([Ze,[t]],s[2])}if(pn(s,"null")){e.advance();const t=Rn([o.ReservedSymbol,"null"],s[2]);return Rn([Ze,[t]],s[2])}}if(cn(s)){const r=Jn(e);if(!Ft(r))throw new n("Expected user defined symbol",s[2]);const a=Xn(e);if(t&&!a)throw new n("Expected assignment",e.peekSourceCodeInfo());return Rn([Ke,[r,a]],s[2])}if(mn(s,"...")){if(r)throw new n("Rest element not allowed",s[2]);e.advance();const t=Lt(Jn(e));if(mn(e.tryPeek(),"="))throw new n("Rest argument can not have default value",e.peekSourceCodeInfo());return Rn([Ge,[t[1],void 0]],s[2])}if(kn(s)){e.advance();const r=[];let o=e.peek(),i=!1;for(;!En(o);){if(i)throw new n("Rest argument must be last",o[2]);if(mn(o,",")){r.push(null),e.advance(),o=e.peek();continue}const t=Gn(e,{allowLiteralPatterns:a});t[0]===Ge&&(i=!0),r.push(t),o=e.peek(),En(o)||(yn(o,","),e.advance()),o=e.peek()}e.advance();const l=Xn(e);if(t&&!l)throw new n("Expected assignment",e.peekSourceCodeInfo());return Rn([He,[r,l]],s[2])}if($n(s)){e.advance();const r={};let o=e.peek(),i=!1;for(;!In(o);){if(i)throw new n("Rest argument must be last",o[2]);mn(o,"...")&&(i=!0,e.advance());const t=Jn(e),l=Vn(t);if(o=e.peek(),pn(o,"as")){if(i)throw new n("Rest argument can not have alias",o[2]);e.advance();const t=Lt(Jn(e));if(r[t[1]])throw new n(`Duplicate binding name: ${t}`,o[2]);r[l]=Rn([Ke,[t,Xn(e)]],s[2])}else if(In(o)||mn(o,",")||mn(o,"=")){const a=Lt(t,t[2]);if(r[a[1]])throw new n(`Duplicate binding name: ${a}`,o[2]);if(i&&mn(e.tryPeek(),"="))throw new n("Rest argument can not have default value",e.peekSourceCodeInfo());r[a[1]]=Rn(i?[Ge,[a[1],Xn(e)]]:[Ke,[a,Xn(e)]],s[2])}else if(mn(o,":")){if(e.advance(),o=e.peek(),a){if(!$n(o)&&!kn(o)&&!Hn(o))throw new n("Expected literal, object or array pattern",o[2])}else if(!$n(o)&&!kn(o))throw new n("Expected object or array",o[2]);r[l]=Gn(e,{allowLiteralPatterns:a})}In(e.peek())||(yn(e.peek(),","),e.advance()),o=e.peek()}e.advance(),o=e.peek();const l=Xn(e);if(t&&!l)throw new n("Expected assignment",o[2]);return Rn([Xe,[r,l]],s[2])}throw new n("Expected symbol",e.peekSourceCodeInfo())}function Xn(e){if(mn(e.tryPeek(),"="))return e.advance(),e.parseExpression()}function Hn(e){return gn(e)||hn(e)||jn(e)||pn(e,"true")||pn(e,"false")||pn(e,"null")}function Zn(e,t){e.advance();const n=Gn(e,{requireDefaultValue:!0,noRest:!0}),r=n[1][1];n[1][1]=void 0;const a=Rn([o.Binding,[n,r]],t[2]);return Rn([o.SpecialExpression,[Ut.let,a]],t[2])}function Qn(e){const t=function(e){const t=un(e.tryPeek()),n=Lt(Jn(e));fn(e.tryPeek(),"in"),e.advance();const r=e.parseExpression();return Rn([o.Binding,[Rn([Ke,[n,void 0]],t[2]),r]],t[2])}(e),r=[];let a=e.peek();er(a,["let","when","while"]);const s=[];if("let"===a[1])for(r.push("&let");cn(a,"let");){const t=Zn(e,a),r=s.flatMap(e=>Object.keys(ct(e[1][0])));if(Object.keys(ct(t[1][1][1][0])).some(e=>r.includes(e)))throw new n("Duplicate binding",t[1][1][2]);s.push(t[1][1]),a=e.peek(),er(a,["let","when","while"]),a=e.peek()}let i,l;for(;pn(a,"when")||pn(a,"while");){e.advance(),"when"===a[1]?(r.push("&when"),i=e.parseExpression()):(r.push("&while"),l=e.parseExpression()),a=e.peek();er(a,r.includes("&when")&&r.includes("&while")?[]:r.includes("&when")?["while"]:["when"]),a=e.peek()}return er(a,[]),[t,s,i,l]}function er(e,t){if(!function(e,t){if(mn(e,",")||xn(e))return!0;for(const n of t){if("let"===n&&cn(e,"let"))return!0;if(["when","while"].includes(n)&&pn(e,n))return!0}return!1}(e,t)){const r=`${[...t,","].map(e=>`"${e}"`).join(", ")} or ")"`;throw new n(`Expected symbol ${r}`,e[2])}}const tr=(1+Math.sqrt(5))/2,nr={E:Math.E,"-E":-Math.E,"ε":Math.E,"-ε":-Math.E,PI:Math.PI,"-PI":-Math.PI,"π":Math.PI,"-π":-Math.PI,PHI:tr,"-PHI":-tr,"φ":tr,"-φ":-tr,POSITIVE_INFINITY:Number.POSITIVE_INFINITY,"∞":Number.POSITIVE_INFINITY,NEGATIVE_INFINITY:Number.NEGATIVE_INFINITY,"-∞":Number.NEGATIVE_INFINITY,MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,MAX_VALUE:Number.MAX_VALUE,MIN_VALUE:Number.MIN_VALUE,NaN:Number.NaN},rr={true:!0,false:!1,null:null,do:null,else:null,case:null,each:null,in:null,when:null,while:null,function:null,as:null,then:null,end:null,with:null,_:null,...nr};function ar(e){const t=dn(e.tryPeek());e.advance();const n=t[1];return function(e){return e in nr}(n)?Rn([o.Number,nr[n]],t[2]):Rn([o.ReservedSymbol,t[1]],t[2])}const sr=/^\$([1-9]\d?)?$/;function or(e){const t=e.peek();if(vn(t)&&cn(e.peekAhead(1))&&mn(e.peekAhead(2),"->"))return null;try{const r=function(e){const t=e.peek();if(cn(t))return[Rn([Ke,[Jn(e),void 0]],t[2])];bn(t),e.advance();let r=!1,a=!1;const s=[];for(;!e.isAtEnd()&&!xn(e.peek())&&!cn(e.peek(),"let");){if(r)throw new n("Rest argument must be last",e.peekSourceCodeInfo());const t=Gn(e);if(void 0!==t[1][1]&&(a=!0),t[0]===Ge&&(r=!0),a&&!t[1][1])throw new n("Default arguments must be last",e.peekSourceCodeInfo());if(s.push(t),!mn(e.peek(),",")&&!xn(e.peek())&&!cn(e.peek(),"let"))throw new n("Expected comma or closing parenthesis",e.peekSourceCodeInfo());mn(e.peek(),",")&&e.advance()}if(!xn(e.peek()))throw new n("Expected closing parenthesis",e.peekSourceCodeInfo());return e.advance(),s}(e);if(!mn(e.peek(),"->"))return null;let a;if(e.advance(),pn(e.peek(),"do")){const t=Wn(e),n=t[1][2];a=n&&n.length>0?[t]:t[1][1]}else a=[e.parseExpression()];return Rn([o.SpecialExpression,[Ut["0_lambda"],[r,a]]],t[2])}catch{return null}}function ir(e,t){if(e.advance(),Wt(t)&&t[1]===Ut.effect)return function(e,t){const r=t[2],a=e.peek();if(!cn(a))throw new n("effect expects a dotted name identifier",a[2]);let s=a[1];e.advance();for(;mn(e.tryPeek(),".");){e.advance();const t=e.peek();if(!cn(t))throw new n("Expected identifier after dot in effect name",t[2]);s+=`.${t[1]}`,e.advance()}if(!xn(e.tryPeek()))throw new n("Expected closing parenthesis after effect name",e.peekSourceCodeInfo());return e.advance(),Rn([o.SpecialExpression,[Ut.effect,s]],r)}(e,t);const r=[];for(;!e.isAtEnd()&&!xn(e.tryPeek());){mn(e.tryPeek(),"...")?(e.advance(),r.push(Rn([o.Spread,e.parseExpression()],e.peekSourceCodeInfo()))):r.push(e.parseExpression());const t=e.tryPeek();if(!mn(t,",")&&!xn(t))throw new n("Expected comma or closing parenthesis",e.tryPeek()?.[2]);mn(t,",")&&e.advance()}if(!xn(e.tryPeek()))throw new n("Expected closing parenthesis",e.peekSourceCodeInfo());if(e.advance(),!Wt(t))return zt(t)||Ft(t)?Un(t,r,t[2]):Rn([o.NormalExpression,[t,r]],t[2]);{const e=t[1];if(e===Ut.import){if(1!==r.length)throw new n(`import expects exactly 1 argument, got ${r.length}`,t[2]);const a=r[0];if(!Ft(a))throw new n("import expects a module name (symbol), got a non-symbol argument",a[2]??t[2]);const s=a[1];return Rn([o.SpecialExpression,[e,s]],t[2])}const a=e;switch(K(Bt.specialExpressions[a].arity,r.length,t[2]),a){case Ut["||"]:case Ut["&&"]:case Ut.recur:case Ut.array:case Ut.object:case Ut["??"]:return Rn([o.SpecialExpression,[a,r]],t[2]);case Ut["defined?"]:{const[e]=r;return Rn([o.SpecialExpression,[a,e]],t[2])}case Ut.perform:{const[e,...n]=r;return Rn([o.SpecialExpression,[a,e,n]],t[2])}case Ut.parallel:case Ut.race:return Rn([o.SpecialExpression,[a,r]],t[2]);case Ut["0_lambda"]:throw new n(`${a} is not allowed`,t[2]);default:throw new n(`Unknown special expression: ${a}`,t[2])}}}function lr(e){const t=Sn(e.tryPeek());e.advance();const r=[];for(;!e.isAtEnd()&&!In(e.tryPeek());){if(mn(e.tryPeek(),"..."))e.advance(),r.push(Rn([o.Spread,e.parseExpression()],e.peekSourceCodeInfo()));else{const t=e.tryPeek();if(jn(t)){const n=Yn(e,t);r.push(Rn([o.String,n[1]],t[2]))}else if(cn(t)){const n=t[1].startsWith("'")?Tn(t[1]):t[1];r.push(Rn([o.String,n],t[2])),e.advance()}else{if(!kn(t))throw new n("Expected key to be a symbol or a string",e.peekSourceCodeInfo());e.advance(),r.push(e.parseExpression()),Nn(e.tryPeek()),e.advance()}yn(e.tryPeek(),":"),e.advance(),r.push(e.parseExpression())}const t=e.tryPeek();if(!mn(t,",")&&!In(t))throw new n("Expected comma or closing brace",e.peekSourceCodeInfo());mn(t,",")&&e.advance()}var a;return In(a=e.tryPeek())||Cn("RBrace",void 0,a),e.advance(),Rn([o.SpecialExpression,[Ut.object,r]],t[2])}function cr(e){let t=function(e){const t=e.peek();if(vn(t)){e.storePosition();const t=or(e);if(t)return t;e.restorePosition(),e.advance();const r=e.parseExpression();if(!xn(e.peek()))throw new n("Expected closing parenthesis",e.peekSourceCodeInfo());return e.advance(),r}if(mn(t)){const r=t[1];if(sn(r))return e.advance(),Rn(void 0!==Ut[r]?[o.SpecialBuiltinSymbol,Ut[r]]:[o.NormalBuiltinSymbol,ze[r]],t[2]);if("->"===r)return function(e){const t=e.peek();e.advance();const r=e.getPosition();let a;if(pn(e.peek(),"do")){const t=Wn(e),n=t[1][2];a=n&&n.length>0?[t]:t[1][1]}else a=[e.parseExpression()];const s=e.getPosition()-1;let i=0,l="NOT_SET";for(let a=r;a<=s;a+=1){const r=e.getTokenAt(a);if(cn(r)){const e=sr.exec(r[1]);if(e){const r=e[1]??"1";if("1"===r){if(!e[1]&&"WITH_1"===l||e[1]&&"NAKED"===l)throw new n("Please make up your mind, either use $ or $1",t[2]);l=e[1]?"WITH_1":"NAKED"}if(i=Math.max(i,Number(r)),i>20)throw new n("Can't specify more than 20 arguments",t[2])}}}const c=[];for(let e=1;e<=i;e+=1)1===e&&"NAKED"===l?c.push(Rn([Ke,[[o.UserDefinedSymbol,"$"],void 0]],t[2])):c.push(Rn([Ke,[[o.UserDefinedSymbol,`$${e}`],void 0]],t[2]));return Rn([o.SpecialExpression,[Ut["0_lambda"],[c,a]]],t[2])}(e);throw new n(`Illegal operator: ${r}`,t[2])}if($n(t))return lr(e);if(kn(t))return function(e){const t=An(e.tryPeek());e.advance();const r=[];for(;!e.isAtEnd()&&!En(e.tryPeek());){mn(e.tryPeek(),"...")?(e.advance(),r.push(Rn([o.Spread,e.parseExpression()],e.peekSourceCodeInfo()))):r.push(e.parseExpression());const t=e.tryPeek();if(!mn(t,",")&&!En(t))throw new n("Expected comma or closing parenthesis",e.peekSourceCodeInfo());mn(t,",")&&e.advance()}return Nn(e.tryPeek()),e.advance(),Rn([o.SpecialExpression,[Ut.array,r]],t[2])}(e);const r=t[0];switch(r){case"Number":case"BasePrefixedNumber":return Kn(e);case"string":return Yn(e,t);case"Symbol":{e.storePosition();const t=or(e);return t||(e.restorePosition(),Jn(e))}case"ReservedSymbol":return ar(e);case"RegexpShorthand":return function(e){const t=e.peek();e.advance();const n=t[1].lastIndexOf('"'),r=t[1].substring(2,n),a=t[1].substring(n+1),s=Rn([o.String,r],t[2]),i=Rn([o.String,a],t[2]);return Rn([o.NormalExpression,[Rn([o.NormalBuiltinSymbol,ze.regexp],t[2]),[s,i]]],t[2])}(e);default:throw new n(`Unknown token type: ${r}`,t[2])}}(e),r=e.tryPeek();for(;mn(r,".")||kn(r)||vn(r);)if("."===r[1]){e.advance();const a=e.tryPeek();if(!cn(a))throw new n("Expected symbol",e.peekSourceCodeInfo());t=ur(t,Rn([o.String,a[1]],a[2]),r[2]),e.advance(),r=e.tryPeek()}else if(kn(r)){e.advance();const a=e.parseExpression();if(!En(e.tryPeek()))throw new n("Expected closing bracket",e.peekSourceCodeInfo());t=ur(t,a,r[2]),e.advance(),r=e.tryPeek()}else vn(r)&&(t=ir(e,t),r=e.tryPeek());return t}function ur(e,t,n){return Rn([o.NormalExpression,[[o.NormalBuiltinSymbol,ze.get],[e,t]]],n)}function pr(e,t=0){const r=e.tryPeek();let a;if(cn(r))switch(r[1]){case"let":return Zn(e,r);case"if":case"unless":a=function(e,t){const n="unless"===t[1];e.advance();const r=e.parseExpression();fn(e.tryPeek(),"then"),e.advance();const a=Ln(e,["else","end"]);let s;return pn(e.tryPeek(),"else")&&(e.advance(),s=Ln(e,["end"])),e.advance(),Rn(n?[o.SpecialExpression,[Ut.unless,[r,a,s]]]:[o.SpecialExpression,[Ut.if,[r,a,s]]],t[2])}(e,r);break;case"cond":a=function(e,t){e.advance();const n=[];for(;!e.isAtEnd()&&!pn(e.tryPeek(),"end");){fn(e.tryPeek(),"case"),e.advance();const t=e.parseExpression();fn(e.tryPeek(),"then"),e.advance();const r=Ln(e,["case","end"]);if(n.push([t,r]),pn(e.tryPeek(),"end"))break}return fn(e.tryPeek()),e.advance(),Rn([o.SpecialExpression,[Ut.cond,n]],t[2])}(e,r);break;case"match":a=function(e,t){e.advance();const n=e.parseExpression(),r=[];for(;!e.isAtEnd()&&!pn(e.tryPeek(),"end");){fn(e.tryPeek(),"case"),e.advance();const t=Gn(e,{allowLiteralPatterns:!0});let n;pn(e.tryPeek(),"when")&&(e.advance(),n=e.parseExpression()),fn(e.tryPeek(),"then"),e.advance();const a=Ln(e,["case","end"]);if(r.push([t,a,n]),pn(e.tryPeek(),"end"))break}return fn(e.tryPeek(),"end"),e.advance(),Rn([o.SpecialExpression,[Ut.match,n,r]],t[2])}(e,r);break;case"for":case"doseq":a=function(e,t){const r="doseq"===t[1];e.advance(),bn(e.tryPeek()),e.advance();const a=[];for(;!e.isAtEnd()&&!xn(e.tryPeek());){const t=Qn(e),r=a.flatMap(e=>Object.keys(ct(e[0][1][0]))),s=ct(t[0][1][0]);if(Object.keys(s).some(e=>r.includes(e)))throw new n("Duplicate binding",t[0][2]);a.push(t),mn(e.tryPeek(),",")&&e.advance()}wn(e.tryPeek()),e.advance(),yn(e.tryPeek(),"->"),e.advance();const s=e.parseExpression();return Rn(r?[o.SpecialExpression,[Ut.doseq,a,s]]:[o.SpecialExpression,[Ut.for,a,s]],t[2])}(e,r);break;case"loop":a=function(e,t){e.advance(),bn(e.tryPeek()),e.advance();const r=[];let a=e.tryPeek();for(;!e.isAtEnd()&&!xn(a);){const t=Gn(e,{requireDefaultValue:!0,noRest:!0}),n=t[1][1];t[1][1]=void 0,r.push(Rn([o.Binding,[t,n]],t[2])),mn(e.tryPeek(),",")&&e.advance(),a=e.tryPeek()}if(0===r.length)throw new n("Expected binding",e.peekSourceCodeInfo());wn(a),e.advance(),yn(e.tryPeek(),"->"),e.advance();const s=e.parseExpression();return Rn([o.SpecialExpression,[Ut.loop,r,s]],t[2])}(e,r)}else pn(r,"do")&&(a=Wn(e));a||=cr(e);let s=e.tryPeek();for(;!Bn(e);){if(qn(s)){const n=s[1],r=Fn(n,s[2]);if(r<=t&&(12!==r||12!==t))break;const i=Rn(Ut[n]?[o.SpecialBuiltinSymbol,Ut[n]]:[o.NormalBuiltinSymbol,ze[n]],s[2]);e.advance();a=Dn(s,i,a,pr(e,r),s[2])}else if(cn(s)){if(!rn(s[1]))break;const r=3;if(r<=t)break;const o=Jn(e),i=pr(e,r);if(Wt(o))throw new n("Special expressions are not allowed in binary functional operators",o[2]);a=Un(o,[a,i],s[2])}else{if("?"!==s?.[1])break;{if(1<=t)break;e.advance();const r=pr(e);if(!mn(e.tryPeek(),":"))throw new n("Expected :",e.peekSourceCodeInfo());e.advance();const s=pr(e);a=Rn([o.SpecialExpression,[Ut.if,[a,r,s]]],a[2])}}s=e.tryPeek()}return a}function fr(e){e.tokens.forEach(e=>{if("Error"===e[0])throw new n(e[3],e[2])});const t=[],r=function(e){const t=new _n(e);return t.parseExpression=(e=0)=>pr(t,e),t}(e);for(;!r.isAtEnd();)if(t.push(pr(r,0)),mn(r.tryPeek(),";"))r.advance();else if(!r.isAtEnd())throw new n("Expected ;",r.peekSourceCodeInfo());return t}function dr(e,{removeWhiteSpace:t}){const n=e.tokens.filter(e=>!(function(e){return"SingleLineComment"===e?.[0]}(e)||function(e){return"MultiLineComment"===e?.[0]}(e)||function(e){return"Shebang"===e?.[0]}(e)||t&&function(e){return"Whitespace"===e?.[0]}(e)));return{...e,tokens:n}}const mr=["(",")","[","]","{","}","'",'"',"`",",",".",";"," ","\n","\r","\t"],yr=["0","1","2","3","4","5","6","7","8","9",...mr],gr=new Set(mr),hr=new Set(yr),vr=/\s/,br=[0],xr=(e,t)=>{if('"'!==e[t])return br;let n='"',r=1,a=e[t+r],s=!1;for(;a&&('"'!==a||s);)r+=1,s?(s=!1,n+=a):("\\"===a&&(s=!0),n+=a),a=e[t+r];return a?(n+='"',[r+1,["string",n]]):[r,["Error",n,void 0,`Unclosed string at position ${t}`]]};function wr(e,t,n,r){return t===n.slice(r,r+t.length)?[t.length,[e,t]]:br}const kr=/\d/,Ar=/[0-7]/,Er=/[0-9a-f]/i,Nr=/[01]/,$r=/[\s)\]}(,;]/,Sr=(e,t)=>{let n=e[t];if("'"===n){let r=1,a=e[t+r],s=!1;for(;"'"!==a||s;){if(void 0===a)return[r,["Error",n,void 0,`Unclosed quoted symbol at position ${t}`]];r+=1,s?(s=!1,n+=a):("\\"===a&&(s=!0),n+=a),a=e[t+r]}return n+="'",[r+1,["Symbol",n]]}if(!hr.has(n)){const r=t;let a=e[t+=1];for(;a&&!gr.has(a);)n+=a,a=e[t+=1];return n.endsWith(":")?[t-r-1,["Symbol",n.slice(0,-1)]]:[t-r,["Symbol",n]]}return br},Ir=[(e,t)=>{let n=e[t];if(!n||!vr.test(n))return br;let r=n;for(n=e[t+=1];n&&vr.test(n);)r+=n,n=e[t+=1];return[r.length,["Whitespace",r]]},(e,t)=>{if("/"===e[t]&&"*"===e[t+1]){let n=2,r="/*";for(;("*"!==e[t+n]||"/"!==e[t+n+1])&&t+n+1<e.length;)r+=e[t+n],n+=1;return t+n+1>=e.length?[n,["Error",r,void 0,`Unclosed multi-line comment at position ${t}`]]:(r+="*/",n+=2,[n,["MultiLineComment",r]])}return br},(e,t)=>{if("/"===e[t]&&"/"===e[t+1]){let n=2,r="//";for(;"\n"!==e[t+n]&&t+n<e.length;)r+=e[t+n],n+=1;return[n,["SingleLineComment",r]]}return br},(e,t)=>{const n=Sr(e,t);if(0===n[0]||!n[1])return br;let r=n[1][1];r=r.startsWith("'")?r.slice(1,r.length-1):r;return void 0===rr[r]?br:[n[0],["ReservedSymbol",r]]},(e,t)=>wr("LParen","(",e,t),(e,t)=>wr("RParen",")",e,t),(e,t)=>wr("LBracket","[",e,t),(e,t)=>wr("RBracket","]",e,t),(e,t)=>wr("LBrace","{",e,t),(e,t)=>wr("RBrace","}",e,t),xr,(e,t)=>{if("#"!==e[t])return br;const[n,r]=xr(e,t+1);if(!r)return br;if("Error"===r[0]){return[n+1,["Error",`#${r[1]}`,void 0,`Unclosed regexp at position ${t}`]]}t+=n+1;let a=n+1,s="";for(;"g"===e[t]||"i"===e[t];)if(s+=e[t],a+=1,t+=1,s.includes(e[t]))return[a,["Error",`#${r[1]}${s}`,void 0,`Duplicated regexp option "${e[t]}"`]];return[a,["RegexpShorthand",`#${r[1]}${s}`]]},(e,t)=>{if("0"!==e[t])return br;const n=e[t+1],r="b"===n||"B"===n?"binary":"o"===n||"O"===n?"octal":"x"===n||"X"===n?"hex":null;if(null===r)return br;let a;for(a=t+2;a<e.length;a+=1){const t=e[a];if("binary"===r&&!Nr.test(t))break;if("octal"===r&&!Ar.test(t))break;if("hex"===r&&!Er.test(t))break}const s=a-t;if(s<=2)return br;const o=e[a];return o&&!$r.test(o)?br:[s,["BasePrefixedNumber",e.substring(t,a)]]},(e,t)=>{let n;const r="-"===e[t],a="+"===e[t],s=r||a?t+1:t;let o=!1,i=!1;for(n=s;n<e.length;n+=1){const r=e[n];if("_"===r){if(!kr.test(e[n-1])||!kr.test(e[n+1]))return n===s?br:[n-t+1,["Error",e.substring(t,n+1),void 0,`Invalid number format at position ${n+1}`]]}else if("."===r){if(n===s)return br;if(o||i)return[n-t+1,["Error",e.substring(t,n+1),void 0,`Invalid number format at position ${n+1}`]];o=!0}else if("e"===r||"E"===r){if(n===s)return br;if(i)return[n-t+1,["Error",e.substring(t,n+1),void 0,`Invalid number format at position ${n+1}`]];if("."===e[n-1]||"+"===e[n-1]||"-"===e[n-1])return[n-t+1,["Error",e.substring(t,n+1),void 0,`Invalid number format at position ${n+1}`]];"+"!==e[n+1]&&"-"!==e[n+1]||(n+=1),i=!0}else if(!kr.test(r))break}if((r||a)&&n===s)return br;const l=n-t;if(0===l)return br;const c=e[n];return c&&":"!==c&&!$r.test(c)?[n-t+1,["Error",e.substring(t,n+1),void 0,`Invalid number format at position ${n+1}`]]:[l,["Number",e.substring(t,n)]]},(e,t)=>{const n=e.slice(t,t+3);if(t+2<e.length&&ln(n))return[3,["Operator",n]];const r=e.slice(t,t+2);if(t+1<e.length&&ln(r))return[2,["Operator",r]];const a=e[t]??"";return ln(a)?[1,["Operator",a]]:br},Sr];function jr(e,t,n){let r=0;const a={tokens:[],filePath:n,hasDebugData:t};for(;r<e.length;){const s=t?qr(e,r,n):void 0,o=Cr(e,r),[i,l]=o;r+=i,l&&(s&&(l[2]=s),a.tokens.push(l))}return a}function qr(e,t,n){const r=e.substring(0,t+1).split(/\r\n|\r|\n/),a=r[r.length-1],s=function(e,t){return e.split(/\r\n|\r|\n/)[t]}(e,r.length-1);return{code:s,position:{line:r.length,column:a.length},filePath:n}}function Cr(e,t){const n=t;if(0===t){const[r,a]=((e,t)=>{if("#"===e[t]&&"!"===e[t+1]){let n=2,r="#!";for(;"\n"!==e[t+n]&&t+n<e.length;)r+=e[t+n],n+=1;return[n,["SingleLineComment",r]]}return br})(e,t);if(t+=r,r>0)return[t-n,a]}for(const r of Ir){const[a,s]=r(e,t);if(t+=a,0!==a)return[t-n,s]}return[1,["Error",e[n],void 0,"Unrecognized character"]]}function Rr(e,t){if("*"===t)return!0;if(t.endsWith(".*")){const n=t.slice(0,-2);return e===n||e.startsWith(`${n}.`)}return e===t}function Pr(e,t){if(!t)return[];const n=[];for(const[r,a]of Object.entries(t))Rr(e,r)&&n.push([r,a]);return n}class Tr{k;snapshots;nextSnapshotIndex;meta;_brand="SuspensionSignal";constructor(e,t,n,r){this.k=e,this.snapshots=t,this.nextSnapshotIndex=n,this.meta=r}}function Or(e){return e instanceof Tr}class Mr{continuation;value;trimToIndex;_brand="ResumeFromSignal";constructor(e,t,n){this.continuation=e,this.value=t,this.trimToIndex=n}}function Vr(e){return e instanceof Mr}const Ur=new Map;function Br(e){let t=Ur.get(e);return t||(t={[f]:!0,name:e},Ur.set(e,t)),t}function Dr(e,t){return Math.imul(e^255&t,16777619)}function _r(e,t){return e=Dr(e,t),e=Dr(e,t>>>8),e=Dr(e,t>>>16),e=Dr(e,t>>>24)}function Fr(e,t){for(let n=0;n<t.length;n++){const r=t.charCodeAt(n);e=Dr(e,r),e=Dr(e,r>>>8)}return e}function Lr(e){let t=2166136261;if(null===e)return t=Dr(t,0),t>>>0;if(void 0===e)return t=Dr(t,7),t>>>0;const n=typeof e;if("boolean"===n)return t=Dr(t,e?1:2),t>>>0;if("number"===n)return t=Dr(t,3),t=Fr(t,Object.is(e,-0)?"-0":String(e)),t>>>0;if("string"===n)return t=Dr(t,4),t=Fr(t,e),t>>>0;if(Array.isArray(e)){t=Dr(t,5),t=_r(t,e.length);for(let n=0;n<e.length;n++)t=_r(t,Lr(e[n]));return t>>>0}t=Dr(t,6);const r=Object.keys(e).sort();t=_r(t,r.length);for(const n of r)t=Fr(t,n),t=_r(t,Lr(e[n]));return t>>>0}function zr(e,t){if(e===t)return!0;if(null===e||null===t)return!1;if(typeof e!=typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!zr(e[n],t[n]))return!1;return!0}if("object"!=typeof e)return!1;const n=e,r=t,a=Object.keys(n),s=Object.keys(r);if(a.length!==s.length)return!1;for(const e of a){if(!(e in r))return!1;if(!zr(n[e],r[e]))return!1}return!0}function Wr(e){if(null===e)return 4;if(void 0===e)return 9;const t=typeof e;if("boolean"===t)return e?4:5;if("number"===t)return String(e).length;if("string"===t)return e.length+2;if(Array.isArray(e)){let t=2;for(let n=0;n<e.length;n++)t+=Wr(e[n])+1;return t}const n=e,r=Object.keys(n);let a=2;for(const e of r)a+=e.length+2+1+Wr(n[e])+1;return a}function Jr(e,t,n,r){if(null===e||"object"!=typeof e)return Lr(e);if(Array.isArray(e))for(let n=0;n<e.length;n++)Jr(e[n],t,{parent:e,key:n});else{const n=e;for(const e of Object.keys(n))Jr(n[e],t,{parent:n,key:e})}const a=Lr(e),s=Wr(e);if(n&&s>=1){let r,o=t.get(a);o||(o=[],t.set(a,o));for(const t of o)if(zr(t.value,e)){r=t;break}r?r.locations.push(n):o.push({hash:a,value:Kr(e),size:s,locations:[n]})}return a}function Yr(e,t){if(null===e||"object"!=typeof e)return e;if(function(e){return null!==e&&"object"==typeof e&&"__poolRef"in e&&"number"==typeof e.__poolRef&&1===Object.keys(e).length}(e)){const n=e.__poolRef;if(!(n in t))throw new Error(`Unknown pool ref: ${n}`);return Yr(t[n],t)}if(Array.isArray(e))return e.map(e=>Yr(e,t));const n=e,r={};for(const e of Object.keys(n))r[e]=Yr(n[e],t);return r}function Kr(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>Kr(e));const t=e,n={};for(const e of Object.keys(t))n[e]=Kr(t[e]);return n}function Gr(e,t){const n=new Map;let r=0;function a(e){if(e instanceof Kt){if(n.has(e))return;n.set(e,r++);for(const t of e.getContextsRaw())for(const e of Object.values(t))a(e.value)}else if(Array.isArray(e))for(const t of e)a(t);else if(null!==e&&"object"==typeof e)for(const t of Object.values(e))a(t)}function s(e,t){if(e instanceof Kt)return{__csRef:n.get(e)};if(Array.isArray(e))return e.map((e,t)=>s(e));if(null!==e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=s(r);return t}return e}a(e),void 0!==t&&a(t);const o=Array.from(n.entries()).map(([e,t])=>({id:t,contexts:e.getContextsRaw().map((e,t)=>{const n={};for(const[t,r]of Object.entries(e))n[t]={value:s(r.value)};return n}),globalContextIndex:e.getGlobalContextIndex(),pure:e.pure})),i=s(e),l=void 0!==t?s(t):void 0;return{version:2,contextStacks:o,k:i,...void 0!==l?{meta:l}:{}}}function Xr(e,t,n,r){const a=Gr(e,r);t.length>0&&(a.snapshots=t),a.nextSnapshotIndex=n;const s=[a.contextStacks,a.k];if(void 0!==a.meta&&s.push(a.meta),a.snapshots)for(const e of a.snapshots)s.push(e);const{roots:o,pool:i}=function(e,t=200){const n=e.map(e=>Kr(e)),r=new Map;for(let e=0;e<n.length;e++)Jr(n[e],r,null);const a={};let s=0;const o=Array.from(r.values()).flat().filter(e=>e.locations.length>1&&e.size>=t).sort((e,t)=>t.size-e.size),i=new Map;for(const e of o){if(i.has(e))continue;const t=s++;a[t]=e.value,i.set(e,t);for(const n of e.locations)Array.isArray(n.parent),n.parent[n.key]={__poolRef:t}}return{roots:n,pool:a}}(s,200);let l=0;if(a.contextStacks=o[l++],a.k=o[l++],void 0!==a.meta&&(a.meta=o[l++]),a.snapshots)for(let e=0;e<a.snapshots.length;e++)a.snapshots[e]=o[l++];return Object.keys(i).length>0&&(a.pool=i),a}function Hr(e,t){let r=e;if(2!==r.version)throw new n(`Unsupported suspension blob version: ${r.version} (expected 2)`,void 0);if(r.pool&&Object.keys(r.pool).length>0){const e=r.pool;r={...r,contextStacks:Yr(r.contextStacks,e),k:Yr(r.k,e),...void 0!==r.meta?{meta:Yr(r.meta,e)}:{},...r.snapshots?{snapshots:r.snapshots.map(t=>Yr(t,e))}:{}},delete r.pool}const a=new Map;for(const e of r.contextStacks){const n=e.contexts.map(()=>({})),r=Kt.fromDeserialized({contexts:n,globalContextIndex:e.globalContextIndex,values:t?.values,modules:t?.modules,pure:e.pure});a.set(e.id,r)}function s(e){if(function(e){return null!==e&&"object"==typeof e&&"__csRef"in e&&"number"==typeof e.__csRef}(e)){const t=a.get(e.__csRef);if(!t)throw new n(`Invalid suspension blob: unknown context stack ref ${e.__csRef}`,void 0);return t}if(Array.isArray(e))return e.map(s);if(null!==e&&"object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=s(r);return t}return e}for(const e of r.contextStacks){const t=a.get(e.id),n=e.contexts.map(e=>{const t=e,n={};for(const[e,r]of Object.entries(t))n[e]={value:s(r.value)};return n});t.setContextsFromDeserialized(n,e.globalContextIndex)}return{k:s(r.k),meta:void 0!==r.meta?s(r.meta):void 0,snapshots:r.snapshots??[],nextSnapshotIndex:r.nextSnapshotIndex??0}}function Zr(){return"undefined"!=typeof process&&"function"==typeof process.stdout?.write}function Qr(e){return"string"==typeof e?e:null===e?"null":"number"==typeof e||"boolean"==typeof e?String(e):w(e)?"Builtin"===e.functionType?`<builtin function ${e.normalBuiltinSymbolType}>`:`<function ${e.n??"λ"}>`:T(e)?`<effect ${e.name}>`:R(e)?`/${e.s}/${e.f}`:"object"==typeof e&&e instanceof RegExp?`${e}`:JSON.stringify(ea(e),null,2)}function ea(e){if(e===Number.POSITIVE_INFINITY)return"∞";if(e===Number.NEGATIVE_INFINITY)return"-∞";if(w(e))return Qr(e);if(T(e))return Qr(e);if(R(e))return Qr(e);if(Array.isArray(e))return e.map(ea);if("object"==typeof e&&null!==e){const t={};for(const[n,r]of Object.entries(e))t[n]=ea(r);return t}return e}const ta={"dvala.io.print":{handler:function(e,t){const n=e[0],r=Qr(n);return Zr()?process.stdout.write(r):console.log(r),{type:"Value",value:n,k:t}},arity:G(1),docs:{category:"effect",description:"Writes a value to stdout without a trailing newline. Accepts any value — strings are printed as-is, other values are auto-formatted. In Node.js uses `process.stdout.write(str)`, in browsers uses `console.log(str)`. Resumes with the original value (identity).",returns:{type:"any"},args:{value:{type:"any",description:"Value to print."}},variants:[{argumentNames:["value"]}],examples:['perform(effect(dvala.io.print), "hello")',"perform(effect(dvala.io.print), 42)"],seeAlso:["-effect-dvala.io.println","-effect-dvala.io.error","-effect-dvala.io.read-line","perform","effect"]}},"dvala.io.println":{handler:function(e,t){const n=e[0],r=Qr(n);return Zr()?process.stdout.write(`${r}\n`):"function"==typeof globalThis.alert?globalThis.alert(r):console.log(r),{type:"Value",value:n,k:t}},arity:G(1),docs:{category:"effect",description:'Writes a value to stdout followed by a newline. Accepts any value — strings are printed as-is, other values are auto-formatted. In Node.js uses `process.stdout.write(str + "\\n")`, in browsers uses `alert(str)`. Resumes with the original value (identity).',returns:{type:"any"},args:{value:{type:"any",description:"Value to print."}},variants:[{argumentNames:["value"]}],examples:['perform(effect(dvala.io.println), "hello")',"perform(effect(dvala.io.println), [1, 2, 3])"],seeAlso:["-effect-dvala.io.print","-effect-dvala.io.error","-effect-dvala.io.read-line","perform","effect"]}},"dvala.io.error":{handler:(e,t)=>{const n=e[0],r=Qr(n);return Zr()?process.stderr.write(`${r}\n`):console.error(r),{type:"Value",value:n,k:t}},arity:G(1),docs:{category:"effect",description:'Writes a value to stderr followed by a newline. Accepts any value — strings are printed as-is, other values are auto-formatted. In Node.js uses `process.stderr.write(str + "\\n")`, in browsers uses `console.error(str)`. Resumes with the original value (identity).',returns:{type:"any"},args:{value:{type:"any",description:"Value to write to stderr."}},variants:[{argumentNames:["value"]}],examples:['perform(effect(dvala.io.error), "something went wrong")'],seeAlso:["-effect-dvala.io.print","-effect-dvala.io.println","perform","effect"]}},"dvala.io.read-line":{handler:(e,t,r)=>{const a="string"==typeof e[0]?e[0]:"";if("function"==typeof globalThis.prompt){return{type:"Value",value:globalThis.prompt(a)??null,k:t}}throw new n('dvala.io.read-line is not supported in this environment. In Node.js, register a "dvala.io.read-line" host handler.',r)},arity:{min:0,max:1},docs:{category:"effect",description:"Reads one line of user input. In browsers uses `window.prompt()`. In Node.js uses `readline`. Resumes with the user's input string, or `null` on cancel.",returns:{type:["string","null"]},args:{message:{type:"string",description:"Optional prompt message to display."}},variants:[{argumentNames:[]},{argumentNames:["message"]}],examples:["effect(dvala.io.read-line)"],seeAlso:["-effect-dvala.io.read-stdin","-effect-dvala.io.print","-effect-dvala.io.println","perform","effect"]}},"dvala.io.read-stdin":{handler:(e,t,r)=>{if(!Zr()||!process.stdin)throw new n("dvala.io.read-stdin is not supported in this environment. Node.js is required.",r);return new Promise((e,n)=>{const r=[];process.stdin.setEncoding("utf-8"),process.stdin.on("data",e=>r.push(e)),process.stdin.on("end",()=>e({type:"Value",value:r.join(""),k:t})),process.stdin.on("error",e=>n(e)),process.stdin.resume()})},arity:G(0),docs:{category:"effect",description:"Reads all of stdin until EOF (Node.js only). Resumes with the full stdin content as a string.",returns:{type:"string"},args:{},variants:[{argumentNames:[]}],examples:["effect(dvala.io.read-stdin)"],seeAlso:["-effect-dvala.io.read-line","perform","effect"]}},"dvala.random":{handler:(e,t)=>({type:"Value",value:Math.random(),k:t}),arity:G(0),docs:{category:"effect",description:"Returns a random floating-point number in the range [0, 1). Equivalent to `Math.random()` in JavaScript.",returns:{type:"number"},args:{},variants:[{argumentNames:[]}],examples:["perform(effect(dvala.random))"],seeAlso:["-effect-dvala.random.int","-effect-dvala.random.uuid","-effect-dvala.random.item","-effect-dvala.random.shuffle","perform","effect"]}},"dvala.random.uuid":{handler:(e,t)=>({type:"Value",value:"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),k:t}),arity:G(0),docs:{category:"effect",description:"Generates a UUID v4 string.",returns:{type:"string"},args:{},variants:[{argumentNames:[]}],examples:["perform(effect(dvala.random.uuid))"],seeAlso:["-effect-dvala.random","perform","effect"]}},"dvala.random.int":{handler:(e,t,r)=>{const a=e[0],s=e[1];if("number"!=typeof a||!Number.isInteger(a))throw new n(`dvala.random.int: min must be an integer, got ${"number"==typeof a?a:typeof a}`,r);if("number"!=typeof s||!Number.isInteger(s))throw new n(`dvala.random.int: max must be an integer, got ${"number"==typeof s?s:typeof s}`,r);if(s<=a)throw new n(`dvala.random.int: max (${s}) must be greater than min (${a})`,r);return{type:"Value",value:Math.floor(Math.random()*(s-a))+a,k:t}},arity:G(2),docs:{category:"effect",description:"Returns a random integer in the range [min, max).",returns:{type:"integer"},args:{min:{type:"integer",description:"Minimum value (inclusive)."},max:{type:"integer",description:"Maximum value (exclusive). Must be greater than min."}},variants:[{argumentNames:["min","max"]}],examples:["perform(effect(dvala.random.int), 1, 100)"],seeAlso:["-effect-dvala.random","-effect-dvala.random.item","perform","effect"]}},"dvala.random.item":{handler:(e,t,r)=>{const a=e[0];if(!Array.isArray(a))throw new n("dvala.random.item: argument must be an array, got "+typeof a,r);if(0===a.length)throw new n("dvala.random.item: cannot pick from an empty array",r);return{type:"Value",value:a[Math.floor(Math.random()*a.length)],k:t}},arity:G(1),docs:{category:"effect",description:"Picks a random element from a non-empty array.",returns:{type:"any"},args:{array:{type:"array",description:"Non-empty array to pick from."}},variants:[{argumentNames:["array"]}],examples:['perform(effect(dvala.random.item), ["a", "b", "c"])'],seeAlso:["-effect-dvala.random","-effect-dvala.random.shuffle","-effect-dvala.random.int","perform","effect"]}},"dvala.random.shuffle":{handler:(e,t,r)=>{const a=e[0];if(!Array.isArray(a))throw new n("dvala.random.shuffle: argument must be an array, got "+typeof a,r);const s=Array.from(a);for(let e=s.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1)),n=s[e];s[e]=s[t],s[t]=n}return{type:"Value",value:s,k:t}},arity:G(1),docs:{category:"effect",description:"Returns a new array with the elements of the input array in random order. Uses the Fisher-Yates shuffle algorithm.",returns:{type:"array"},args:{array:{type:"array",description:"Array to shuffle."}},variants:[{argumentNames:["array"]}],examples:["perform(effect(dvala.random.shuffle), [1, 2, 3, 4, 5])"],seeAlso:["-effect-dvala.random","-effect-dvala.random.item","perform","effect"]}},"dvala.time.now":{handler:(e,t)=>({type:"Value",value:Date.now(),k:t}),arity:G(0),docs:{category:"effect",description:"Returns the current timestamp in milliseconds since the Unix epoch. Equivalent to `Date.now()` in JavaScript.",returns:{type:"number"},args:{},variants:[{argumentNames:[]}],examples:["perform(effect(dvala.time.now))"],seeAlso:["-effect-dvala.time.zone","-effect-dvala.sleep","perform","effect"]}},"dvala.time.zone":{handler:(e,t)=>({type:"Value",value:Intl.DateTimeFormat().resolvedOptions().timeZone,k:t}),arity:G(0),docs:{category:"effect",description:'Returns the current IANA timezone string, e.g. `"Europe/Stockholm"` or `"America/New_York"`.',returns:{type:"string"},args:{},variants:[{argumentNames:[]}],examples:["perform(effect(dvala.time.zone))"],seeAlso:["-effect-dvala.time.now","perform","effect"]}},"dvala.checkpoint":{handler:(e,t)=>({type:"Value",value:null,k:t}),arity:{min:0,max:1},docs:{category:"effect",description:"Captures a snapshot of the current program state (continuation stack). The snapshot is stored in an in-memory list accessible via `ctx.snapshots` in host handlers. Optionally accepts a metadata value for domain context (e.g., step labels, timestamps). The standard fallback resumes with `null`, but host handlers can override the resume value. The snapshot is always captured regardless of whether a handler intercepts.",returns:{type:"null"},args:{meta:{type:"any",description:"Optional metadata to attach to the snapshot."}},variants:[{argumentNames:[]},{argumentNames:["meta"]}],examples:["perform(effect(dvala.checkpoint))",'perform(effect(dvala.checkpoint), { step: "analysis-done" })'],seeAlso:["perform","effect"]}},"dvala.sleep":{handler:(e,t,r)=>{const a=e[0];if("number"!=typeof a||a<0)throw new n(`dvala.sleep requires a non-negative number argument, got ${"number"==typeof a?a:typeof a}`,r);return new Promise(e=>{setTimeout(()=>e({type:"Value",value:null,k:t}),a)})},arity:G(1),docs:{category:"effect",description:"Waits for the specified number of milliseconds before resuming. Resumes with `null`. Only works in async execution (`run`) — `runSync` will throw when a Promise surfaces.",returns:{type:"null"},args:{ms:{type:"number",description:"The number of milliseconds to sleep. Must be a non-negative number."}},variants:[{argumentNames:["ms"]}],examples:["effect(dvala.sleep)"],seeAlso:["-effect-dvala.time.now","perform","effect"]}}};function na(e,t){switch(e[0]){case o.Number:case o.String:return e[1];case o.NormalBuiltinSymbol:case o.SpecialBuiltinSymbol:case o.UserDefinedSymbol:return t.evaluateSymbol(e);case o.ReservedSymbol:return ua(e);case o.NormalExpression:{const r=function(e,t){const r=e[2];return et(function(e,t){const r=[],a=[],s=at(e,(e,s)=>Yt(e)?et(na(e[1],t),t=>{if(!Array.isArray(t))throw new n(`Spread operator requires an array, got ${y(e)}`,e[2]);r.push(...t)}):e[0]!==o.ReservedSymbol||"_"!==e[1]?et(na(e,t),e=>{r.push(e)}):void a.push(s));return et(s,()=>({params:r,placeholders:a}))}(e[1][1],t),({params:a,placeholders:o})=>{if(Jt(e)){const i=e[1][0];if(o.length>0){return et(na(i,t),e=>({[u]:!0,function:M(e,r),functionType:"Partial",params:a,placeholders:o,sourceCodeInfo:r,arity:G(o.length)}))}if(zt(i)){const r=i[1],s=Bt.allNormalExpressions[r];if(t.pure&&!1===s.pure)throw new n(`Cannot call impure function '${s.name}' in pure mode`,e[2]);return s.dvalaImpl?sa(s.dvalaImpl,a,t,e[2]):s.evaluate(a,e[2],t,{executeFunction:ra})}{const n=t.getValue(i[1]);if(void 0!==n)return ra(M(n,r),a,t,r);throw new s(i[1],e[2])}}return et(na(e[1][0],t),e=>{const n=M(e,r);if(o.length>0){return{[u]:!0,function:n,functionType:"Partial",params:a,placeholders:o,sourceCodeInfo:r,arity:G(o.length)}}return ra(n,a,t,r)})})}(e,t);return et(r,t=>{if("number"==typeof t&&Number.isNaN(t))throw new n("Number is NaN",e[2]);return be(t)})}case o.SpecialExpression:{const r={type:"Eval",node:e,env:t,k:[]};try{return be(Ta(r))}catch(r){if(r instanceof n&&r.message.includes("Unexpected async operation")){return Oa({type:"Eval",node:e,env:t,k:[]}).then(e=>be(e))}throw r}}default:throw new n(`${l(e[0])}-node cannot be evaluated`,e[2])}}function ra(e,t,r,a){if(w(e))return aa(e,t,r,a);if(Array.isArray(e))return ia(e,t,a);if(I(e))return oa(e,t,a);if("string"==typeof e)return la(e,t,a);if(W(e))return ca(e,t,a);throw new n("Unexpected function type",a)}function aa(e,t,r,a){switch(e.functionType){case"UserDefined":return sa(e,t,r,a);case"Partial":return function(e,t,r,a){const s=[...e.params];if(t.length!==e.placeholders.length)throw new n(`(partial) expects ${e.placeholders.length} arguments, got ${t.length}.`,a);const o=[...t];for(const t of e.placeholders)s.splice(t,0,o.shift());return ra(e.function,s,r,a)}(e,t,r,a);case"Comp":return function(e,t,r,a){const{params:s}=e;if(0===s.length){if(1!==t.length)throw new n(`(comp) expects one argument, got ${y(t.length)}.`,a);return E(t[0],a)}let o=t;for(let e=s.length-1;e>=0;e--){const t=s[e];o=et(o,e=>et(ra(M(t,a),e,r,a),e=>[e]))}return et(o,e=>E(e[0],a))}(e,t,r,a);case"Constantly":return e.value;case"Juxt":return function(e,t,n,r){return function(e,t){const n=[];for(let r=0;r<e.length;r++){const a=t(e[r],r);if(a instanceof Promise)return tt(a,n,e,t,r);n.push(a)}return n}(e.params,e=>ra(M(e,r),t,n,r))}(e,t,r,a);case"Complement":return et(ra(e.function,t,r,a),e=>!e);case"EveryPred":return function(e,t,n,r){const a=[];for(const s of e.params)for(const e of t)a.push(()=>ra(M(s,r),[e],n,r));return nt(a,(e,t)=>!!e&&et(t(),e=>!!e),!0)}(e,t,r,a);case"SomePred":return function(e,t,n,r){const a=[];for(const s of e.params)for(const e of t)a.push(()=>ra(M(s,r),[e],n,r));return nt(a,(e,t)=>!!e||et(t(),e=>!!e),!1)}(e,t,r,a);case"Fnull":return function(e,t,n,r){const a=t.map((t,n)=>null===t?te(e.params[n]):t);return ra(M(e.function,r),a,n,r)}(e,t,r,a);case"EffectMatcher":return function(e,t,n){K({min:1,max:1},t.length,e.sourceCodeInfo??n);const r=t[0];O(r,n);const a=r.name;if("string"===e.matchType)return Rr(a,e.pattern);const s=new RegExp(e.pattern,e.flags);return s.test(a)}(e,t,a);case"Builtin":{const s=Bt.allNormalExpressions[e.normalBuiltinSymbolType];return s.dvalaImpl?sa(s.dvalaImpl,t,r,a):function(e,t,r,a){const s=v(Bt.allNormalExpressions[e.normalBuiltinSymbolType],a);if(r.pure&&!1===s.pure)throw new n(`Cannot call impure function '${e.name}' in pure mode`,a);if(s.dvalaImpl)return sa(s.dvalaImpl,t,r,a);return s.evaluate(t,a,r,{executeFunction:ra})}(e,t,r,a)}case"SpecialBuiltin":return function(e,t,r,a){const s=v(Bt.specialExpressions[e.specialBuiltinSymbolType],a);if(s.evaluateAsNormalExpression)return s.evaluateAsNormalExpression(t,a,r,{executeFunction:ra});throw new n(`Special builtin function ${e.specialBuiltinSymbolType} is not supported as normal expression.`,a)}(e,t,r,a);case"Module":return function(e,t,r,a){const s=r.getModule(e.moduleName);if(!s)throw new n(`Module '${e.moduleName}' not found.`,a);const o=s.functions[e.functionName];if(!o)throw new n(`Function '${e.functionName}' not found in module '${e.moduleName}'.`,a);if(r.pure&&!1===o.pure)throw new n(`Cannot call impure function '${e.functionName}' in pure mode`,a);if(K(o.arity,t.length,a),o.dvalaImpl)return sa(o.dvalaImpl,t,r,a);return o.evaluate(t,a,r,{executeFunction:ra})}(e,t,r,a)}}function sa(e,r,a,s){function o(r){if(!Y(e.arity,r.length))throw new n(`Expected ${e.arity} arguments, got ${r.length}.`,s);const i=e.evaluatedfunction,l=i[0],c=l.filter(e=>e[0]!==Ge).length,u=a.create(e.evaluatedfunction[2]),p={self:{value:e}},f=[];let d,m;for(let e=0;e<r.length;e+=1)if(e<c){const t=e;d=et(d,()=>{const e=te(r[t]);return et(it(l[t],e,e=>na(e,u.create(p))),e=>{Object.entries(e).forEach(([e,t])=>{p[e]={value:t}})})})}else f.push(te(r[e]));for(let e=r.length;e<c;e++){const t=e;m=et(m,()=>{const e=l[t];return et(na(e[1][1],a.create(p)),t=>et(it(e,t,e=>na(e,a.create(p))),e=>{Object.entries(e).forEach(([e,t])=>{p[e]={value:t}})}))})}return et(d,()=>et(m,()=>{const e=l.find(e=>e[0]===Ge),n=void 0!==e?et(it(e,f,e=>na(e,a.create(p))),e=>{Object.entries(e).forEach(([e,t])=>{p[e]={value:t}})}):void 0;return et(n,()=>{const e=u.create(p),n=nt(i[1],(t,n)=>na(n,e),null);return n instanceof Promise?n.catch(e=>{if(e instanceof t)return o(e.params);throw e}):n})}))}for(;;)try{return o(r)}catch(e){if(e instanceof t){r=e.params;continue}throw e}}function oa(e,t,r){if(1!==t.length)throw new n("Object as function requires one string parameter.",r);const a=t[0];return B(a,r),te(e[a])}function ia(e,t,r){if(1!==t.length)throw new n("Array as function requires one non negative integer parameter.",r);const a=t[0];return J(a,r,{integer:!0,nonNegative:!0}),te(e[a])}function la(e,t,r){if(1!==t.length)throw new n("String as function requires one Obj parameter.",r);const a=te(t[0]);if(I(a))return te(a[e]);if(W(a,{integer:!0}))return te(e[a]);throw new n(`string as function expects Obj or integer parameter, got ${y(a)}`,r)}function ca(e,t,r){if(J(e,void 0,{integer:!0}),1!==t.length)throw new n("Number as function requires one Arr parameter.",r);const a=t[0];return S(a,r),te(a[e])}function ua(e){const t=e[1];if(!["true","false","null"].includes(t))throw new n(`Reserved symbol ${t} cannot be evaluated`,e[2]);return v(rr[t],e[2])}function pa(e,t,r){switch(e[0]){case o.Number:case o.String:return{type:"Value",value:e[1],k:r};case o.NormalBuiltinSymbol:case o.SpecialBuiltinSymbol:case o.UserDefinedSymbol:return{type:"Value",value:t.evaluateSymbol(e),k:r};case o.ReservedSymbol:return{type:"Value",value:ua(e),k:r};case o.NormalExpression:return function(e,t,n){const r=e[1][1],a=e[2],s={type:"NanCheck",sourceCodeInfo:a},i={type:"EvalArgs",node:e,index:0,params:[],placeholders:[],env:t,sourceCodeInfo:a};let l=0;for(;l<r.length;){const e=r[l];if(e[0]!==o.ReservedSymbol||"_"!==e[1])break;i.placeholders.push(i.params.length),l++}if(i.index=l,l>=r.length)return fa(i,[s,...n]);const c=r[l],u=[i,s,...n];if(Yt(c))return{type:"Eval",node:c[1],env:t,k:u};return{type:"Eval",node:c,env:t,k:u}}(e,t,r);case o.SpecialExpression:return function(e,t,r){const a=e[2],s=e[1][0];switch(s){case Ut.if:case Ut.unless:{const[n,o,i]=e[1][1];return{type:"Eval",node:n,env:t,k:[{type:"IfBranch",thenNode:o,elseNode:i,inverted:s===Ut.unless,env:t,sourceCodeInfo:a},...r]}}case Ut["&&"]:{const n=e[1][1];if(0===n.length)return{type:"Value",value:!0,k:r};const s={type:"And",nodes:n,index:1,env:t,sourceCodeInfo:a};return 1===n.length?{type:"Eval",node:n[0],env:t,k:r}:{type:"Eval",node:n[0],env:t,k:[s,...r]}}case Ut["||"]:{const n=e[1][1];if(0===n.length)return{type:"Value",value:!1,k:r};const s={type:"Or",nodes:n,index:1,env:t,sourceCodeInfo:a};return 1===n.length?{type:"Eval",node:n[0],env:t,k:r}:{type:"Eval",node:n[0],env:t,k:[s,...r]}}case Ut["??"]:{const n=e[1][1];if(0===n.length)return{type:"Value",value:null,k:r};const s=n[0];if(Ft(s)&&null===t.lookUp(s)){if(1===n.length)return{type:"Value",value:null,k:r};const e={type:"Qq",nodes:n,index:2,env:t,sourceCodeInfo:a},s=n[1];return Ft(s)&&null===t.lookUp(s)?function(e,t){return ha(e,t)}(e,r):2===n.length?{type:"Eval",node:s,env:t,k:r}:{type:"Eval",node:s,env:t,k:[e,...r]}}const o={type:"Qq",nodes:n,index:1,env:t,sourceCodeInfo:a};return 1===n.length?{type:"Eval",node:s,env:t,k:r}:{type:"Eval",node:s,env:t,k:[o,...r]}}case Ut.cond:{const n=e[1][1];if(0===n.length)return{type:"Value",value:null,k:r};const s={type:"Cond",phase:"test",cases:n,index:0,env:t,sourceCodeInfo:a};return{type:"Eval",node:n[0][0],env:t,k:[s,...r]}}case Ut.match:{const n=e[1][1],s=e[1][2];return{type:"Eval",node:n,env:t,k:[{type:"Match",phase:"matchValue",matchValue:null,cases:s,index:0,bindings:{},env:t,sourceCodeInfo:a},...r]}}case Ut.block:{const n=e[1][1],s=e[1][2],o={},i=t.create(o);let l=r;if(s&&s.length>0){l=[{type:"TryWith",handlers:s.map(([e,n])=>({effectRef:na(e,t),handlerNode:n})),env:t,sourceCodeInfo:a},...r]}if(0===n.length)return{type:"Value",value:null,k:l};if(1===n.length)return{type:"Eval",node:n[0],env:i,k:l};const c={type:"Sequence",nodes:n,index:1,env:i,sourceCodeInfo:a};return{type:"Eval",node:n[0],env:i,k:[c,...l]}}case Ut.let:{const n=e[1][1],s=n[1][0];return{type:"Eval",node:n[1][1],env:t,k:[{type:"LetBind",target:s,env:t,sourceCodeInfo:a},...r]}}case Ut.loop:{const n=e[1][1],s=e[1][2];if(0===n.length){const e={},o={type:"LoopIterate",bindingNodes:n,bindingContext:e,body:s,env:t.create(e),sourceCodeInfo:a};return{type:"Eval",node:s,env:t.create(e),k:[o,...r]}}const o={type:"LoopBind",phase:"value",bindingNodes:n,index:0,context:{},body:s,env:t,sourceCodeInfo:a};return{type:"Eval",node:n[0][1][1],env:t,k:[o,...r]}}case Ut.for:case Ut.doseq:{const n=e[1][1],o=e[1][2],i=s===Ut.for;if(0===n.length)return{type:"Value",value:i?[]:null,k:r};const l={},c=t.create(l),u={type:"ForLoop",returnResult:i,bindingNodes:n,body:o,result:[],phase:"evalCollection",bindingLevel:0,levelStates:[],context:l,env:c,sourceCodeInfo:a};return{type:"Eval",node:n[0][0][1][1],env:c,k:[u,...r]}}case Ut.recur:{const n=e[1][1];if(0===n.length)return Ea([],r,a);const s={type:"Recur",nodes:n,index:1,params:[],env:t,sourceCodeInfo:a};if(1===n.length){const e={...s,index:1};return{type:"Eval",node:n[0],env:t,k:[e,...r]}}return{type:"Eval",node:n[0],env:t,k:[s,...r]}}case Ut.array:{const n=e[1][1];if(0===n.length)return{type:"Value",value:[],k:r};const s=n[0],o=Yt(s),i={type:"ArrayBuild",nodes:n,index:0,result:[],isSpread:o,env:t,sourceCodeInfo:a};return{type:"Eval",node:o?s[1]:s,env:t,k:[i,...r]}}case Ut.object:{const n=e[1][1];if(0===n.length)return{type:"Value",value:{},k:r};const s=n[0],o=Yt(s),i={type:"ObjectBuild",nodes:n,index:0,result:{},currentKey:null,isSpread:o,env:t,sourceCodeInfo:a};return{type:"Eval",node:o?s[1]:s,env:t,k:[i,...r]}}case Ut["0_lambda"]:{const n=function(e,t){const n={},r=e[0].reduce((e,t)=>(Object.keys(ct(t)).forEach(t=>{e[t]={value:null}}),e),{});return Zt(e[1],t.new(r),Bt,na).forEach(e=>{const r=t.getValue(e);A(r)&&(n[e]={value:r})}),[e[0],e[1],n]}(e[1][1],t),a=n[0].filter(e=>e[0]!==Ge&&void 0===e[1][1]).length,s={min:a>0?a:void 0,max:n[0].some(e=>e[0]===Ge)?void 0:n[0].length};return{type:"Value",value:{[u]:!0,sourceCodeInfo:e[2],functionType:"UserDefined",name:void 0,evaluatedfunction:n,arity:s,docString:""},k:r}}case Ut["defined?"]:{const n=e[1][1];if(!Ft(n))return{type:"Value",value:!0,k:r};return{type:"Value",value:null!==t.lookUp(n),k:r}}case Ut.import:{const s=e[1][1],o=t.getValueModule(s);if(o.found)return{type:"Value",value:o.value,k:r};const i=t.getModule(s);if(!i)throw new n(`Unknown module: '${s}'`,a);const l={};for(const[e,t]of Object.entries(i.functions))l[e]={[u]:!0,sourceCodeInfo:a,functionType:"Module",moduleName:s,functionName:e,arity:t.arity};if(i.source){const e=fr(dr(jr(i.source,!1,void 0),{removeWhiteSpace:!0})),n=t.create({}),o={type:"ImportMerge",tsFunctions:l,moduleName:s,module:i,env:t,sourceCodeInfo:a};if(1===e.length)return{type:"Eval",node:e[0],env:n,k:[o,...r]};const c={type:"Sequence",nodes:e,index:1,env:n};return{type:"Eval",node:e[0],env:n,k:[c,o,...r]}}return t.registerValueModule(s,l),{type:"Value",value:l,k:r}}case Ut.effect:return{type:"Value",value:Br(e[1][1]),k:r};case Ut.perform:{const n=[e[1][1],...e[1][2]];if(1===n.length){const e={type:"PerformArgs",argNodes:n,index:1,params:[],env:t,sourceCodeInfo:a};return{type:"Eval",node:n[0],env:t,k:[e,...r]}}const s={type:"PerformArgs",argNodes:n,index:1,params:[],env:t,sourceCodeInfo:a};return{type:"Eval",node:n[0],env:t,k:[s,...r]}}case Ut.parallel:return{type:"Parallel",branches:e[1][1],env:t,k:r};case Ut.race:return{type:"Race",branches:e[1][1],env:t,k:r};default:throw new n(`Unknown special expression type: ${s}`,a)}}(e,t,r);default:throw new n(`${l(e[0])}-node cannot be evaluated`,e[2])}}function fa(e,t){const{node:r,params:a,placeholders:o,env:i,sourceCodeInfo:l}=e;if(Jt(r)){const e=r[1][0];if(o.length>0){const n=i.evaluateSymbol(e);return{type:"Value",value:{[u]:!0,function:M(n,l),functionType:"Partial",params:a,placeholders:o,sourceCodeInfo:l,arity:G(o.length)},k:t}}if(zt(e)){const r=e[1],s=Bt.allNormalExpressions[r];if(i.pure&&!1===s.pure)throw new n(`Cannot call impure function '${s.name}' in pure mode`,l);if(s.dvalaImpl)return ma(s.dvalaImpl,a,i,l,t);return Ra(s.evaluate(a,l,i,{executeFunction:ra}),t)}const c=i.getValue(e[1]);if(void 0!==c)return da(M(c,l),a,o,i,l,t);throw new s(e[1],l)}return{type:"Eval",node:r[1][0],env:i,k:[{type:"CallFn",params:a,placeholders:o,env:i,sourceCodeInfo:l},...t]}}function da(e,t,r,a,s,o){if(r.length>0){return{type:"Value",value:{[u]:!0,function:e,functionType:"Partial",params:t,placeholders:r,sourceCodeInfo:s,arity:G(r.length)},k:o}}if(w(e))return function(e,t,n,r,a){switch(e.functionType){case"UserDefined":return ma(e,t,n,r,a);case"Partial":case"Comp":case"Constantly":case"Juxt":case"Complement":case"EveryPred":case"SomePred":case"Fnull":case"EffectMatcher":case"SpecialBuiltin":return Ra(aa(e,t,n,r),a);case"Module":{const s=n.getModule(e.moduleName),o=s?.functions[e.functionName];if(o?.dvalaImpl)return K(o.arity,t.length,r),ma(o.dvalaImpl,t,n,r,a);return Ra(aa(e,t,n,r),a)}case"Builtin":{const s=Bt.allNormalExpressions[e.normalBuiltinSymbolType];if(s.dvalaImpl)return ma(s.dvalaImpl,t,n,r,a);return Ra(aa(e,t,n,r),a)}}}(e,t,a,s,o);if(Array.isArray(e))return{type:"Value",value:ia(e,t,s),k:o};if(I(e))return{type:"Value",value:oa(e,t,s),k:o};if("string"==typeof e)return{type:"Value",value:la(e,t,s),k:o};if(W(e))return{type:"Value",value:ca(e,t,s),k:o};throw new n("Unexpected function type",s)}function ma(e,t,r,a,s){if(!Y(e.arity,t.length))throw new n(`Expected ${e.arity} arguments, got ${t.length}.`,a);const o=e.evaluatedfunction,i=o[0],l=i.filter(e=>e[0]!==Ge).length,c=r.create(e.evaluatedfunction[2]),u={self:{value:e}},p=[];for(let n=0;n<t.length;n+=1)if(n<l){const o=te(t[n]),l=it(i[n],o,e=>na(e,c.create(u)));if(l instanceof Promise){return Ra(sa(e,t,r,a),s)}Object.entries(l).forEach(([e,t])=>{u[e]={value:t}})}else p.push(te(t[n]));for(let n=t.length;n<l;n++){const o=i[n],l=na(o[1][1],c.create(u));if(l instanceof Promise){return Ra(sa(e,t,r,a),s)}const p=it(o,l,e=>na(e,c.create(u)));if(p instanceof Promise){return Ra(sa(e,t,r,a),s)}Object.entries(p).forEach(([e,t])=>{u[e]={value:t}})}const f=i.find(e=>e[0]===Ge);if(f){const n=it(f,p,e=>na(e,c.create(u)));if(n instanceof Promise){return Ra(sa(e,t,r,a),s)}Object.entries(n).forEach(([e,t])=>{u[e]={value:t}})}const d=o[1],m=c.create(u);if(0===d.length)return{type:"Value",value:null,k:s};const y={type:"FnBody",fn:e,bodyIndex:1,env:m,outerEnv:r,sourceCodeInfo:a};return d.length,{type:"Eval",node:d[0],env:m,k:[y,...s]}}function ya(e,t,r){switch(e.type){case"Sequence":return function(e,t,n){const{nodes:r,index:a,env:s}=e;if(a>=r.length)return{type:"Value",value:t,k:n};const o={...e,index:a+1};if(a===r.length-1)return{type:"Eval",node:r[a],env:s,k:n};return{type:"Eval",node:r[a],env:s,k:[o,...n]}}(e,t,r);case"IfBranch":return function(e,t,n){const{thenNode:r,elseNode:a,inverted:s,env:o}=e,i=s?!t:t;if(i)return{type:"Eval",node:r,env:o,k:n};if(a)return{type:"Eval",node:a,env:o,k:n};return{type:"Value",value:null,k:n}}(e,t,r);case"Cond":return function(e,t,n){const{cases:r,index:a,env:s}=e;if("test"===e.phase){if(t)return{type:"Eval",node:r[a][1],env:s,k:n};const o=a+1;if(o>=r.length)return{type:"Value",value:null,k:n};const i={...e,index:o};return{type:"Eval",node:r[o][0],env:s,k:[i,...n]}}return{type:"Value",value:t,k:n}}(e,t,r);case"Match":return function(e,t,n){const{cases:r,env:a}=e;if("matchValue"===e.phase){const r=t;return ga({...e,matchValue:r,phase:"guard"},n)}if("guard"===e.phase){if(!t){return ga({...e,index:e.index+1,bindings:{}},n)}const s={};for(const[t,n]of Object.entries(e.bindings))s[t]={value:n};const o=a.create(s);return{type:"Eval",node:r[e.index][1],env:o,k:n}}return{type:"Value",value:t,k:n}}(e,t,r);case"And":return function(e,t,n){if(!t)return{type:"Value",value:t,k:n};const{nodes:r,index:a,env:s}=e;if(a>=r.length)return{type:"Value",value:t,k:n};if(a===r.length-1)return{type:"Eval",node:r[a],env:s,k:n};const o={...e,index:a+1};return{type:"Eval",node:r[a],env:s,k:[o,...n]}}(e,t,r);case"Or":return function(e,t,n){if(t)return{type:"Value",value:t,k:n};const{nodes:r,index:a,env:s}=e;if(a>=r.length)return{type:"Value",value:t,k:n};if(a===r.length-1)return{type:"Eval",node:r[a],env:s,k:n};const o={...e,index:a+1};return{type:"Eval",node:r[a],env:s,k:[o,...n]}}(e,t,r);case"Qq":return function(e,t,n){if(null!==t)return{type:"Value",value:t,k:n};return ha(e,n)}(e,t,r);case"ArrayBuild":return function(e,t,r){const{nodes:a,result:s,env:o,sourceCodeInfo:i}=e;if(e.isSpread){if(!Array.isArray(t))throw new n("Spread value is not an array",i);s.push(...t)}else s.push(t);const l=e.index+1;if(l>=a.length)return{type:"Value",value:s,k:r};const c=a[l],u=Yt(c),p={...e,index:l,isSpread:u};return{type:"Eval",node:u?c[1]:c,env:o,k:[p,...r]}}(e,t,r);case"ObjectBuild":return function(e,t,r){const{nodes:a,result:s,env:o,sourceCodeInfo:i}=e;if(e.isSpread){if(!x(t))throw new n("Spread value is not an object",i);Object.assign(s,t);const l=e.index+1;if(l>=a.length)return{type:"Value",value:s,k:r};const c=a[l],u=Yt(c),p={...e,index:l,currentKey:null,isSpread:u};return{type:"Eval",node:u?c[1]:c,env:o,k:[p,...r]}}if(null===e.currentKey){B(t,i);const s=a[e.index+1];if(void 0===s)throw new n("Missing value for key",i);return{type:"Eval",node:s,env:o,k:[{...e,currentKey:t},...r]}}{s[e.currentKey]=t;const n=e.index+2;if(n>=a.length)return{type:"Value",value:s,k:r};const i=a[n],l=Yt(i),c={...e,index:n,currentKey:null,isSpread:l};return{type:"Eval",node:l?i[1]:i,env:o,k:[c,...r]}}}(e,t,r);case"LetBind":return function(e,t,n){const{target:r,env:a,sourceCodeInfo:s}=e,o=it(r,t,e=>na(e,a));return et(o,e=>(a.addValues(e,s),{type:"Value",value:t,k:n}))}(e,t,r);case"LoopBind":return function(e,t,n){const{bindingNodes:r,index:a,context:s,body:o,env:i,sourceCodeInfo:l}=e,c=r[a],u=it(c[1][0],t,e=>na(e,i.create(s)));return et(u,t=>{Object.entries(t).forEach(([e,t])=>{s[e]={value:t}});const c=a+1;if(c>=r.length){const e=i.create(s);return{type:"Eval",node:o,env:e,k:[{type:"LoopIterate",bindingNodes:r,bindingContext:s,body:o,env:e,sourceCodeInfo:l},...n]}}const u={...e,index:c};return{type:"Eval",node:r[c][1][1],env:i.create(s),k:[u,...n]}})}(e,t,r);case"LoopIterate":return function(e,t,n){return{type:"Value",value:t,k:n}}(0,t,r);case"ForLoop":return function(e,t,r){const{returnResult:a,bindingNodes:s,result:o,env:i,sourceCodeInfo:l,context:c}=e,{asColl:u,isSeq:p}={asColl:(e,t)=>{if("string"==typeof e||Array.isArray(e)||I(e))return e;throw new n(`Expected collection, got ${y(e)}`,t)},isSeq:e=>"string"==typeof e||Array.isArray(e)};switch(e.phase){case"evalCollection":{const n=u(t,l),a=p(n)?n:Object.entries(n);if(0===a.length)return va(e,r);const o=[...e.levelStates];o[e.bindingLevel]={collection:a,index:0};const f=s[e.bindingLevel];return et(it(f[0][1][0],E(a[0],l),e=>na(e,i)),t=>{Object.entries(t).forEach(([e,t])=>{c[e]={value:t}});const n=f[1];return n.length>0?xa(e,o,n,0,r):wa(e,o,r)})}case"evalLet":throw new n("ForLoop evalLet should not reach applyFrame",l);case"evalWhen":{if(!t)return ba(e,r);const n=s[e.bindingLevel][3];if(n){const t={...e,phase:"evalWhile"};return{type:"Eval",node:n,env:i,k:[t,...r]}}return ka(e,r)}case"evalWhile":if(!t){const t=[...e.levelStates];return t[e.bindingLevel]={...t[e.bindingLevel],index:Number.POSITIVE_INFINITY},ba({...e,levelStates:t},r)}return ka(e,r);case"evalBody":return a&&o.push(t),ba(e,r);case"evalElement":throw new n(`Unexpected ForLoop phase: ${e.phase}`,l)}return{type:"Value",value:null,k:r}}(e,t,r);case"Recur":return function(e,t,n){const{nodes:r,index:a,params:s,env:o}=e;if(s.push(t),a>=r.length)return Ea(s,n,e.sourceCodeInfo);const i={...e,index:a+1};return{type:"Eval",node:r[a],env:o,k:[i,...n]}}(e,t,r);case"PerformArgs":return function(e,t,n){const{argNodes:r,index:a,params:s,env:o}=e;if(s.push(t),a>=r.length){const t=s[0];O(t,e.sourceCodeInfo);return{type:"Perform",effect:t,args:s.slice(1),k:n,sourceCodeInfo:e.sourceCodeInfo}}const i={...e,index:a+1};return{type:"Eval",node:r[a],env:o,k:[i,...n]}}(e,t,r);case"TryWith":return function(e,t){return{type:"Value",value:e,k:t}}(t,r);case"EffectResume":return function(e,t){return{type:"Value",value:t,k:e.resumeK}}(e,t);case"ParallelResume":return function(e,t,n){return{type:"ParallelResume",value:t,branchCount:e.branchCount,completedBranches:e.completedBranches,suspendedBranches:e.suspendedBranches,k:n}}(e,t,r);case"EvalArgs":return function(e,t,r){const{node:a,params:s,placeholders:i,env:l}=e,c=a[1][1],u=c[e.index];if(Yt(u)){if(!Array.isArray(t))throw new n(`Spread operator requires an array, got ${y(t)}`,u[2]);s.push(...t)}else s.push(t);let p=e.index+1;for(;p<c.length;){const e=c[p];if(e[0]!==o.ReservedSymbol||"_"!==e[1])break;i.push(s.length),p++}if(p>=c.length)return fa({...e,index:p},r);const f={...e,index:p},d=c[p];if(Yt(d))return{type:"Eval",node:d[1],env:l,k:[f,...r]};return{type:"Eval",node:d,env:l,k:[f,...r]}}(e,t,r);case"CallFn":return function(e,t,n){const r=M(t,e.sourceCodeInfo);return da(r,e.params,e.placeholders,e.env,e.sourceCodeInfo,n)}(e,t,r);case"FnBody":return function(e,t,n){const{fn:r,bodyIndex:a,env:s}=e,o=r.evaluatedfunction[1];if(a>=o.length)return{type:"Value",value:t,k:n};const i={...e,bodyIndex:a+1};return{type:"Eval",node:o[a],env:s,k:[i,...n]}}(e,t,r);case"BindingDefault":return function(e,t,r){const{target:a,record:s,env:o,sourceCodeInfo:i}=e,l=it(a,t,e=>na(e,o));if(l instanceof Promise)throw new n("Async binding default evaluation not supported in trampoline yet",i);return Object.assign(s,l),{type:"Value",value:t,k:r}}(e,t,r);case"NanCheck":return function(e,t,r){if("number"==typeof t&&Number.isNaN(t))throw new n("Number is NaN",e.sourceCodeInfo);return{type:"Value",value:be(t),k:r}}(e,t,r);case"DebugStep":return function(e,t,n){if("awaitValue"===e.phase){const r={expression:e.sourceCodeInfo?.code??"",value:t,location:e.sourceCodeInfo?{line:e.sourceCodeInfo.position.line,column:e.sourceCodeInfo.position.column}:{line:0,column:0},env:Ca(e.env)},a={type:"DebugStep",phase:"awaitPerform",sourceCodeInfo:e.sourceCodeInfo,env:e.env};return{type:"Perform",effect:Br("dvala.debug.step"),args:[r],k:[a,...n]}}return{type:"Value",value:t,k:n}}(e,t,r);case"ImportMerge":{const n=I(t)?t:{};for(const[t,r]of Object.entries(n)){const n=e.module.functions[t];n&&k(r)&&(n.dvalaImpl=r)}const a={};for(const[t,r]of Object.entries(n))e.module.functions[t]||(a[t]=r);const s={...e.tsFunctions,...a};return e.env.registerValueModule(e.moduleName,s),{type:"Value",value:s,k:r}}default:throw new n(`Unhandled frame type: ${e.type}`,void 0)}}function ga(e,t){const{matchValue:r,cases:a,index:s,env:o,sourceCodeInfo:i}=e;for(let l=s;l<a.length;l++){const[s,c,u]=a[l],p=pt(s,r,e=>na(e,o));if(p instanceof Promise)throw new n("Async pattern matching not supported in trampoline yet",i);if(null===p)continue;if(u){const n={};for(const[e,t]of Object.entries(p))n[e]={value:t};return{type:"Eval",node:u,env:o.create(n),k:[{...e,phase:"guard",index:l,bindings:p},...t]}}const f={};for(const[e,t]of Object.entries(p))f[e]={value:t};return{type:"Eval",node:c,env:o.create(f),k:t}}return{type:"Value",value:null,k:t}}function ha(e,t){const{nodes:n,env:r}=e;let{index:a}=e;for(;a<n.length;){const e=n[a];if(!Ft(e)||null!==r.lookUp(e))break;a++}if(a>=n.length)return{type:"Value",value:null,k:t};if(a===n.length-1)return{type:"Eval",node:n[a],env:r,k:t};const s={...e,index:a+1};return{type:"Eval",node:n[a],env:r,k:[s,...t]}}function va(e,t){return{type:"Value",value:e.returnResult?e.result:null,k:t}}function ba(e,t){const{bindingNodes:n,env:r,sourceCodeInfo:a,context:s}=e,o=[...e.levelStates],i=e.bindingLevel,l=o[i],c=l.index+1;if(c>=l.collection.length)return 0===i?va(e,t):ba({...e,bindingLevel:i-1},t);o[i]={...l,index:c};const u=n[i];return et(it(u[0][1][0],E(l.collection[c],a),e=>na(e,r)),n=>{Object.entries(n).forEach(([e,t])=>{s[e]={value:t}});const r=u[1];return r.length>0?xa({...e,levelStates:o,bindingLevel:i},o,r,0,t):wa({...e,levelStates:o,bindingLevel:i},o,t)})}function xa(e,t,n,r,a){const{env:s,context:o}=e;let i;for(let e=r;e<n.length;e++){const t=e;i=et(i,()=>{const e=n[t],[r,a]=e[1];return et(na(a,s),e=>et(it(r,e,e=>na(e,s)),e=>{Object.entries(e).forEach(([e,t])=>{o[e]={value:t}})}))})}return et(i,()=>wa({...e,levelStates:t},t,a))}function wa(e,t,n){const{bindingNodes:r,env:a}=e,s=r[e.bindingLevel],o=s[2],i=s[3];if(o){return{type:"Eval",node:o,env:a,k:[{...e,levelStates:t,phase:"evalWhen"},...n]}}if(i){return{type:"Eval",node:i,env:a,k:[{...e,levelStates:t,phase:"evalWhile"},...n]}}return ka({...e,levelStates:t},n)}function ka(e,t){const{bindingNodes:n,body:r,env:a}=e,s=e.bindingLevel+1;if(s<n.length){return{type:"Eval",node:n[s][0][1][1],env:a,k:[{...e,phase:"evalCollection",bindingLevel:s},...t]}}const o={...e,phase:"evalBody"};return{type:"Eval",node:r,env:a.create(e.context),k:[o,...t]}}function Aa(e,t,n,r,a){const s=Br("dvala.error"),o=[e.shortMessage];for(let n=0;n<t.length;n++){const r=t[n];if("TryWith"===r.type)for(const a of r.handlers)if(Na(a,s,r.env,e.sourceCodeInfo))return $a(a,r,o,t,n,e.sourceCodeInfo)}const i=Pr("dvala.error",n);return i.length>0?Ia("dvala.error",i,o,t,r,e.sourceCodeInfo,a):null}function Ea(e,t,r){for(let a=0;a<t.length;a++){const s=t[a];if("LoopIterate"===s.type){const{bindingNodes:o,bindingContext:i,body:l,env:c}=s,u=t.slice(a+1);if(e.length!==o.length)throw new n(`recur expected ${o.length} parameters, got ${e.length}`,r);const p=at(o,(t,n)=>et(it(t[1][0],te(e[n]),e=>na(e,c)),e=>{Object.entries(e).forEach(([e,t])=>{i[e]={value:t}})}));return et(p,()=>{const e=c.getContextsRaw()[0];if(e!==i)for(const[t,n]of Object.entries(i))e[t]=n;const t={type:"LoopIterate",bindingNodes:o,bindingContext:i,body:l,env:c,sourceCodeInfo:s.sourceCodeInfo};return{type:"Eval",node:l,env:c,k:[t,...u]}})}if("FnBody"===s.type){const{fn:n,outerEnv:r}=s,o=t.slice(a+1);return ma(n,e,r,s.sourceCodeInfo,o)}}throw new n("recur called outside of loop or function body",r)}function Na(e,t,r,a){if(T(e.effectRef))return e.effectRef.name===t.name;if(w(e.effectRef)){const s=ra(e.effectRef,[t],r,a);if(s instanceof Promise)throw new n("Effect handler predicates must be synchronous",a);return!!s}return!1}function $a(e,t,n,r,a,s){const o=[{type:"EffectResume",resumeK:r,sourceCodeInfo:s},...r.slice(a+1)];return da(M(na(e.handlerNode,t.env),t.sourceCodeInfo),[n],[],t.env,s,o)}function Sa(e,t,a,s,o,i,l){if("dvala.checkpoint"===e.name&&l){const e=t[0],n={continuation:Gr(a),timestamp:Date.now(),index:l.nextSnapshotIndex++,runId:l.runId,...void 0!==e?{meta:e}:{}};l.snapshots.push(n),void 0!==l.maxSnapshots&&l.snapshots.length>l.maxSnapshots&&l.snapshots.shift()}for(let n=0;n<a.length;n++){const r=a[n];if("TryWith"===r.type)for(const o of r.handlers)if(Na(o,e,r.env,s))return $a(o,r,t,a,n,s)}const c=Pr(e.name,o);if(c.length>0)return Ia(e.name,c,t,a,i,s,l);const u=function(e){const t=ta[e];if(t)return(e,n,r)=>(K(t.arity,e.length,r),t.handler(e,n,r))}(e.name);if(u)return u(t,a,s);if("dvala.error"===e.name){const e="string"==typeof t[0]?t[0]:String(t[0]??"Unknown error");throw new r(e,s)}throw new n(`Unhandled effect: '${e.name}'`,s)}function Ia(e,t,a,s,o,i,l){const c=o??(new AbortController).signal,u=Array.from(a);function p(e,t){switch(e.kind){case"step":return e.step;case"asyncResume":return e.promise.then(e=>({type:"Value",value:e,k:s}),e=>({type:"Error",error:e instanceof n?e:new n(e instanceof Error?e:`${e}`,i),k:s}));case"throw":throw e.error;case"next":return f(t)}}function f(a){if(a>=t.length){if("dvala.error"===e){const e="string"==typeof u[0]?u[0]:String(u[0]??"Unknown error");throw new r(e,i)}throw new n(`Unhandled effect: '${e}'`,i)}const[,o]=t[a];let f,d=!1;function m(e){if(d)throw new n(`Effect handler called ${e}() after already calling another operation`,i);d=!0}const y=o({effectName:e,args:u,signal:c,resume:e=>{m("resume"),f=e instanceof Promise?{kind:"asyncResume",promise:e}:{kind:"step",step:{type:"Value",value:e,k:s}}},fail:t=>{m("fail");f={kind:"step",step:{type:"Error",error:new n(t??`Effect handler failed for '${e}'`,i),k:s}}},suspend:e=>{m("suspend"),f={kind:"throw",error:new Tr(s,l?l.snapshots:[],l?l.nextSnapshotIndex:0,e)}},next:()=>{m("next"),f={kind:"next"}},get snapshots(){return l?[...l.snapshots]:[]},checkpoint:e=>{if(!l)throw new n("checkpoint is not available outside effect-enabled execution",i);const t={continuation:Gr(s),timestamp:Date.now(),index:l.nextSnapshotIndex++,runId:l.runId,...void 0!==e?{meta:e}:{}};return l.snapshots.push(t),void 0!==l.maxSnapshots&&l.snapshots.length>l.maxSnapshots&&l.snapshots.shift(),t},resumeFrom:(e,t)=>{if(d)throw new n("Effect handler called resumeFrom() after already calling another operation",i);if(!l)throw new n("resumeFrom is not available outside effect-enabled execution",i);const r=l.snapshots.find(t=>t.index===e.index&&t.runId===e.runId);if(!r)throw new n(`Invalid snapshot: no snapshot with index ${e.index} found in current run`,i);d=!0,f={kind:"throw",error:new Mr(r.continuation,t,r.index)}}});if(!(y instanceof Promise)){if(!f)throw new n(`Effect handler for '${e}' did not call resume(), fail(), suspend(), or next()`,i);return p(f,a+1)}return f?(y.catch(()=>{}),p(f,a+1)):y.then(()=>{if(!f)throw new n(`Effect handler for '${e}' did not call resume(), fail(), suspend(), or next()`,i);return p(f,a+1)},e=>{if(f)return p(f,a+1);if(Or(e)||Vr(e))throw e;return{type:"Error",error:e instanceof n?e:new n(e instanceof Error?e:`${e}`,i),k:s}})}return f(0)}function ja(e,t){throw new Tr(e,[],0,t)}async function qa(e,t,n,r){return Ua({type:"Eval",node:e,env:t,k:[]},n,r)}function Ca(e){const t={},n=e.getHostValues();if(n)for(const[e,r]of Object.entries(n))t[e]=r;const r=e.getContextsRaw();for(let e=r.length-1;e>=0;e--)for(const[n,a]of Object.entries(r[e]))t[n]=a.value;return t}function Ra(e,t){return e instanceof Promise?e.then(e=>({type:"Value",value:e,k:t}),e=>({type:"Error",error:e instanceof n?e:new n(`${e}`,void 0),k:t})):{type:"Value",value:e,k:t}}function Pa(e,t,r,a){try{switch(e.type){case"Value":{if(0===e.k.length)return e;const[t,...n]=e.k;return ya(t,e.value,n)}case"Eval":return pa(e.node,e.env,e.k);case"Apply":return ya(e.frame,e.value,e.k);case"Perform":return Sa(e.effect,e.args,e.k,e.sourceCodeInfo,t,r,a);case"Parallel":return async function(e,t,r,a,s){const o=s??(new AbortController).signal,i=e.map(e=>qa(e,t,a,o)),l=await Promise.allSettled(i),c=[],u=[],p=[];for(let e=0;e<l.length;e++){const t=l[e];if("rejected"===t.status)p.push(new n(`${t.reason}`,void 0));else{const n=t.value;switch(n.type){case"completed":c.push({index:e,value:n.value});break;case"suspended":u.push({index:e,snapshot:n.snapshot});break;case"error":p.push(n.error)}}}if(p.length>0)throw p[0];if(u.length>0)return ja([{type:"ParallelResume",branchCount:e.length,completedBranches:c,suspendedBranches:u.slice(1)},...r],u[0].snapshot.meta);const f=Array.from({length:e.length});for(const{index:e,value:t}of c)f[e]=t;return{type:"Value",value:f,k:r}}(e.branches,e.env,e.k,t,r);case"Race":return async function(e,t,r,a,s){const o=s??(new AbortController).signal,i=e.map(()=>new AbortController),l=()=>{for(const e of i)e.abort(o.reason)};o.addEventListener("abort",l,{once:!0});try{let s=-1,o=null;const l=e.map(async(e,n)=>{const r=i[n].signal,l=await qa(e,t,a,r);if("completed"===l.type&&s<0){s=n,o=l.value;for(let e=0;e<i.length;e++)e!==n&&i[e].abort("race: branch lost")}return l}),c=await Promise.allSettled(l);if(s>=0)return{type:"Value",value:o,k:r};const u=[],p=[];for(let e=0;e<c.length;e++){const t=c[e];if("rejected"===t.status)p.push(new n(`${t.reason}`,void 0));else{const e=t.value;switch(e.type){case"suspended":u.push(e.snapshot.meta??null);break;case"error":p.push(e.error)}}}u.length>0&&ja(r,{type:"race",branches:u});const f=p.map(e=>e.message).join("; ");throw new n(`race: all branches failed: ${f}`,void 0)}finally{o.removeEventListener("abort",l)}}(e.branches,e.env,e.k,t,r);case"ParallelResume":return function(e){const{value:t,branchCount:n,completedBranches:r,suspendedBranches:a,k:s}=e,o=new Set(r.map(e=>e.index)),i=new Set(a.map(e=>e.index));let l=-1;for(let e=0;e<n;e++)if(!o.has(e)&&!i.has(e)){l=e;break}const c=[...r,{index:l,value:t}];if(a.length>0){const e=a[0];return ja([{type:"ParallelResume",branchCount:n,completedBranches:c,suspendedBranches:a.slice(1)},...s],e.snapshot.meta)}const u=Array.from({length:n});for(const{index:e,value:t}of c)u[e]=t;return{type:"Value",value:u,k:s}}(e);case"Error":{const n=Aa(e.error,e.k,t,r,a);if(null!==n)return n;throw e.error}}}catch(s){if(Or(s))throw s;if(s instanceof n){const n=Aa(s,"Value"===e.type?e.k.slice(1):e.k,t,r,a);if(null!==n)return n}throw s}}function Ta(e,t){let r=e;for(;;){if(r instanceof Promise)throw new n("Unexpected async operation in synchronous context. Use async.run() for async operations.",void 0);if("Value"===r.type&&0===r.k.length)return r.value;r=Pa(r,t)}}async function Oa(e){let t=e;for(;;){if(t instanceof Promise&&(t=await t),"Value"===t.type&&0===t.k.length)return t.value;t=Pa(t)}}function Ma(e,t){if(0===e.length)return{type:"Value",value:null,k:[]};if(1===e.length)return{type:"Eval",node:e[0],env:t,k:[]};const n={type:"Sequence",nodes:e,index:1,env:t};return{type:"Eval",node:e[0],env:t,k:[n]}}function Va(e,t){const r=Ma(e.body,t);try{return Ta(r)}catch(r){if(r instanceof n&&r.message.includes("Unexpected async operation")){return Oa(Ma(e.body,t))}throw r}}async function Ua(e,t,r,a,s,i){const l=null!=t&&"dvala.debug.step"in t,c={snapshots:a?a.snapshots:[],nextSnapshotIndex:a?a.nextSnapshotIndex:0,runId:"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),...void 0!==s?{maxSnapshots:s}:{}};let u=e;for(;;)try{for(;;){if(u instanceof Promise&&(u=await u),"Value"===u.type&&0===u.k.length)return{type:"completed",value:u.value};if(l&&"Eval"===u.type&&u.node[2]){const e=u.node[0];if(e===o.NormalExpression||e===o.SpecialExpression){const e={type:"DebugStep",phase:"awaitValue",sourceCodeInfo:u.node[2],env:u.env};u={...u,k:[e,...u.k]}}}u=Pa(u,t,r,c)}}catch(e){if(Vr(e)){const{k:t}=Hr(e.continuation,i),n=c.snapshots.findIndex(t=>t.index>e.trimToIndex);-1!==n&&c.snapshots.splice(n),u={type:"Value",value:e.value,k:t};continue}if(Or(e)){return{type:"suspended",snapshot:{continuation:Xr(e.k,e.snapshots,e.nextSnapshotIndex,e.meta),timestamp:Date.now(),index:c.nextSnapshotIndex++,runId:c.runId,meta:e.meta}}}return e instanceof n?{type:"error",error:e}:{type:"error",error:new n(`${e}`,void 0)}}}async function Ba(e,t,r){try{const n=r?.modules?new Map(r.modules.map(e=>[e.name,e])):void 0,a=Hr(e.continuation,{values:r?.bindings,modules:n}),s={values:r?.bindings,modules:n};return await async function(e,t,n,r,a){return Ua({type:"Value",value:t,k:e},n,(new AbortController).signal,r,r?.maxSnapshots,a)}(a.k,t,r?.handlers,{snapshots:a.snapshots,nextSnapshotIndex:a.nextSnapshotIndex,maxSnapshots:r?.maxSnapshots},s)}catch(e){return e instanceof n?{type:"error",error:e}:{type:"error",error:new n(`${e}`,void 0)}}}new Set(Object.keys(ta));const Da={collection:'{\n map: (first-coll, ...args) -> do\n let fn = last(args);\n let other-colls = slice(args, 0, count(args) - 1);\n let all-colls = [first-coll, ...other-colls];\n\n cond\n case object?(first-coll) then do\n let expected-keys = keys(first-coll) |> sort;\n doseq (obj in other-colls) -> do\n if not(object?(obj)) then\n perform(effect(dvala.error), "Expected object")\n end;\n let obj-keys = keys(obj) |> sort;\n if not(obj-keys == expected-keys) then\n perform(effect(dvala.error), ++(\n "All objects must have the same keys. Expected: ",\n join(expected-keys, ", "),\n ". Found: ",\n join(obj-keys, ", ")\n ))\n end\n end;\n reduce(keys(first-coll), (acc, k) -> do\n let a = for (coll in all-colls) -> coll(k);\n assoc(acc, k, apply(fn, a))\n end, {})\n end\n\n case string?(first-coll) then do\n doseq (s in other-colls) -> do\n if not(string?(s)) then\n perform(effect(dvala.error), "Expected string")\n end\n end;\n let len = reduce(other-colls, (m, s) -> min(m, count(s)), count(first-coll));\n let mapped = for (i in range(len)) -> do\n let a = for (coll in all-colls) -> nth(coll, i);\n apply(fn, a)\n end;\n reduce(mapped, (acc, ch) -> do\n if not(string?(ch)) then\n perform(effect(dvala.error), "Expected string")\n end;\n ++(acc, ch)\n end, "")\n end\n\n case true then do\n doseq (x in other-colls) -> do\n if not(array?(x)) then\n perform(effect(dvala.error), "Expected array")\n end\n end;\n let len = reduce(other-colls, (m, x) -> min(m, count(x)), count(first-coll));\n for (i in range(len)) -> do\n let a = for (coll in all-colls) -> nth(coll, i);\n apply(fn, a)\n end\n end\n end\n end,\n\n filter: (coll, fn) -> do\n cond\n case array?(coll) then\n reduce(coll, (acc, elem) -> if fn(elem) then [...acc, elem] else acc end, [])\n\n case string?(coll) then\n reduce(coll, (acc, ch) -> if fn(ch) then ++(acc, ch) else acc end, "")\n\n case object?(coll) then\n reduce(keys(coll), (acc, k) -> do\n if fn(coll(k)) then\n assoc(acc, k, coll(k))\n else\n acc\n end\n end, {})\n\n case true then\n perform(effect(dvala.error), "Expected collection")\n end\n end,\n\n reduce: (coll, fn, initial) -> do\n cond\n case string?(coll) then\n loop (acc = initial, i = 0) -> do\n if i >= count(coll) then\n acc\n else\n recur(fn(acc, nth(coll, i)), i + 1)\n end\n end\n\n case array?(coll) then\n loop (acc = initial, i = 0) -> do\n if i >= count(coll) then\n acc\n else\n recur(fn(acc, nth(coll, i)), i + 1)\n end\n end\n\n case object?(coll) then do\n let values = vals(coll);\n loop (acc = initial, i = 0) -> do\n if i >= count(values) then\n acc\n else\n recur(fn(acc, nth(values, i)), i + 1)\n end\n end\n end\n\n case true then\n perform(effect(dvala.error), "Expected collection")\n end\n end\n}',sequence:'{\n some: (seq, fn) -> do\n if null?(seq) then null\n else do\n loop (i = 0) -> do\n if i >= count(seq) then\n null\n else do\n let elem = nth(seq, i);\n if fn(elem) then elem\n else recur(i + 1)\n end\n end\n end\n end\n end\n end\n end,\n\n take-while: (seq, fn) -> do\n let is-str = string?(seq);\n let len = count(seq);\n let idx = loop (i = 0) -> do\n if i >= len then\n len\n else if fn(nth(seq, i)) then\n recur(i + 1)\n else\n i\n end\n end\n end;\n slice(seq, 0, idx)\n end,\n\n drop-while: (seq, fn) -> do\n let is-str = string?(seq);\n let len = count(seq);\n let idx = loop (i = 0) -> do\n if i >= len then\n len\n else if fn(nth(seq, i)) then\n recur(i + 1)\n else\n i\n end\n end\n end;\n slice(seq, idx)\n end,\n\n sort: (seq, ...args) -> do\n let cmp = if count(args) == 0 then compare else first(args) end;\n let is-str = string?(seq);\n let arr = if is-str then split(seq, "") else seq end;\n let len = count(arr);\n\n // merge two sorted arrays\n let merge-arrays = (left, right) -> do\n let left-len = count(left);\n let right-len = count(right);\n loop (result = [], li = 0, ri = 0) -> do\n if li >= left-len then\n ++(result, slice(right, ri))\n else if ri >= right-len then\n ++(result, slice(left, li))\n else do\n let l = nth(left, li);\n let r = nth(right, ri);\n if cmp(l, r) <= 0 then\n recur(push(result, l), li + 1, ri)\n else\n recur(push(result, r), li, ri + 1)\n end\n end\n end\n end\n end\n end;\n\n // recursive merge-sort\n let merge-sort = (a) -> do\n let n = count(a);\n if n <= 1 then a\n else do\n let mid = floor(n / 2);\n let left = merge-sort(slice(a, 0, mid));\n let right = merge-sort(slice(a, mid));\n merge-arrays(left, right)\n end\n end\n end;\n\n let sorted = merge-sort(arr);\n if is-str then join(sorted, "") else sorted end\n end\n}\n',array:'{\n mapcat: (arr, fn) -> do\n flatten(map(arr, fn), 1)\n end,\n\n moving-fn: (arr, window-size, fn) -> do\n if window-size > count(arr) then\n perform(effect(dvala.error), "Expected window-size <= array length")\n end;\n for (i in range(count(arr) - window-size + 1)) -> do\n fn(slice(arr, i, i + window-size))\n end\n end,\n\n running-fn: (arr, fn) -> do\n for (i in range(count(arr))) -> do\n fn(slice(arr, 0, i + 1))\n end\n end\n}\n',functional:'{\n "|>": (a, b) -> b(a),\n\n apply: (fn, ...args) -> do\n let arr = last(args);\n let leading = slice(args, 0, count(args) - 1);\n fn(...leading, ...arr)\n end\n}\n',object:'{\n merge-with: (...args) -> do\n let fn = last(args);\n let objs = slice(args, 0, count(args) - 1);\n if not(function?(fn)) then\n perform(effect(dvala.error), str("Expected function, got: ", type(fn)))\n end;\n if count(objs) == 0 then\n perform(effect(dvala.error), "Expected at least one object argument")\n end;\n reduce(rest(objs), (result, obj) -> do\n if not(object?(obj)) then\n perform(effect(dvala.error), str("Expected object, got: ", type(obj)))\n end;\n reduce(keys(obj), (res, key) -> do\n if contains?(res, key) then\n assoc(res, key, fn(get(res, key), get(obj, key)))\n else\n assoc(res, key, get(obj, key))\n end\n end, result)\n end, do\n let f = first(objs);\n if not(object?(f)) then\n perform(effect(dvala.error), str("Expected object, got: ", type(f)))\n end;\n f\n end)\n end\n}\n'};let _a=!1;function Fa(e){!function(){if(!_a){_a=!0;for(const[,e]of Object.entries(Da)){const t=Va({body:fr(dr(jr(e,!1,void 0),{removeWhiteSpace:!0})),hasDebugData:!1},Ht());if(t instanceof Promise)throw new TypeError("Core dvala sources must be synchronous");if(!I(t))continue;const n=t;for(const[e,t]of Object.entries(n)){const n=Le[e];n&&w(t)&&"UserDefined"===t.functionType&&(n.dvalaImpl=t)}}}}();const t=[];let r=-1;const a=e?.handlers??{},s=e?.bindings,o=e?.modules,i={...a,"dvala.debug.step":async e=>{e.suspend(e.args[0])}};function l(e){if("suspended"===e.type){const n=function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return{expression:"",value:null,location:{line:0,column:0},env:{}};const t=e,n=t.location;return{expression:t.expression??"",value:t.value,location:{line:n?.line??0,column:n?.column??0},env:t.env??{}}}(e.snapshot.meta??null),a={snapshot:e.snapshot,step:n,timestamp:Date.now()};t.length=r+1,t.push(a),r=t.length-1}else e.type;return e}async function c(e,t){return Ba(e,t,{handlers:i,bindings:s,modules:o})}const u={get history(){return t},get currentStep(){return r},get current(){return r>=0&&r<t.length?t[r]:void 0},async run(e){t.length=0,r=-1;try{const t=o?new Map(o.map(e=>[e.name,e])):void 0,n=Ht({bindings:s},t),r=function(e){return{body:fr(dr(jr(e,!0,void 0),{removeWhiteSpace:!0})),hasDebugData:!0}}(e),a=await async function(e,t,n,r,a){const s=(new AbortController).signal;return Ua(Ma(e.body,t),n,s,void 0,r,a)}(r,n,i,void 0,{values:s,modules:t});return l(a)}catch(e){return e instanceof n?{type:"error",error:e}:{type:"error",error:new n(`${e}`,void 0)}}},async stepForward(){if(r<t.length-1)return r++,{type:"suspended",snapshot:t[r].snapshot};if(r<0||r>=t.length)return{type:"error",error:new n("No current step to advance from",void 0)};const e=t[r];return l(await c(e.snapshot,e.step.value))},async stepBackward(){if(r<=0)return{type:"error",error:new n("Already at the beginning of execution history",void 0)};r--;return{type:"suspended",snapshot:t[r].snapshot}},async jumpTo(e){if(e<0||e>=t.length)return{type:"error",error:new n(`Step index ${e} out of range (0..${t.length-1})`,void 0)};r=e;return{type:"suspended",snapshot:t[r].snapshot}},async rerunFrom(e,a){if(e<0||e>=t.length)return{type:"error",error:new n(`Step index ${e} out of range (0..${t.length-1})`,void 0)};r=e,t.length=e+1;const s=t[e];return l(await c(s.snapshot,a))}};return u}export{Fa as createDebugger};
2
2
  //# sourceMappingURL=debug.esm.js.map