@motionscript/math 0.0.0-stage → 0.1.0-alpha.10

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 (335) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +49 -0
  4. package/README.md +389 -2
  5. package/dist/annotate/angle-mark.d.ts +96 -0
  6. package/dist/annotate/angle-mark.d.ts.map +1 -0
  7. package/dist/annotate/angle-mark.js +97 -0
  8. package/dist/annotate/angle-mark.js.map +1 -0
  9. package/dist/annotate/curly-brace.d.ts +115 -0
  10. package/dist/annotate/curly-brace.d.ts.map +1 -0
  11. package/dist/annotate/curly-brace.js +99 -0
  12. package/dist/annotate/curly-brace.js.map +1 -0
  13. package/dist/annotate/emphasis-mark.d.ts +80 -0
  14. package/dist/annotate/emphasis-mark.d.ts.map +1 -0
  15. package/dist/annotate/emphasis-mark.js +80 -0
  16. package/dist/annotate/emphasis-mark.js.map +1 -0
  17. package/dist/browser/THIRD_PARTY_LICENSES.txt +420 -0
  18. package/dist/browser/chunks/chunk-IRZCG6PM.js +2 -0
  19. package/dist/browser/chunks/chunk-IRZCG6PM.js.map +7 -0
  20. package/dist/browser/chunks/chunk-WMVW6ZIV.js +2 -0
  21. package/dist/browser/chunks/chunk-WMVW6ZIV.js.map +7 -0
  22. package/dist/browser/chunks/mathjax-WV55AC2P.js +61 -0
  23. package/dist/browser/chunks/mathjax-WV55AC2P.js.map +7 -0
  24. package/dist/browser/index.js +2 -0
  25. package/dist/browser/index.js.map +7 -0
  26. package/dist/browser/kit.js +2 -0
  27. package/dist/browser/kit.js.map +7 -0
  28. package/dist/browser/manifest.json +30 -0
  29. package/dist/browser/tex.js +2 -0
  30. package/dist/browser/tex.js.map +7 -0
  31. package/dist/engine.d.ts +71 -0
  32. package/dist/engine.d.ts.map +1 -0
  33. package/dist/engine.js +45 -0
  34. package/dist/engine.js.map +1 -0
  35. package/dist/index.d.ts +30 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +30 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/kit/brace.d.ts +8 -0
  40. package/dist/kit/brace.d.ts.map +1 -0
  41. package/dist/kit/brace.js +36 -0
  42. package/dist/kit/brace.js.map +1 -0
  43. package/dist/kit/cache.d.ts +30 -0
  44. package/dist/kit/cache.d.ts.map +1 -0
  45. package/dist/kit/cache.js +53 -0
  46. package/dist/kit/cache.js.map +1 -0
  47. package/dist/kit/component.d.ts +51 -0
  48. package/dist/kit/component.d.ts.map +1 -0
  49. package/dist/kit/component.js +30 -0
  50. package/dist/kit/component.js.map +1 -0
  51. package/dist/kit/contour.d.ts +8 -0
  52. package/dist/kit/contour.d.ts.map +1 -0
  53. package/dist/kit/contour.js +93 -0
  54. package/dist/kit/contour.js.map +1 -0
  55. package/dist/kit/coords.d.ts +69 -0
  56. package/dist/kit/coords.d.ts.map +1 -0
  57. package/dist/kit/coords.js +224 -0
  58. package/dist/kit/coords.js.map +1 -0
  59. package/dist/kit/curve.d.ts +28 -0
  60. package/dist/kit/curve.d.ts.map +1 -0
  61. package/dist/kit/curve.js +29 -0
  62. package/dist/kit/curve.js.map +1 -0
  63. package/dist/kit/equation.d.ts +61 -0
  64. package/dist/kit/equation.d.ts.map +1 -0
  65. package/dist/kit/equation.js +168 -0
  66. package/dist/kit/equation.js.map +1 -0
  67. package/dist/kit/equation3d.d.ts +50 -0
  68. package/dist/kit/equation3d.d.ts.map +1 -0
  69. package/dist/kit/equation3d.js +103 -0
  70. package/dist/kit/equation3d.js.map +1 -0
  71. package/dist/kit/expression.d.ts +35 -0
  72. package/dist/kit/expression.d.ts.map +1 -0
  73. package/dist/kit/expression.js +124 -0
  74. package/dist/kit/expression.js.map +1 -0
  75. package/dist/kit/field-mark.d.ts +79 -0
  76. package/dist/kit/field-mark.d.ts.map +1 -0
  77. package/dist/kit/field-mark.js +109 -0
  78. package/dist/kit/field-mark.js.map +1 -0
  79. package/dist/kit/field.d.ts +14 -0
  80. package/dist/kit/field.d.ts.map +1 -0
  81. package/dist/kit/field.js +46 -0
  82. package/dist/kit/field.js.map +1 -0
  83. package/dist/kit/follow.d.ts +109 -0
  84. package/dist/kit/follow.d.ts.map +1 -0
  85. package/dist/kit/follow.js +163 -0
  86. package/dist/kit/follow.js.map +1 -0
  87. package/dist/kit/furniture.d.ts +32 -0
  88. package/dist/kit/furniture.d.ts.map +1 -0
  89. package/dist/kit/furniture.js +92 -0
  90. package/dist/kit/furniture.js.map +1 -0
  91. package/dist/kit/geometry.d.ts +13 -0
  92. package/dist/kit/geometry.d.ts.map +1 -0
  93. package/dist/kit/geometry.js +54 -0
  94. package/dist/kit/geometry.js.map +1 -0
  95. package/dist/kit/graph.d.ts +46 -0
  96. package/dist/kit/graph.d.ts.map +1 -0
  97. package/dist/kit/graph.js +90 -0
  98. package/dist/kit/graph.js.map +1 -0
  99. package/dist/kit/mark.d.ts +72 -0
  100. package/dist/kit/mark.d.ts.map +1 -0
  101. package/dist/kit/mark.js +87 -0
  102. package/dist/kit/mark.js.map +1 -0
  103. package/dist/kit/part-fills.d.ts +23 -0
  104. package/dist/kit/part-fills.d.ts.map +1 -0
  105. package/dist/kit/part-fills.js +46 -0
  106. package/dist/kit/part-fills.js.map +1 -0
  107. package/dist/kit/place.d.ts +20 -0
  108. package/dist/kit/place.d.ts.map +1 -0
  109. package/dist/kit/place.js +66 -0
  110. package/dist/kit/place.js.map +1 -0
  111. package/dist/kit/sampler.d.ts +17 -0
  112. package/dist/kit/sampler.d.ts.map +1 -0
  113. package/dist/kit/sampler.js +250 -0
  114. package/dist/kit/sampler.js.map +1 -0
  115. package/dist/kit/scale.d.ts +12 -0
  116. package/dist/kit/scale.d.ts.map +1 -0
  117. package/dist/kit/scale.js +37 -0
  118. package/dist/kit/scale.js.map +1 -0
  119. package/dist/kit/source.d.ts +22 -0
  120. package/dist/kit/source.d.ts.map +1 -0
  121. package/dist/kit/source.js +45 -0
  122. package/dist/kit/source.js.map +1 -0
  123. package/dist/kit/system.d.ts +31 -0
  124. package/dist/kit/system.d.ts.map +1 -0
  125. package/dist/kit/system.js +71 -0
  126. package/dist/kit/system.js.map +1 -0
  127. package/dist/kit/ticks.d.ts +19 -0
  128. package/dist/kit/ticks.d.ts.map +1 -0
  129. package/dist/kit/ticks.js +78 -0
  130. package/dist/kit/ticks.js.map +1 -0
  131. package/dist/kit/withdrawn.d.ts +9 -0
  132. package/dist/kit/withdrawn.d.ts.map +1 -0
  133. package/dist/kit/withdrawn.js +9 -0
  134. package/dist/kit/withdrawn.js.map +1 -0
  135. package/dist/marks/curve-area.d.ts +51 -0
  136. package/dist/marks/curve-area.d.ts.map +1 -0
  137. package/dist/marks/curve-area.js +59 -0
  138. package/dist/marks/curve-area.js.map +1 -0
  139. package/dist/marks/drop-lines.d.ts +57 -0
  140. package/dist/marks/drop-lines.d.ts.map +1 -0
  141. package/dist/marks/drop-lines.js +43 -0
  142. package/dist/marks/drop-lines.js.map +1 -0
  143. package/dist/marks/plot-point.d.ts +71 -0
  144. package/dist/marks/plot-point.d.ts.map +1 -0
  145. package/dist/marks/plot-point.js +71 -0
  146. package/dist/marks/plot-point.js.map +1 -0
  147. package/dist/marks/riemann-sum.d.ts +58 -0
  148. package/dist/marks/riemann-sum.d.ts.map +1 -0
  149. package/dist/marks/riemann-sum.js +63 -0
  150. package/dist/marks/riemann-sum.js.map +1 -0
  151. package/dist/marks/tangent-line.d.ts +71 -0
  152. package/dist/marks/tangent-line.d.ts.map +1 -0
  153. package/dist/marks/tangent-line.js +89 -0
  154. package/dist/marks/tangent-line.js.map +1 -0
  155. package/dist/marks/vector-arrow.d.ts +60 -0
  156. package/dist/marks/vector-arrow.d.ts.map +1 -0
  157. package/dist/marks/vector-arrow.js +67 -0
  158. package/dist/marks/vector-arrow.js.map +1 -0
  159. package/dist/nodes.d.ts +43 -0
  160. package/dist/nodes.d.ts.map +1 -0
  161. package/dist/nodes.js +57 -0
  162. package/dist/nodes.js.map +1 -0
  163. package/dist/plots/function-plot.d.ts +159 -0
  164. package/dist/plots/function-plot.d.ts.map +1 -0
  165. package/dist/plots/function-plot.js +184 -0
  166. package/dist/plots/function-plot.js.map +1 -0
  167. package/dist/plots/points-plot.d.ts +64 -0
  168. package/dist/plots/points-plot.d.ts.map +1 -0
  169. package/dist/plots/points-plot.js +72 -0
  170. package/dist/plots/points-plot.js.map +1 -0
  171. package/dist/plots/stream-lines.d.ts +76 -0
  172. package/dist/plots/stream-lines.d.ts.map +1 -0
  173. package/dist/plots/stream-lines.js +122 -0
  174. package/dist/plots/stream-lines.js.map +1 -0
  175. package/dist/plots/traced-path.d.ts +70 -0
  176. package/dist/plots/traced-path.d.ts.map +1 -0
  177. package/dist/plots/traced-path.js +41 -0
  178. package/dist/plots/traced-path.js.map +1 -0
  179. package/dist/plots/vector-field.d.ts +60 -0
  180. package/dist/plots/vector-field.d.ts.map +1 -0
  181. package/dist/plots/vector-field.js +77 -0
  182. package/dist/plots/vector-field.js.map +1 -0
  183. package/dist/structures/graph-layout.d.ts +11 -0
  184. package/dist/structures/graph-layout.d.ts.map +1 -0
  185. package/dist/structures/graph-layout.js +135 -0
  186. package/dist/structures/graph-layout.js.map +1 -0
  187. package/dist/structures/network-graph.d.ts +174 -0
  188. package/dist/structures/network-graph.d.ts.map +1 -0
  189. package/dist/structures/network-graph.js +240 -0
  190. package/dist/structures/network-graph.js.map +1 -0
  191. package/dist/structures/sample-space.d.ts +114 -0
  192. package/dist/structures/sample-space.d.ts.map +1 -0
  193. package/dist/structures/sample-space.js +161 -0
  194. package/dist/structures/sample-space.js.map +1 -0
  195. package/dist/systems/axes2d.d.ts +197 -0
  196. package/dist/systems/axes2d.d.ts.map +1 -0
  197. package/dist/systems/axes2d.js +157 -0
  198. package/dist/systems/axes2d.js.map +1 -0
  199. package/dist/systems/number-line.d.ts +101 -0
  200. package/dist/systems/number-line.d.ts.map +1 -0
  201. package/dist/systems/number-line.js +91 -0
  202. package/dist/systems/number-line.js.map +1 -0
  203. package/dist/systems/number-plane.d.ts +168 -0
  204. package/dist/systems/number-plane.d.ts.map +1 -0
  205. package/dist/systems/number-plane.js +186 -0
  206. package/dist/systems/number-plane.js.map +1 -0
  207. package/dist/systems/polar-plane.d.ts +98 -0
  208. package/dist/systems/polar-plane.d.ts.map +1 -0
  209. package/dist/systems/polar-plane.js +139 -0
  210. package/dist/systems/polar-plane.js.map +1 -0
  211. package/dist/tex/geometry.d.ts +85 -0
  212. package/dist/tex/geometry.d.ts.map +1 -0
  213. package/dist/tex/geometry.js +632 -0
  214. package/dist/tex/geometry.js.map +1 -0
  215. package/dist/tex/index.d.ts +11 -0
  216. package/dist/tex/index.d.ts.map +1 -0
  217. package/dist/tex/index.js +10 -0
  218. package/dist/tex/index.js.map +1 -0
  219. package/dist/tex/mathjax.d.ts +33 -0
  220. package/dist/tex/mathjax.d.ts.map +1 -0
  221. package/dist/tex/mathjax.js +74 -0
  222. package/dist/tex/mathjax.js.map +1 -0
  223. package/dist/tex/matrix.d.ts +101 -0
  224. package/dist/tex/matrix.d.ts.map +1 -0
  225. package/dist/tex/matrix.js +56 -0
  226. package/dist/tex/matrix.js.map +1 -0
  227. package/dist/tex/node.d.ts +98 -0
  228. package/dist/tex/node.d.ts.map +1 -0
  229. package/dist/tex/node.js +25 -0
  230. package/dist/tex/node.js.map +1 -0
  231. package/dist/tex/tween.d.ts +50 -0
  232. package/dist/tex/tween.d.ts.map +1 -0
  233. package/dist/tex/tween.js +253 -0
  234. package/dist/tex/tween.js.map +1 -0
  235. package/dist/tex/typeset.d.ts +133 -0
  236. package/dist/tex/typeset.d.ts.map +1 -0
  237. package/dist/tex/typeset.js +403 -0
  238. package/dist/tex/typeset.js.map +1 -0
  239. package/dist/three/axes3d.d.ts +247 -0
  240. package/dist/three/axes3d.d.ts.map +1 -0
  241. package/dist/three/axes3d.js +187 -0
  242. package/dist/three/axes3d.js.map +1 -0
  243. package/dist/three/curve-plot3d.d.ts +126 -0
  244. package/dist/three/curve-plot3d.d.ts.map +1 -0
  245. package/dist/three/curve-plot3d.js +109 -0
  246. package/dist/three/curve-plot3d.js.map +1 -0
  247. package/dist/three/entries.d.ts +17 -0
  248. package/dist/three/entries.d.ts.map +1 -0
  249. package/dist/three/entries.js +15 -0
  250. package/dist/three/entries.js.map +1 -0
  251. package/dist/three/label3d.d.ts +11 -0
  252. package/dist/three/label3d.d.ts.map +1 -0
  253. package/dist/three/label3d.js +42 -0
  254. package/dist/three/label3d.js.map +1 -0
  255. package/dist/three/plot-point3d.d.ts +99 -0
  256. package/dist/three/plot-point3d.d.ts.map +1 -0
  257. package/dist/three/plot-point3d.js +34 -0
  258. package/dist/three/plot-point3d.js.map +1 -0
  259. package/dist/three/space.d.ts +43 -0
  260. package/dist/three/space.d.ts.map +1 -0
  261. package/dist/three/space.js +58 -0
  262. package/dist/three/space.js.map +1 -0
  263. package/dist/three/surface-plot3d.d.ts +207 -0
  264. package/dist/three/surface-plot3d.d.ts.map +1 -0
  265. package/dist/three/surface-plot3d.js +261 -0
  266. package/dist/three/surface-plot3d.js.map +1 -0
  267. package/dist/three/vector-arrow3d.d.ts +96 -0
  268. package/dist/three/vector-arrow3d.d.ts.map +1 -0
  269. package/dist/three/vector-arrow3d.js +53 -0
  270. package/dist/three/vector-arrow3d.js.map +1 -0
  271. package/package.json +80 -3
  272. package/registry.json +251 -0
  273. package/src/annotate/angle-mark.ts +137 -0
  274. package/src/annotate/curly-brace.ts +148 -0
  275. package/src/annotate/emphasis-mark.ts +118 -0
  276. package/src/engine.ts +86 -0
  277. package/src/index.ts +29 -0
  278. package/src/kit/brace.ts +37 -0
  279. package/src/kit/cache.ts +61 -0
  280. package/src/kit/component.ts +57 -0
  281. package/src/kit/contour.ts +94 -0
  282. package/src/kit/coords.ts +278 -0
  283. package/src/kit/curve.ts +47 -0
  284. package/src/kit/equation.ts +181 -0
  285. package/src/kit/equation3d.ts +137 -0
  286. package/src/kit/expression.ts +159 -0
  287. package/src/kit/field-mark.ts +171 -0
  288. package/src/kit/field.ts +50 -0
  289. package/src/kit/follow.ts +229 -0
  290. package/src/kit/furniture.ts +113 -0
  291. package/src/kit/geometry.ts +49 -0
  292. package/src/kit/graph.ts +116 -0
  293. package/src/kit/mark.ts +152 -0
  294. package/src/kit/part-fills.ts +61 -0
  295. package/src/kit/place.ts +77 -0
  296. package/src/kit/sampler.ts +281 -0
  297. package/src/kit/scale.ts +39 -0
  298. package/src/kit/source.ts +57 -0
  299. package/src/kit/system.ts +105 -0
  300. package/src/kit/ticks.ts +85 -0
  301. package/src/kit/withdrawn.ts +8 -0
  302. package/src/marks/curve-area.ts +89 -0
  303. package/src/marks/drop-lines.ts +71 -0
  304. package/src/marks/plot-point.ts +102 -0
  305. package/src/marks/riemann-sum.ts +99 -0
  306. package/src/marks/tangent-line.ts +119 -0
  307. package/src/marks/vector-arrow.ts +98 -0
  308. package/src/nodes.ts +99 -0
  309. package/src/plots/function-plot.ts +220 -0
  310. package/src/plots/points-plot.ts +103 -0
  311. package/src/plots/stream-lines.ts +160 -0
  312. package/src/plots/traced-path.ts +70 -0
  313. package/src/plots/vector-field.ts +107 -0
  314. package/src/structures/graph-layout.ts +145 -0
  315. package/src/structures/network-graph.ts +291 -0
  316. package/src/structures/sample-space.ts +210 -0
  317. package/src/systems/axes2d.ts +226 -0
  318. package/src/systems/number-line.ts +130 -0
  319. package/src/systems/number-plane.ts +232 -0
  320. package/src/systems/polar-plane.ts +177 -0
  321. package/src/tex/geometry.ts +703 -0
  322. package/src/tex/index.ts +15 -0
  323. package/src/tex/mathjax.ts +82 -0
  324. package/src/tex/matrix.ts +97 -0
  325. package/src/tex/node.ts +74 -0
  326. package/src/tex/tween.ts +308 -0
  327. package/src/tex/typeset.ts +461 -0
  328. package/src/three/axes3d.ts +267 -0
  329. package/src/three/curve-plot3d.ts +146 -0
  330. package/src/three/entries.ts +42 -0
  331. package/src/three/label3d.ts +52 -0
  332. package/src/three/plot-point3d.ts +63 -0
  333. package/src/three/space.ts +92 -0
  334. package/src/three/surface-plot3d.ts +318 -0
  335. package/src/three/vector-arrow3d.ts +88 -0
@@ -0,0 +1,168 @@
1
+ import { expressionOps } from "@motionscript/sdk";
2
+ import { createBoundedCache } from "./cache.js";
3
+ import { compileExpressionCached, MATH_DIALECT } from "./expression.js";
4
+ /** The free variable each kind is sampled over, for a host's help text. */
5
+ export const EQUATION_VARIABLES = {
6
+ function: ["x"],
7
+ polar: ["theta"],
8
+ parametric: ["t"],
9
+ implicit: ["x", "y"],
10
+ };
11
+ const parsed = createBoundedCache(256);
12
+ /**
13
+ * `source` as an {@link Equation}, or the reason it is not one. Memoised, so an
14
+ * unchanged equation is the identical object and a geometry cache can key on it.
15
+ */
16
+ export function parseEquation(source, params = []) {
17
+ const key = `${params.join(",")}|${source}`;
18
+ const hit = parsed.get(key);
19
+ if (hit !== undefined)
20
+ return hit;
21
+ let result;
22
+ try {
23
+ result = read(source.trim(), params);
24
+ }
25
+ catch (error) {
26
+ result = error instanceof Error ? error : new Error(String(error));
27
+ }
28
+ parsed.set(key, result);
29
+ return result;
30
+ }
31
+ /**
32
+ * Why `source` will not plot, or `null` when it will. An empty one is not an
33
+ * error (nobody has written it yet), and neither is a name it does not know:
34
+ * that is a named value, see {@link equationParams}.
35
+ */
36
+ export function equationError(source) {
37
+ if (source.trim() === "")
38
+ return null;
39
+ const equation = parseEquation(source, equationParams(source));
40
+ return equation instanceof Error ? equation.message : null;
41
+ }
42
+ /** A name that is always a variable of some kind of equation, so never a named value. */
43
+ const VARIABLE_NAMES = new Set(["r", ...Object.values(EQUATION_VARIABLES).flat()]);
44
+ const named = createBoundedCache(256);
45
+ /**
46
+ * Every name `source` reads, in the order it first names them, variables
47
+ * included. Empty for text that does not parse.
48
+ */
49
+ export function equationNames(source) {
50
+ const hit = named.get(source);
51
+ if (hit !== undefined)
52
+ return hit;
53
+ const names = new Set();
54
+ const text = source.trim();
55
+ try {
56
+ for (const part of splitTuple(text) ?? splitTopLevel(text, "=")) {
57
+ collectNames(expressionOps.parse(part.trim(), MATH_DIALECT).root, names);
58
+ }
59
+ }
60
+ catch {
61
+ names.clear();
62
+ }
63
+ const result = [...names];
64
+ named.set(source, result);
65
+ return result;
66
+ }
67
+ /**
68
+ * The named values `source` reads: every name that is not a variable, a
69
+ * function or a constant.
70
+ */
71
+ export function equationParams(source) {
72
+ return equationNames(source).filter((name) => !VARIABLE_NAMES.has(name));
73
+ }
74
+ function collectNames(node, into) {
75
+ switch (node.kind) {
76
+ case "ref":
77
+ into.add(node.name);
78
+ return;
79
+ case "unary":
80
+ collectNames(node.operand, into);
81
+ return;
82
+ case "binary":
83
+ collectNames(node.left, into);
84
+ collectNames(node.right, into);
85
+ return;
86
+ case "call":
87
+ for (const arg of node.args)
88
+ collectNames(arg, into);
89
+ return;
90
+ default:
91
+ }
92
+ }
93
+ function read(source, params) {
94
+ if (source === "")
95
+ throw new Error("Empty equation");
96
+ const compile = (text, variables) => {
97
+ const result = compileExpressionCached(text.trim(), variables, params);
98
+ if (result instanceof Error)
99
+ throw result;
100
+ return result;
101
+ };
102
+ const pair = splitTuple(source);
103
+ if (pair?.length === 2)
104
+ return { kind: "parametric", x: compile(pair[0], ["t"]), y: compile(pair[1], ["t"]) };
105
+ const sides = splitTopLevel(source, "=");
106
+ if (sides.length > 2)
107
+ throw new Error("An equation has one '='");
108
+ if (sides.length === 1)
109
+ return { kind: "function", of: "x", f: compile(source, ["x"]) };
110
+ const [left, right] = sides;
111
+ const subject = left.trim();
112
+ const implicit = () => {
113
+ const l = compile(left, ["x", "y"]);
114
+ const r = compile(right, ["x", "y"]);
115
+ return { kind: "implicit", f: (x, y, scope) => l(x, y, scope) - r(x, y, scope) };
116
+ };
117
+ if (subject === "r")
118
+ return { kind: "polar", f: compile(right, ["theta"]) };
119
+ if (subject === "y" || subject === "x") {
120
+ const of = subject === "y" ? "x" : "y";
121
+ // `y = x + y` names its own subject on the right, so it is not a function of one variable.
122
+ try {
123
+ return { kind: "function", of, f: compile(right, [of]) };
124
+ }
125
+ catch (error) {
126
+ try {
127
+ return implicit();
128
+ }
129
+ catch {
130
+ throw error;
131
+ }
132
+ }
133
+ }
134
+ return implicit();
135
+ }
136
+ /** `(a, b, …)` as its parts, or `null` when `source` is not one parenthesised list of two or more. */
137
+ export function splitTuple(source) {
138
+ if (!source.startsWith("(") || !source.endsWith(")"))
139
+ return null;
140
+ let depth = 0;
141
+ for (let i = 0; i < source.length - 1; i++) {
142
+ if (source[i] === "(")
143
+ depth++;
144
+ else if (source[i] === ")" && --depth === 0)
145
+ return null;
146
+ }
147
+ const parts = splitTopLevel(source.slice(1, -1), ",");
148
+ return parts.length >= 2 ? parts : null;
149
+ }
150
+ export function splitTopLevel(source, separator) {
151
+ const parts = [];
152
+ let depth = 0;
153
+ let from = 0;
154
+ for (let i = 0; i < source.length; i++) {
155
+ const c = source[i];
156
+ if (c === "(")
157
+ depth++;
158
+ else if (c === ")")
159
+ depth--;
160
+ else if (c === separator && depth === 0) {
161
+ parts.push(source.slice(from, i));
162
+ from = i + 1;
163
+ }
164
+ }
165
+ parts.push(source.slice(from));
166
+ return parts;
167
+ }
168
+ //# sourceMappingURL=equation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"equation.js","sourceRoot":"","sources":["../../src/kit/equation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAuB,MAAM,mBAAmB,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAE,uBAAuB,EAAE,YAAY,EAA2B,MAAM,cAAc,CAAC;AAoB9F,2EAA2E;AAC3E,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAC9B,QAAQ,EAAE,CAAC,GAAG,CAAC;IACf,KAAK,EAAE,CAAC,OAAO,CAAC;IAChB,UAAU,EAAE,CAAC,GAAG,CAAC;IACjB,QAAQ,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC;CACwC,CAAC;AAEjE,MAAM,MAAM,GAAG,kBAAkB,CAAmB,GAAG,CAAC,CAAC;AAEzD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AAI,CAAC,KAAK,GAAG;YAAE,KAAK,EAAE,CAAC;aACvB,IAAI,CAAC,KAAK,SAAS,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;YACtC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;YAClC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QACjB,CAAC;IACL,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IAC/B,OAAO,KAAK,CAAC;AACjB,CAAC","sourcesContent":["import { expressionOps, type ExpressionNode } from \"@motionscript/sdk\";\nimport { createBoundedCache } from \"./cache\";\nimport { compileExpressionCached, MATH_DIALECT, type CompiledExpression } from \"./expression\";\n\n/**\n * A plotted equation, read the way it is written rather than by a `kind` prop:\n *\n * | Written as | Is |\n * |---|---|\n * | `sin(x)`, `y = sin(x)` | a function of `x` |\n * | `x = y^2` | a function of `y` |\n * | `r = 1 + cos(theta)` | polar, in `theta` |\n * | `(cos(t), sin(t))` | parametric, in `t` |\n * | `x^2 + y^2 = 4` | implicit, in `x` and `y` |\n */\nexport type Equation =\n | { kind: \"function\"; of: \"x\" | \"y\"; f: CompiledExpression }\n | { kind: \"polar\"; f: CompiledExpression }\n | { kind: \"parametric\"; x: CompiledExpression; y: CompiledExpression }\n /** Drawn where `f(x, y)` is zero. */\n | { kind: \"implicit\"; f: CompiledExpression };\n\n/** The free variable each kind is sampled over, for a host's help text. */\nexport const EQUATION_VARIABLES = {\n function: [\"x\"],\n polar: [\"theta\"],\n parametric: [\"t\"],\n implicit: [\"x\", \"y\"],\n} as const satisfies Record<Equation[\"kind\"], readonly string[]>;\n\nconst parsed = createBoundedCache<Equation | Error>(256);\n\n/**\n * `source` as an {@link Equation}, or the reason it is not one. Memoised, so an\n * unchanged equation is the identical object and a geometry cache can key on it.\n */\nexport function parseEquation(source: string, params: readonly string[] = []): Equation | Error {\n const key = `${params.join(\",\")}|${source}`;\n const hit = parsed.get(key);\n if (hit !== undefined) return hit;\n let result: Equation | Error;\n try {\n result = read(source.trim(), params);\n } catch (error) {\n result = error instanceof Error ? error : new Error(String(error));\n }\n parsed.set(key, result);\n return result;\n}\n\n/**\n * Why `source` will not plot, or `null` when it will. An empty one is not an\n * error (nobody has written it yet), and neither is a name it does not know:\n * that is a named value, see {@link equationParams}.\n */\nexport function equationError(source: string): string | null {\n if (source.trim() === \"\") return null;\n const equation = parseEquation(source, equationParams(source));\n return equation instanceof Error ? equation.message : null;\n}\n\n/** A name that is always a variable of some kind of equation, so never a named value. */\nconst VARIABLE_NAMES: ReadonlySet<string> = new Set([\"r\", ...Object.values(EQUATION_VARIABLES).flat()]);\n\nconst named = createBoundedCache<readonly string[]>(256);\n\n/**\n * Every name `source` reads, in the order it first names them, variables\n * included. Empty for text that does not parse.\n */\nexport function equationNames(source: string): readonly string[] {\n const hit = named.get(source);\n if (hit !== undefined) return hit;\n const names = new Set<string>();\n const text = source.trim();\n try {\n for (const part of splitTuple(text) ?? splitTopLevel(text, \"=\")) {\n collectNames(expressionOps.parse(part.trim(), MATH_DIALECT).root, names);\n }\n } catch {\n names.clear();\n }\n const result = [...names];\n named.set(source, result);\n return result;\n}\n\n/**\n * The named values `source` reads: every name that is not a variable, a\n * function or a constant.\n */\nexport function equationParams(source: string): readonly string[] {\n return equationNames(source).filter((name) => !VARIABLE_NAMES.has(name));\n}\n\nfunction collectNames(node: ExpressionNode, into: Set<string>): void {\n switch (node.kind) {\n case \"ref\":\n into.add(node.name);\n return;\n case \"unary\":\n collectNames(node.operand, into);\n return;\n case \"binary\":\n collectNames(node.left, into);\n collectNames(node.right, into);\n return;\n case \"call\":\n for (const arg of node.args) collectNames(arg, into);\n return;\n default:\n }\n}\n\nfunction read(source: string, params: readonly string[]): Equation {\n if (source === \"\") throw new Error(\"Empty equation\");\n const compile = (text: string, variables: readonly string[]): CompiledExpression => {\n const result = compileExpressionCached(text.trim(), variables, params);\n if (result instanceof Error) throw result;\n return result;\n };\n\n const pair = splitTuple(source);\n if (pair?.length === 2) return { kind: \"parametric\", x: compile(pair[0], [\"t\"]), y: compile(pair[1], [\"t\"]) };\n\n const sides = splitTopLevel(source, \"=\");\n if (sides.length > 2) throw new Error(\"An equation has one '='\");\n if (sides.length === 1) return { kind: \"function\", of: \"x\", f: compile(source, [\"x\"]) };\n\n const [left, right] = sides;\n const subject = left.trim();\n const implicit = (): Equation => {\n const l = compile(left, [\"x\", \"y\"]);\n const r = compile(right, [\"x\", \"y\"]);\n return { kind: \"implicit\", f: (x, y, scope) => l(x, y, scope) - r(x, y, scope) };\n };\n if (subject === \"r\") return { kind: \"polar\", f: compile(right, [\"theta\"]) };\n if (subject === \"y\" || subject === \"x\") {\n const of = subject === \"y\" ? \"x\" : \"y\";\n // `y = x + y` names its own subject on the right, so it is not a function of one variable.\n try {\n return { kind: \"function\", of, f: compile(right, [of]) };\n } catch (error) {\n try {\n return implicit();\n } catch {\n throw error;\n }\n }\n }\n return implicit();\n}\n\n/** `(a, b, …)` as its parts, or `null` when `source` is not one parenthesised list of two or more. */\nexport function splitTuple(source: string): string[] | null {\n if (!source.startsWith(\"(\") || !source.endsWith(\")\")) return null;\n let depth = 0;\n for (let i = 0; i < source.length - 1; i++) {\n if (source[i] === \"(\") depth++;\n else if (source[i] === \")\" && --depth === 0) return null;\n }\n const parts = splitTopLevel(source.slice(1, -1), \",\");\n return parts.length >= 2 ? parts : null;\n}\n\nexport function splitTopLevel(source: string, separator: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let from = 0;\n for (let i = 0; i < source.length; i++) {\n const c = source[i];\n if (c === \"(\") depth++;\n else if (c === \")\") depth--;\n else if (c === separator && depth === 0) {\n parts.push(source.slice(from, i));\n from = i + 1;\n }\n }\n parts.push(source.slice(from));\n return parts;\n}\n"]}
@@ -0,0 +1,50 @@
1
+ import { type CompiledExpression } from "./expression.js";
2
+ /**
3
+ * A surface's equation, read the way it is written:
4
+ *
5
+ * | Written as | Is |
6
+ * |---|---|
7
+ * | `sin(x) * cos(y)`, `z = x^2 - y^2` | a height over `x` and `y` |
8
+ * | `(cos(u) sin(v), sin(u) sin(v), cos(v))` | parametric, in `u` and `v` |
9
+ */
10
+ export type SurfaceEquation = {
11
+ kind: "height";
12
+ f: CompiledExpression;
13
+ } | {
14
+ kind: "parametric";
15
+ x: CompiledExpression;
16
+ y: CompiledExpression;
17
+ z: CompiledExpression;
18
+ };
19
+ /** A curve through space, three parts in `t`: `(cos(t), sin(t), t / 4)`. */
20
+ export interface SpaceCurveEquation {
21
+ x: CompiledExpression;
22
+ y: CompiledExpression;
23
+ z: CompiledExpression;
24
+ }
25
+ /** What each 3D form is written over, for a host's help text. */
26
+ export declare const EQUATION_VARIABLES_3D: {
27
+ readonly height: readonly ["x", "y"];
28
+ readonly surface: readonly ["u", "v"];
29
+ readonly spaceCurve: readonly ["t"];
30
+ };
31
+ /** The named values a surface's equation reads: every name that is not one of its variables. */
32
+ export declare function surfaceParams(source: string): readonly string[];
33
+ /** The named values a space curve's equation reads. */
34
+ export declare function spaceCurveParams(source: string): readonly string[];
35
+ /** `source` as a surface, or the reason it is not one. Memoised, so an unchanged equation is the identical object. */
36
+ export declare function parseSurface(source: string, params?: readonly string[]): SurfaceEquation | Error;
37
+ /** `source` as a space curve, or the reason it is not one. */
38
+ export declare function parseSpaceCurve(source: string, params?: readonly string[]): SpaceCurveEquation | Error;
39
+ /** Why `source` will not draw as a surface, or `null`; empty text is not an error. */
40
+ export declare function surfaceError(source: string): string | null;
41
+ /** Why `source` will not draw as a space curve, or `null`. */
42
+ export declare function spaceCurveError(source: string): string | null;
43
+ /** How a host checks an equation as it is typed, and finds its named values, by the `kind` its property declares. */
44
+ export interface EquationLanguage {
45
+ error(source: string): string | null;
46
+ params(source: string): readonly string[];
47
+ variables: readonly string[];
48
+ }
49
+ export declare const EQUATION_KINDS: Readonly<Record<"equation" | "surfaceEquation" | "spaceCurveEquation" | "fieldEquation", EquationLanguage>>;
50
+ //# sourceMappingURL=equation3d.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"equation3d.d.ts","sourceRoot":"","sources":["../../src/kit/equation3d.ts"],"names":[],"mappings":"AAEA,OAAO,EAA2B,KAAK,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAGhF;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,GACrB;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,CAAC,EAAE,kBAAkB,CAAA;CAAE,GACzC;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,CAAC,EAAE,kBAAkB,CAAC;IAAC,CAAC,EAAE,kBAAkB,CAAC;IAAC,CAAC,EAAE,kBAAkB,CAAA;CAAE,CAAC;AAElG,4EAA4E;AAC5E,MAAM,WAAW,kBAAkB;IAC/B,CAAC,EAAE,kBAAkB,CAAC;IACtB,CAAC,EAAE,kBAAkB,CAAC;IACtB,CAAC,EAAE,kBAAkB,CAAC;CACzB;AAED,iEAAiE;AACjE,eAAO,MAAM,qBAAqB;;;;CAIxB,CAAC;AAQX,gGAAgG;AAChG,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAE/D;AAED,uDAAuD;AACvD,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAElE;AAED,sHAAsH;AACtH,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,GAAE,SAAS,MAAM,EAAO,GAAG,eAAe,GAAG,KAAK,CAcpG;AAED,8DAA8D;AAC9D,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,GAAE,SAAS,MAAM,EAAO,GAAG,kBAAkB,GAAG,KAAK,CAQ1G;AAED,sFAAsF;AACtF,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAI1D;AAED,8DAA8D;AAC9D,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAI7D;AA+BD,qHAAqH;AACrH,MAAM,WAAW,gBAAgB;IAC7B,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IACrC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;IAC1C,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;CAChC;AAED,eAAO,MAAM,cAAc,EAAE,QAAQ,CACjC,MAAM,CAAC,UAAU,GAAG,iBAAiB,GAAG,oBAAoB,GAAG,eAAe,EAAE,gBAAgB,CAAC,CAUpG,CAAC"}
@@ -0,0 +1,103 @@
1
+ import { createBoundedCache } from "./cache.js";
2
+ import { equationError, equationNames, equationParams, EQUATION_VARIABLES, splitTopLevel, splitTuple } from "./equation.js";
3
+ import { compileExpressionCached } from "./expression.js";
4
+ import { fieldError, fieldParams, FIELD_VARIABLES } from "./field.js";
5
+ /** What each 3D form is written over, for a host's help text. */
6
+ export const EQUATION_VARIABLES_3D = {
7
+ height: ["x", "y"],
8
+ surface: ["u", "v"],
9
+ spaceCurve: ["t"],
10
+ };
11
+ const SURFACE_NAMES = new Set(["x", "y", "z", "u", "v"]);
12
+ const SPACE_CURVE_NAMES = new Set(["t"]);
13
+ const surfaces = createBoundedCache(128);
14
+ const curves = createBoundedCache(128);
15
+ /** The named values a surface's equation reads: every name that is not one of its variables. */
16
+ export function surfaceParams(source) {
17
+ return equationNames(source).filter((name) => !SURFACE_NAMES.has(name));
18
+ }
19
+ /** The named values a space curve's equation reads. */
20
+ export function spaceCurveParams(source) {
21
+ return equationNames(source).filter((name) => !SPACE_CURVE_NAMES.has(name));
22
+ }
23
+ /** `source` as a surface, or the reason it is not one. Memoised, so an unchanged equation is the identical object. */
24
+ export function parseSurface(source, params = []) {
25
+ return memo(surfaces, source, params, (text) => {
26
+ const compile = compiler(params);
27
+ const parts = splitTuple(text);
28
+ if (parts) {
29
+ if (parts.length !== 3)
30
+ throw new Error("A parametric surface has three parts: (x, y, z)");
31
+ const [x, y, z] = parts.map((part) => compile(part, EQUATION_VARIABLES_3D.surface));
32
+ return { kind: "parametric", x, y, z };
33
+ }
34
+ const sides = splitTopLevel(text, "=");
35
+ if (sides.length > 2)
36
+ throw new Error("An equation has one '='");
37
+ if (sides.length === 2 && sides[0].trim() !== "z")
38
+ throw new Error("A surface is written z = …, or as three parts (x, y, z)");
39
+ return { kind: "height", f: compile(sides[sides.length - 1], EQUATION_VARIABLES_3D.height) };
40
+ });
41
+ }
42
+ /** `source` as a space curve, or the reason it is not one. */
43
+ export function parseSpaceCurve(source, params = []) {
44
+ return memo(curves, source, params, (text) => {
45
+ const compile = compiler(params);
46
+ const parts = splitTuple(text);
47
+ if (parts?.length !== 3)
48
+ throw new Error("A space curve has three parts: (x, y, z)");
49
+ const [x, y, z] = parts.map((part) => compile(part, EQUATION_VARIABLES_3D.spaceCurve));
50
+ return { x, y, z };
51
+ });
52
+ }
53
+ /** Why `source` will not draw as a surface, or `null`; empty text is not an error. */
54
+ export function surfaceError(source) {
55
+ if (source.trim() === "")
56
+ return null;
57
+ const equation = parseSurface(source, surfaceParams(source));
58
+ return equation instanceof Error ? equation.message : null;
59
+ }
60
+ /** Why `source` will not draw as a space curve, or `null`. */
61
+ export function spaceCurveError(source) {
62
+ if (source.trim() === "")
63
+ return null;
64
+ const equation = parseSpaceCurve(source, spaceCurveParams(source));
65
+ return equation instanceof Error ? equation.message : null;
66
+ }
67
+ function compiler(params) {
68
+ return (text, variables) => {
69
+ const result = compileExpressionCached(text.trim(), variables, params);
70
+ if (result instanceof Error)
71
+ throw result;
72
+ return result;
73
+ };
74
+ }
75
+ function memo(cache, source, params, read) {
76
+ const key = `${params.join(",")}|${source}`;
77
+ const hit = cache.get(key);
78
+ if (hit !== undefined)
79
+ return hit;
80
+ let result;
81
+ try {
82
+ const text = source.trim();
83
+ if (text === "")
84
+ throw new Error("Empty equation");
85
+ result = read(text);
86
+ }
87
+ catch (error) {
88
+ result = error instanceof Error ? error : new Error(String(error));
89
+ }
90
+ cache.set(key, result);
91
+ return result;
92
+ }
93
+ export const EQUATION_KINDS = {
94
+ equation: { error: equationError, params: equationParams, variables: [...new Set(Object.values(EQUATION_VARIABLES).flat())] },
95
+ surfaceEquation: {
96
+ error: surfaceError,
97
+ params: surfaceParams,
98
+ variables: [...EQUATION_VARIABLES_3D.height, ...EQUATION_VARIABLES_3D.surface],
99
+ },
100
+ spaceCurveEquation: { error: spaceCurveError, params: spaceCurveParams, variables: EQUATION_VARIABLES_3D.spaceCurve },
101
+ fieldEquation: { error: fieldError, params: fieldParams, variables: FIELD_VARIABLES },
102
+ };
103
+ //# sourceMappingURL=equation3d.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"equation3d.js","sourceRoot":"","sources":["../../src/kit/equation3d.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,cAAc,EAAE,kBAAkB,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACzH,OAAO,EAAE,uBAAuB,EAA2B,MAAM,cAAc,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAqBnE,iEAAiE;AACjE,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACjC,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC;IAClB,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC;IACnB,UAAU,EAAE,CAAC,GAAG,CAAC;CACX,CAAC;AAEX,MAAM,aAAa,GAAwB,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AAC9E,MAAM,iBAAiB,GAAwB,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAE9D,M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B,CAAC,CAAC;QACnD,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACvE,CAAC;IACD,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IACvB,OAAO,MAAM,CAAC;AAClB,CAAC;AASD,MAAM,CAAC,MAAM,cAAc,GAEvB;IACA,QAAQ,EAAE,EAAE,KAAK,EAAE,aAAa,EAAE,MAAM,EAAE,cAAc,EAAE,SAAS,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE;IAC7H,eAAe,EAAE;QACb,KAAK,EAAE,YAAY;QACnB,MAAM,EAAE,aAAa;QACrB,SAAS,EAAE,CAAC,GAAG,qBAAqB,CAAC,MAAM,EAAE,GAAG,qBAAqB,CAAC,OAAO,CAAC;KACjF;IACD,kBAAkB,EAAE,EAAE,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,gBAAgB,EAAE,SAAS,EAAE,qBAAqB,CAAC,UAAU,EAAE;IACrH,aAAa,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,eAAe,EAAE;CACxF,CAAC","sourcesContent":["import { createBoundedCache } from \"./cache\";\nimport { equationError, equationNames, equationParams, EQUATION_VARIABLES, splitTopLevel, splitTuple } from \"./equation\";\nimport { compileExpressionCached, type CompiledExpression } from \"./expression\";\nimport { fieldError, fieldParams, FIELD_VARIABLES } from \"./field\";\n\n/**\n * A surface's equation, read the way it is written:\n *\n * | Written as | Is |\n * |---|---|\n * | `sin(x) * cos(y)`, `z = x^2 - y^2` | a height over `x` and `y` |\n * | `(cos(u) sin(v), sin(u) sin(v), cos(v))` | parametric, in `u` and `v` |\n */\nexport type SurfaceEquation =\n | { kind: \"height\"; f: CompiledExpression }\n | { kind: \"parametric\"; x: CompiledExpression; y: CompiledExpression; z: CompiledExpression };\n\n/** A curve through space, three parts in `t`: `(cos(t), sin(t), t / 4)`. */\nexport interface SpaceCurveEquation {\n x: CompiledExpression;\n y: CompiledExpression;\n z: CompiledExpression;\n}\n\n/** What each 3D form is written over, for a host's help text. */\nexport const EQUATION_VARIABLES_3D = {\n height: [\"x\", \"y\"],\n surface: [\"u\", \"v\"],\n spaceCurve: [\"t\"],\n} as const;\n\nconst SURFACE_NAMES: ReadonlySet<string> = new Set([\"x\", \"y\", \"z\", \"u\", \"v\"]);\nconst SPACE_CURVE_NAMES: ReadonlySet<string> = new Set([\"t\"]);\n\nconst surfaces = createBoundedCache<SurfaceEquation | Error>(128);\nconst curves = createBoundedCache<SpaceCurveEquation | Error>(128);\n\n/** The named values a surface's equation reads: every name that is not one of its variables. */\nexport function surfaceParams(source: string): readonly string[] {\n return equationNames(source).filter((name) => !SURFACE_NAMES.has(name));\n}\n\n/** The named values a space curve's equation reads. */\nexport function spaceCurveParams(source: string): readonly string[] {\n return equationNames(source).filter((name) => !SPACE_CURVE_NAMES.has(name));\n}\n\n/** `source` as a surface, or the reason it is not one. Memoised, so an unchanged equation is the identical object. */\nexport function parseSurface(source: string, params: readonly string[] = []): SurfaceEquation | Error {\n return memo(surfaces, source, params, (text) => {\n const compile = compiler(params);\n const parts = splitTuple(text);\n if (parts) {\n if (parts.length !== 3) throw new Error(\"A parametric surface has three parts: (x, y, z)\");\n const [x, y, z] = parts.map((part) => compile(part, EQUATION_VARIABLES_3D.surface));\n return { kind: \"parametric\", x, y, z };\n }\n const sides = splitTopLevel(text, \"=\");\n if (sides.length > 2) throw new Error(\"An equation has one '='\");\n if (sides.length === 2 && sides[0].trim() !== \"z\") throw new Error(\"A surface is written z = …, or as three parts (x, y, z)\");\n return { kind: \"height\", f: compile(sides[sides.length - 1], EQUATION_VARIABLES_3D.height) };\n });\n}\n\n/** `source` as a space curve, or the reason it is not one. */\nexport function parseSpaceCurve(source: string, params: readonly string[] = []): SpaceCurveEquation | Error {\n return memo(curves, source, params, (text) => {\n const compile = compiler(params);\n const parts = splitTuple(text);\n if (parts?.length !== 3) throw new Error(\"A space curve has three parts: (x, y, z)\");\n const [x, y, z] = parts.map((part) => compile(part, EQUATION_VARIABLES_3D.spaceCurve));\n return { x, y, z };\n });\n}\n\n/** Why `source` will not draw as a surface, or `null`; empty text is not an error. */\nexport function surfaceError(source: string): string | null {\n if (source.trim() === \"\") return null;\n const equation = parseSurface(source, surfaceParams(source));\n return equation instanceof Error ? equation.message : null;\n}\n\n/** Why `source` will not draw as a space curve, or `null`. */\nexport function spaceCurveError(source: string): string | null {\n if (source.trim() === \"\") return null;\n const equation = parseSpaceCurve(source, spaceCurveParams(source));\n return equation instanceof Error ? equation.message : null;\n}\n\nfunction compiler(params: readonly string[]) {\n return (text: string, variables: readonly string[]): CompiledExpression => {\n const result = compileExpressionCached(text.trim(), variables, params);\n if (result instanceof Error) throw result;\n return result;\n };\n}\n\nfunction memo<T extends object>(\n cache: ReturnType<typeof createBoundedCache<T | Error>>,\n source: string,\n params: readonly string[],\n read: (text: string) => T,\n): T | Error {\n const key = `${params.join(\",\")}|${source}`;\n const hit = cache.get(key);\n if (hit !== undefined) return hit;\n let result: T | Error;\n try {\n const text = source.trim();\n if (text === \"\") throw new Error(\"Empty equation\");\n result = read(text);\n } catch (error) {\n result = error instanceof Error ? error : new Error(String(error));\n }\n cache.set(key, result);\n return result;\n}\n\n/** How a host checks an equation as it is typed, and finds its named values, by the `kind` its property declares. */\nexport interface EquationLanguage {\n error(source: string): string | null;\n params(source: string): readonly string[];\n variables: readonly string[];\n}\n\nexport const EQUATION_KINDS: Readonly<\n Record<\"equation\" | \"surfaceEquation\" | \"spaceCurveEquation\" | \"fieldEquation\", EquationLanguage>\n> = {\n equation: { error: equationError, params: equationParams, variables: [...new Set(Object.values(EQUATION_VARIABLES).flat())] },\n surfaceEquation: {\n error: surfaceError,\n params: surfaceParams,\n variables: [...EQUATION_VARIABLES_3D.height, ...EQUATION_VARIABLES_3D.surface],\n },\n spaceCurveEquation: { error: spaceCurveError, params: spaceCurveParams, variables: EQUATION_VARIABLES_3D.spaceCurve },\n fieldEquation: { error: fieldError, params: fieldParams, variables: FIELD_VARIABLES },\n};\n"]}
@@ -0,0 +1,35 @@
1
+ import type { ExpressionDialect } from "@motionscript/sdk";
2
+ /**
3
+ * The language a plot's equation is written in: the engine's own expression
4
+ * grammar (`expressionOps.parse`) under a dialect of its own, where trig is in
5
+ * radians, names are bare identifiers, and the logs and hyperbolics a plot
6
+ * wants are present. Never `new Function`: an equation is text stored in a
7
+ * document, and the shared parser can only produce arithmetic.
8
+ */
9
+ /** Named values an expression reads at call time, beside its two variables. */
10
+ export type ExpressionScope = Readonly<Record<string, number>>;
11
+ /**
12
+ * A compiled expression. The two variables are fixed slots because this is the
13
+ * hot path of every sampled curve; a one-variable expression never reads `b`.
14
+ */
15
+ export type CompiledExpression = (a: number, b: number, scope?: ExpressionScope) => number;
16
+ export declare const MATH_DIALECT: ExpressionDialect;
17
+ /** What an expression may name, for a host's "what can I write here" help. */
18
+ export interface ExpressionVocabulary {
19
+ variables: readonly string[];
20
+ functions: readonly string[];
21
+ constants: readonly string[];
22
+ }
23
+ export declare function expressionVocabulary(variables: readonly string[]): ExpressionVocabulary;
24
+ /**
25
+ * Compile `source` over up to two `variables`, in slot order, and any `params`
26
+ * it may read from the scope. Throws on a syntax error or an unknown name.
27
+ */
28
+ export declare function compileExpression(source: string, variables: readonly string[], params?: readonly string[]): CompiledExpression;
29
+ /**
30
+ * {@link compileExpression}, memoised: equal source under equal names is the
31
+ * identical closure, so "did this expression change" is an `===`, and a failure
32
+ * is remembered rather than re-parsed every frame.
33
+ */
34
+ export declare function compileExpressionCached(source: string, variables: readonly string[], params?: readonly string[]): CompiledExpression | Error;
35
+ //# sourceMappingURL=expression.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"expression.d.ts","sourceRoot":"","sources":["../../src/kit/expression.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAkB,MAAM,mBAAmB,CAAC;AAG3E;;;;;;GAMG;AAEH,+EAA+E;AAC/E,MAAM,MAAM,eAAe,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAE/D;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,eAAe,KAAK,MAAM,CAAC;AAwB3F,eAAO,MAAM,YAAY,EAAE,iBAQ1B,CAAC;AAEF,8EAA8E;AAC9E,MAAM,WAAW,oBAAoB;IACjC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7B,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7B,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;CAChC;AAED,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,GAAG,oBAAoB,CAMvF;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAC7B,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,SAAS,MAAM,EAAE,EAC5B,MAAM,GAAE,SAAS,MAAM,EAAO,GAC/B,kBAAkB,CAOpB;AAsDD;;;;GAIG;AACH,wBAAgB,uBAAuB,CACnC,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,SAAS,MAAM,EAAE,EAC5B,MAAM,GAAE,SAAS,MAAM,EAAO,GAC/B,kBAAkB,GAAG,KAAK,CAY5B"}
@@ -0,0 +1,124 @@
1
+ import { expressionOps } from "@motionscript/sdk";
2
+ import { createBoundedCache } from "./cache.js";
3
+ const UNARY = {
4
+ sin: Math.sin, cos: Math.cos, tan: Math.tan,
5
+ asin: Math.asin, acos: Math.acos, atan: Math.atan,
6
+ sinh: Math.sinh, cosh: Math.cosh, tanh: Math.tanh,
7
+ sqrt: Math.sqrt, cbrt: Math.cbrt, abs: Math.abs, exp: Math.exp,
8
+ log: Math.log, ln: Math.log, log2: Math.log2, log10: Math.log10,
9
+ floor: Math.floor, ceil: Math.ceil, round: Math.round, sign: Math.sign, trunc: Math.trunc,
10
+ };
11
+ const NARY = {
12
+ atan2: { fn: Math.atan2, arity: [2, 2] },
13
+ pow: { fn: Math.pow, arity: [2, 2] },
14
+ mod: { fn: (a, b) => a % b, arity: [2, 2] },
15
+ hypot: { fn: Math.hypot, arity: [1, Infinity] },
16
+ min: { fn: Math.min, arity: [1, Infinity] },
17
+ max: { fn: Math.max, arity: [1, Infinity] },
18
+ };
19
+ const CONSTANTS = {
20
+ pi: Math.PI, PI: Math.PI, e: Math.E, E: Math.E, tau: Math.PI * 2, phi: (1 + Math.sqrt(5)) / 2,
21
+ };
22
+ export const MATH_DIALECT = {
23
+ functions: {
24
+ ...Object.fromEntries(Object.keys(UNARY).map((name) => [name, { arity: [1, 1] }])),
25
+ ...Object.fromEntries(Object.entries(NARY).map(([name, { arity }]) => [name, { arity }])),
26
+ },
27
+ constants: CONSTANTS,
28
+ refs: "bare",
29
+ unknownName: (name) => `Unknown name '${name}'`,
30
+ };
31
+ export function expressionVocabulary(variables) {
32
+ return {
33
+ variables,
34
+ functions: [...Object.keys(UNARY), ...Object.keys(NARY)].sort(),
35
+ constants: ["pi", "e", "tau", "phi"],
36
+ };
37
+ }
38
+ /**
39
+ * Compile `source` over up to two `variables`, in slot order, and any `params`
40
+ * it may read from the scope. Throws on a syntax error or an unknown name.
41
+ */
42
+ export function compileExpression(source, variables, params = []) {
43
+ // The parser folds a constant before it yields a reference, so a name that
44
+ // is both would silently stop being the variable it was passed as.
45
+ for (const name of [...variables, ...params]) {
46
+ if (Object.hasOwn(CONSTANTS, name))
47
+ throw new Error(`'${name}' is a constant, so it cannot be a variable`);
48
+ }
49
+ return emit(expressionOps.parse(source, MATH_DIALECT).root, variables, params);
50
+ }
51
+ function emit(node, variables, params) {
52
+ switch (node.kind) {
53
+ case "const": {
54
+ const { value } = node;
55
+ return () => value;
56
+ }
57
+ case "ref": {
58
+ const { name } = node;
59
+ const slot = variables.indexOf(name);
60
+ if (slot === 0)
61
+ return (a) => a;
62
+ if (slot === 1)
63
+ return (_a, b) => b;
64
+ if (params.includes(name))
65
+ return (_a, _b, scope) => scope?.[name] ?? NaN;
66
+ throw new Error(MATH_DIALECT.unknownName(name));
67
+ }
68
+ case "unary": {
69
+ const operand = emit(node.operand, variables, params);
70
+ return (a, b, s) => -operand(a, b, s);
71
+ }
72
+ case "binary": {
73
+ const l = emit(node.left, variables, params);
74
+ const r = emit(node.right, variables, params);
75
+ switch (node.op) {
76
+ case "+": return (a, b, s) => l(a, b, s) + r(a, b, s);
77
+ case "-": return (a, b, s) => l(a, b, s) - r(a, b, s);
78
+ case "*": return (a, b, s) => l(a, b, s) * r(a, b, s);
79
+ case "/": return (a, b, s) => l(a, b, s) / r(a, b, s);
80
+ case "%": return (a, b, s) => l(a, b, s) % r(a, b, s);
81
+ case "^": return (a, b, s) => Math.pow(l(a, b, s), r(a, b, s));
82
+ }
83
+ break;
84
+ }
85
+ case "call": {
86
+ const args = node.args.map((arg) => emit(arg, variables, params));
87
+ const unary = UNARY[node.name];
88
+ if (unary) {
89
+ const [x] = args;
90
+ return (a, b, s) => unary(x(a, b, s));
91
+ }
92
+ const { fn } = NARY[node.name];
93
+ // The common arity, so the hot path allocates no array per sample.
94
+ if (args.length === 2) {
95
+ const [x, y] = args;
96
+ return (a, b, s) => fn(x(a, b, s), y(a, b, s));
97
+ }
98
+ return (a, b, s) => fn(...args.map((arg) => arg(a, b, s)));
99
+ }
100
+ }
101
+ throw new Error("Unsupported expression");
102
+ }
103
+ const compiled = createBoundedCache(256);
104
+ /**
105
+ * {@link compileExpression}, memoised: equal source under equal names is the
106
+ * identical closure, so "did this expression change" is an `===`, and a failure
107
+ * is remembered rather than re-parsed every frame.
108
+ */
109
+ export function compileExpressionCached(source, variables, params = []) {
110
+ const key = `${variables.join(",")}|${params.join(",")}|${source}`;
111
+ const hit = compiled.get(key);
112
+ if (hit !== undefined)
113
+ return hit;
114
+ let result;
115
+ try {
116
+ result = compileExpression(source, variables, params);
117
+ }
118
+ catch (error) {
119
+ result = error instanceof Error ? error : new Error(String(error));
120
+ }
121
+ compiled.set(key, result);
122
+ return result;
123
+ }
124
+ //# sourceMappingURL=expression.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"expression.js","sourceRoot":"","sources":["../../src/kit/expression.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAmB7C,MAAM,KAAK,GAA0C;IACjD,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG;IAC3C,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI;IACjD,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI;IACjD,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG;IAC9D,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK;IAC/D,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,KAAK,EAA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GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC/D,CAAC;IACL,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;AAC9C,CAAC;AAED,MAAM,QAAQ,GAAG,kBAAkB,CAA6B,GAAG,CAAC,CAAC;AAErE;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CACnC,MAAc,EACd,SAA4B,EAC5B,SAA4B,EAAE;IAE9B,MAAM,GAAG,GAAG,GAAG,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,MAAM,EAAE,CAAC;IACnE,MAAM,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC9B,IAAI,GAAG,KAAK,SAAS;QAAE,OAAO,GAAG,CAAC;IAClC,IAAI,MAAkC,CAAC;IACvC,IAAI,CAAC;QACD,MAAM,GAAG,iBAAiB,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;IAC1D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACvE,CAAC;IACD,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IAC1B,OAAO,MAAM,CAAC;AAClB,CAAC","sourcesContent":["import { expressionOps } from \"@motionscript/sdk\";\nimport type { ExpressionDialect, ExpressionNode } from \"@motionscript/sdk\";\nimport { createBoundedCache } from \"./cache\";\n\n/**\n * The language a plot's equation is written in: the engine's own expression\n * grammar (`expressionOps.parse`) under a dialect of its own, where trig is in\n * radians, names are bare identifiers, and the logs and hyperbolics a plot\n * wants are present. Never `new Function`: an equation is text stored in a\n * document, and the shared parser can only produce arithmetic.\n */\n\n/** Named values an expression reads at call time, beside its two variables. */\nexport type ExpressionScope = Readonly<Record<string, number>>;\n\n/**\n * A compiled expression. The two variables are fixed slots because this is the\n * hot path of every sampled curve; a one-variable expression never reads `b`.\n */\nexport type CompiledExpression = (a: number, b: number, scope?: ExpressionScope) => number;\n\nconst UNARY: Record<string, (v: number) => number> = {\n sin: Math.sin, cos: Math.cos, tan: Math.tan,\n asin: Math.asin, acos: Math.acos, atan: Math.atan,\n sinh: Math.sinh, cosh: Math.cosh, tanh: Math.tanh,\n sqrt: Math.sqrt, cbrt: Math.cbrt, abs: Math.abs, exp: Math.exp,\n log: Math.log, ln: Math.log, log2: Math.log2, log10: Math.log10,\n floor: Math.floor, ceil: Math.ceil, round: Math.round, sign: Math.sign, trunc: Math.trunc,\n};\n\nconst NARY: Record<string, { fn: (...args: number[]) => number; arity: [number, number] }> = {\n atan2: { fn: Math.atan2, arity: [2, 2] },\n pow: { fn: Math.pow, arity: [2, 2] },\n mod: { fn: (a, b) => a % b, arity: [2, 2] },\n hypot: { fn: Math.hypot, arity: [1, Infinity] },\n min: { fn: Math.min, arity: [1, Infinity] },\n max: { fn: Math.max, arity: [1, Infinity] },\n};\n\nconst CONSTANTS: Record<string, number> = {\n pi: Math.PI, PI: Math.PI, e: Math.E, E: Math.E, tau: Math.PI * 2, phi: (1 + Math.sqrt(5)) / 2,\n};\n\nexport const MATH_DIALECT: ExpressionDialect = {\n functions: {\n ...Object.fromEntries(Object.keys(UNARY).map((name) => [name, { arity: [1, 1] as [number, number] }])),\n ...Object.fromEntries(Object.entries(NARY).map(([name, { arity }]) => [name, { arity }])),\n },\n constants: CONSTANTS,\n refs: \"bare\",\n unknownName: (name) => `Unknown name '${name}'`,\n};\n\n/** What an expression may name, for a host's \"what can I write here\" help. */\nexport interface ExpressionVocabulary {\n variables: readonly string[];\n functions: readonly string[];\n constants: readonly string[];\n}\n\nexport function expressionVocabulary(variables: readonly string[]): ExpressionVocabulary {\n return {\n variables,\n functions: [...Object.keys(UNARY), ...Object.keys(NARY)].sort(),\n constants: [\"pi\", \"e\", \"tau\", \"phi\"],\n };\n}\n\n/**\n * Compile `source` over up to two `variables`, in slot order, and any `params`\n * it may read from the scope. Throws on a syntax error or an unknown name.\n */\nexport function compileExpression(\n source: string,\n variables: readonly string[],\n params: readonly string[] = [],\n): CompiledExpression {\n // The parser folds a constant before it yields a reference, so a name that\n // is both would silently stop being the variable it was passed as.\n for (const name of [...variables, ...params]) {\n if (Object.hasOwn(CONSTANTS, name)) throw new Error(`'${name}' is a constant, so it cannot be a variable`);\n }\n return emit(expressionOps.parse(source, MATH_DIALECT).root, variables, params);\n}\n\nfunction emit(node: ExpressionNode, variables: readonly string[], params: readonly string[]): CompiledExpression {\n switch (node.kind) {\n case \"const\": {\n const { value } = node;\n return () => value;\n }\n case \"ref\": {\n const { name } = node;\n const slot = variables.indexOf(name);\n if (slot === 0) return (a) => a;\n if (slot === 1) return (_a, b) => b;\n if (params.includes(name)) return (_a, _b, scope) => scope?.[name] ?? NaN;\n throw new Error(MATH_DIALECT.unknownName(name));\n }\n case \"unary\": {\n const operand = emit(node.operand, variables, params);\n return (a, b, s) => -operand(a, b, s);\n }\n case \"binary\": {\n const l = emit(node.left, variables, params);\n const r = emit(node.right, variables, params);\n switch (node.op) {\n case \"+\": return (a, b, s) => l(a, b, s) + r(a, b, s);\n case \"-\": return (a, b, s) => l(a, b, s) - r(a, b, s);\n case \"*\": return (a, b, s) => l(a, b, s) * r(a, b, s);\n case \"/\": return (a, b, s) => l(a, b, s) / r(a, b, s);\n case \"%\": return (a, b, s) => l(a, b, s) % r(a, b, s);\n case \"^\": return (a, b, s) => Math.pow(l(a, b, s), r(a, b, s));\n }\n break;\n }\n case \"call\": {\n const args = node.args.map((arg) => emit(arg, variables, params));\n const unary = UNARY[node.name];\n if (unary) {\n const [x] = args;\n return (a, b, s) => unary(x(a, b, s));\n }\n const { fn } = NARY[node.name];\n // The common arity, so the hot path allocates no array per sample.\n if (args.length === 2) {\n const [x, y] = args;\n return (a, b, s) => fn(x(a, b, s), y(a, b, s));\n }\n return (a, b, s) => fn(...args.map((arg) => arg(a, b, s)));\n }\n }\n throw new Error(\"Unsupported expression\");\n}\n\nconst compiled = createBoundedCache<CompiledExpression | Error>(256);\n\n/**\n * {@link compileExpression}, memoised: equal source under equal names is the\n * identical closure, so \"did this expression change\" is an `===`, and a failure\n * is remembered rather than re-parsed every frame.\n */\nexport function compileExpressionCached(\n source: string,\n variables: readonly string[],\n params: readonly string[] = [],\n): CompiledExpression | Error {\n const key = `${variables.join(\",\")}|${params.join(\",\")}|${source}`;\n const hit = compiled.get(key);\n if (hit !== undefined) return hit;\n let result: CompiledExpression | Error;\n try {\n result = compileExpression(source, variables, params);\n } catch (error) {\n result = error instanceof Error ? error : new Error(String(error));\n }\n compiled.set(key, result);\n return result;\n}\n"]}