@math.gl/sql 0.0.0-stage → 5.0.0-beta.11

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 (334) hide show
  1. package/LICENSE +249 -0
  2. package/README.md +26 -2
  3. package/THIRD-PARTY-NOTICES.md +5 -0
  4. package/dist/arrow/aggregates.d.ts +46 -0
  5. package/dist/arrow/aggregates.d.ts.map +1 -0
  6. package/dist/arrow/aggregates.js +289 -0
  7. package/dist/arrow/aggregates.js.map +1 -0
  8. package/dist/arrow/buffers.d.ts +30 -0
  9. package/dist/arrow/buffers.d.ts.map +1 -0
  10. package/dist/arrow/buffers.js +177 -0
  11. package/dist/arrow/buffers.js.map +1 -0
  12. package/dist/arrow/cast.d.ts +19 -0
  13. package/dist/arrow/cast.d.ts.map +1 -0
  14. package/dist/arrow/cast.js +138 -0
  15. package/dist/arrow/cast.js.map +1 -0
  16. package/dist/arrow/compiler.d.ts +10 -0
  17. package/dist/arrow/compiler.d.ts.map +1 -0
  18. package/dist/arrow/compiler.js +1421 -0
  19. package/dist/arrow/compiler.js.map +1 -0
  20. package/dist/arrow/float16.d.ts +7 -0
  21. package/dist/arrow/float16.d.ts.map +1 -0
  22. package/dist/arrow/float16.js +26 -0
  23. package/dist/arrow/float16.js.map +1 -0
  24. package/dist/arrow/index.cjs +3220 -0
  25. package/dist/arrow/index.cjs.map +6 -0
  26. package/dist/arrow/index.d.ts +5 -0
  27. package/dist/arrow/index.d.ts.map +1 -0
  28. package/dist/arrow/index.js +7 -0
  29. package/dist/arrow/index.js.map +1 -0
  30. package/dist/arrow/like.d.ts +3 -0
  31. package/dist/arrow/like.d.ts.map +1 -0
  32. package/dist/arrow/like.js +75 -0
  33. package/dist/arrow/like.js.map +1 -0
  34. package/dist/arrow/list-values.d.ts +14 -0
  35. package/dist/arrow/list-values.d.ts.map +1 -0
  36. package/dist/arrow/list-values.js +180 -0
  37. package/dist/arrow/list-values.js.map +1 -0
  38. package/dist/arrow/predicate.d.ts +7 -0
  39. package/dist/arrow/predicate.d.ts.map +1 -0
  40. package/dist/arrow/predicate.js +10 -0
  41. package/dist/arrow/predicate.js.map +1 -0
  42. package/dist/arrow/query-arrow-aggregate-snapshots.d.ts +24 -0
  43. package/dist/arrow/query-arrow-aggregate-snapshots.d.ts.map +1 -0
  44. package/dist/arrow/query-arrow-aggregate-snapshots.js +64 -0
  45. package/dist/arrow/query-arrow-aggregate-snapshots.js.map +1 -0
  46. package/dist/arrow/query-arrow-sql.d.ts +8 -0
  47. package/dist/arrow/query-arrow-sql.d.ts.map +1 -0
  48. package/dist/arrow/query-arrow-sql.js +191 -0
  49. package/dist/arrow/query-arrow-sql.js.map +1 -0
  50. package/dist/arrow/query-arrow-table.d.ts +36 -0
  51. package/dist/arrow/query-arrow-table.d.ts.map +1 -0
  52. package/dist/arrow/query-arrow-table.js +208 -0
  53. package/dist/arrow/query-arrow-table.js.map +1 -0
  54. package/dist/arrow/query-worker-entry.d.ts +2 -0
  55. package/dist/arrow/query-worker-entry.d.ts.map +1 -0
  56. package/dist/arrow/query-worker-entry.js +7 -0
  57. package/dist/arrow/query-worker-entry.js.map +1 -0
  58. package/dist/arrow/query-worker.d.ts +65 -0
  59. package/dist/arrow/query-worker.d.ts.map +1 -0
  60. package/dist/arrow/query-worker.js +135 -0
  61. package/dist/arrow/query-worker.js.map +1 -0
  62. package/dist/arrow/registry.d.ts +4 -0
  63. package/dist/arrow/registry.d.ts.map +1 -0
  64. package/dist/arrow/registry.js +65 -0
  65. package/dist/arrow/registry.js.map +1 -0
  66. package/dist/arrow/relational-query.d.ts +36 -0
  67. package/dist/arrow/relational-query.d.ts.map +1 -0
  68. package/dist/arrow/relational-query.js +174 -0
  69. package/dist/arrow/relational-query.js.map +1 -0
  70. package/dist/arrow/replace-arrow-columns.d.ts +8 -0
  71. package/dist/arrow/replace-arrow-columns.d.ts.map +1 -0
  72. package/dist/arrow/replace-arrow-columns.js +63 -0
  73. package/dist/arrow/replace-arrow-columns.js.map +1 -0
  74. package/dist/arrow/signature.d.ts +6 -0
  75. package/dist/arrow/signature.d.ts.map +1 -0
  76. package/dist/arrow/signature.js +51 -0
  77. package/dist/arrow/signature.js.map +1 -0
  78. package/dist/arrow/temporal-cast.d.ts +9 -0
  79. package/dist/arrow/temporal-cast.d.ts.map +1 -0
  80. package/dist/arrow/temporal-cast.js +60 -0
  81. package/dist/arrow/temporal-cast.js.map +1 -0
  82. package/dist/arrow/types.d.ts +62 -0
  83. package/dist/arrow/types.d.ts.map +1 -0
  84. package/dist/arrow/types.js +5 -0
  85. package/dist/arrow/types.js.map +1 -0
  86. package/dist/arrow/worker-entry.d.ts +2 -0
  87. package/dist/arrow/worker-entry.d.ts.map +1 -0
  88. package/dist/arrow/worker-entry.js +9 -0
  89. package/dist/arrow/worker-entry.js.map +1 -0
  90. package/dist/arrow/worker.cjs +3973 -0
  91. package/dist/arrow/worker.cjs.map +6 -0
  92. package/dist/arrow/worker.d.ts +58 -0
  93. package/dist/arrow/worker.d.ts.map +1 -0
  94. package/dist/arrow/worker.js +84 -0
  95. package/dist/arrow/worker.js.map +1 -0
  96. package/dist/color/index.cjs +382 -0
  97. package/dist/color/index.cjs.map +6 -0
  98. package/dist/color/index.d.ts +26 -0
  99. package/dist/color/index.d.ts.map +1 -0
  100. package/dist/color/index.js +306 -0
  101. package/dist/color/index.js.map +1 -0
  102. package/dist/diagnostic-log.d.ts +8 -0
  103. package/dist/diagnostic-log.d.ts.map +1 -0
  104. package/dist/diagnostic-log.js +15 -0
  105. package/dist/diagnostic-log.js.map +1 -0
  106. package/dist/expressions/ast.d.ts +12 -0
  107. package/dist/expressions/ast.d.ts.map +1 -0
  108. package/dist/expressions/ast.js +112 -0
  109. package/dist/expressions/ast.js.map +1 -0
  110. package/dist/expressions/columnar-predicate.d.ts +56 -0
  111. package/dist/expressions/columnar-predicate.d.ts.map +1 -0
  112. package/dist/expressions/columnar-predicate.js +176 -0
  113. package/dist/expressions/columnar-predicate.js.map +1 -0
  114. package/dist/expressions/evaluation-error.d.ts +14 -0
  115. package/dist/expressions/evaluation-error.d.ts.map +1 -0
  116. package/dist/expressions/evaluation-error.js +26 -0
  117. package/dist/expressions/evaluation-error.js.map +1 -0
  118. package/dist/expressions/expression-eval.d.ts +96 -0
  119. package/dist/expressions/expression-eval.d.ts.map +1 -0
  120. package/dist/expressions/expression-eval.js +330 -0
  121. package/dist/expressions/expression-eval.js.map +1 -0
  122. package/dist/expressions/function-libraries.d.ts +63 -0
  123. package/dist/expressions/function-libraries.d.ts.map +1 -0
  124. package/dist/expressions/function-libraries.js +69 -0
  125. package/dist/expressions/function-libraries.js.map +1 -0
  126. package/dist/expressions/function-registry.d.ts +93 -0
  127. package/dist/expressions/function-registry.d.ts.map +1 -0
  128. package/dist/expressions/function-registry.js +139 -0
  129. package/dist/expressions/function-registry.js.map +1 -0
  130. package/dist/expressions/get.d.ts +9 -0
  131. package/dist/expressions/get.d.ts.map +1 -0
  132. package/dist/expressions/get.js +32 -0
  133. package/dist/expressions/get.js.map +1 -0
  134. package/dist/expressions/index.cjs +1888 -0
  135. package/dist/expressions/index.cjs.map +6 -0
  136. package/dist/expressions/index.d.ts +13 -0
  137. package/dist/expressions/index.d.ts.map +1 -0
  138. package/dist/expressions/index.js +14 -0
  139. package/dist/expressions/index.js.map +1 -0
  140. package/dist/expressions/numeric-functions.d.ts +277 -0
  141. package/dist/expressions/numeric-functions.d.ts.map +1 -0
  142. package/dist/expressions/numeric-functions.js +52 -0
  143. package/dist/expressions/numeric-functions.js.map +1 -0
  144. package/dist/expressions/parse-expression-string.d.ts +21 -0
  145. package/dist/expressions/parse-expression-string.d.ts.map +1 -0
  146. package/dist/expressions/parse-expression-string.js +61 -0
  147. package/dist/expressions/parse-expression-string.js.map +1 -0
  148. package/dist/expressions/predicate-expression.d.ts +7 -0
  149. package/dist/expressions/predicate-expression.d.ts.map +1 -0
  150. package/dist/expressions/predicate-expression.js +112 -0
  151. package/dist/expressions/predicate-expression.js.map +1 -0
  152. package/dist/expressions/scalar-type.d.ts +6 -0
  153. package/dist/expressions/scalar-type.d.ts.map +1 -0
  154. package/dist/expressions/scalar-type.js +23 -0
  155. package/dist/expressions/scalar-type.js.map +1 -0
  156. package/dist/expressions/vendor/jsep/runtime.d.ts +3 -0
  157. package/dist/expressions/vendor/jsep/runtime.d.ts.map +1 -0
  158. package/dist/expressions/vendor/jsep/runtime.js +972 -0
  159. package/dist/expressions/vendor/jsep/runtime.js.map +1 -0
  160. package/dist/expressions/vendor/jsep/types.d.ts +148 -0
  161. package/dist/expressions/vendor/jsep/types.d.ts.map +1 -0
  162. package/dist/expressions/vendor/jsep/types.js +6 -0
  163. package/dist/expressions/vendor/jsep/types.js.map +1 -0
  164. package/dist/index.cjs +4865 -0
  165. package/dist/index.cjs.map +6 -0
  166. package/dist/index.d.ts +9 -0
  167. package/dist/index.d.ts.map +1 -0
  168. package/dist/index.js +10 -0
  169. package/dist/index.js.map +1 -0
  170. package/dist/math/index.cjs +444 -0
  171. package/dist/math/index.cjs.map +6 -0
  172. package/dist/math/index.d.ts +44 -0
  173. package/dist/math/index.d.ts.map +1 -0
  174. package/dist/math/index.js +182 -0
  175. package/dist/math/index.js.map +1 -0
  176. package/dist/scales/arrow-domains.d.ts +15 -0
  177. package/dist/scales/arrow-domains.d.ts.map +1 -0
  178. package/dist/scales/arrow-domains.js +124 -0
  179. package/dist/scales/arrow-domains.js.map +1 -0
  180. package/dist/scales/arrow-scales.cjs +3837 -0
  181. package/dist/scales/arrow-scales.cjs.map +6 -0
  182. package/dist/scales/arrow-scales.d.ts +20 -0
  183. package/dist/scales/arrow-scales.d.ts.map +1 -0
  184. package/dist/scales/arrow-scales.js +109 -0
  185. package/dist/scales/arrow-scales.js.map +1 -0
  186. package/dist/scales/compile-scale.d.ts +7 -0
  187. package/dist/scales/compile-scale.d.ts.map +1 -0
  188. package/dist/scales/compile-scale.js +195 -0
  189. package/dist/scales/compile-scale.js.map +1 -0
  190. package/dist/scales/hdr-colors.d.ts +13 -0
  191. package/dist/scales/hdr-colors.d.ts.map +1 -0
  192. package/dist/scales/hdr-colors.js +115 -0
  193. package/dist/scales/hdr-colors.js.map +1 -0
  194. package/dist/scales/index.cjs +1214 -0
  195. package/dist/scales/index.cjs.map +6 -0
  196. package/dist/scales/index.d.ts +9 -0
  197. package/dist/scales/index.d.ts.map +1 -0
  198. package/dist/scales/index.js +10 -0
  199. package/dist/scales/index.js.map +1 -0
  200. package/dist/scales/palettes.d.ts +5 -0
  201. package/dist/scales/palettes.d.ts.map +1 -0
  202. package/dist/scales/palettes.js +85 -0
  203. package/dist/scales/palettes.js.map +1 -0
  204. package/dist/scales/parse-sql-scale.d.ts +14 -0
  205. package/dist/scales/parse-sql-scale.d.ts.map +1 -0
  206. package/dist/scales/parse-sql-scale.js +165 -0
  207. package/dist/scales/parse-sql-scale.js.map +1 -0
  208. package/dist/scales/quantile-sketch.d.ts +22 -0
  209. package/dist/scales/quantile-sketch.d.ts.map +1 -0
  210. package/dist/scales/quantile-sketch.js +108 -0
  211. package/dist/scales/quantile-sketch.js.map +1 -0
  212. package/dist/scales/scale-types.d.ts +92 -0
  213. package/dist/scales/scale-types.d.ts.map +1 -0
  214. package/dist/scales/scale-types.js +119 -0
  215. package/dist/scales/scale-types.js.map +1 -0
  216. package/dist/scales/streaming-domains.d.ts +18 -0
  217. package/dist/scales/streaming-domains.d.ts.map +1 -0
  218. package/dist/scales/streaming-domains.js +109 -0
  219. package/dist/scales/streaming-domains.js.map +1 -0
  220. package/dist/sql/bind-sql-predicate.d.ts +4 -0
  221. package/dist/sql/bind-sql-predicate.d.ts.map +1 -0
  222. package/dist/sql/bind-sql-predicate.js +11 -0
  223. package/dist/sql/bind-sql-predicate.js.map +1 -0
  224. package/dist/sql/index.cjs +1588 -0
  225. package/dist/sql/index.cjs.map +6 -0
  226. package/dist/sql/index.d.ts +10 -0
  227. package/dist/sql/index.d.ts.map +1 -0
  228. package/dist/sql/index.js +10 -0
  229. package/dist/sql/index.js.map +1 -0
  230. package/dist/sql/parse-sql-expression.d.ts +44 -0
  231. package/dist/sql/parse-sql-expression.d.ts.map +1 -0
  232. package/dist/sql/parse-sql-expression.js +455 -0
  233. package/dist/sql/parse-sql-expression.js.map +1 -0
  234. package/dist/sql/parse-sql-predicate.d.ts +13 -0
  235. package/dist/sql/parse-sql-predicate.d.ts.map +1 -0
  236. package/dist/sql/parse-sql-predicate.js +365 -0
  237. package/dist/sql/parse-sql-predicate.js.map +1 -0
  238. package/dist/sql/parse-sql-query.d.ts +8 -0
  239. package/dist/sql/parse-sql-query.d.ts.map +1 -0
  240. package/dist/sql/parse-sql-query.js +66 -0
  241. package/dist/sql/parse-sql-query.js.map +1 -0
  242. package/dist/sql/parse-sql-select.d.ts +55 -0
  243. package/dist/sql/parse-sql-select.d.ts.map +1 -0
  244. package/dist/sql/parse-sql-select.js +244 -0
  245. package/dist/sql/parse-sql-select.js.map +1 -0
  246. package/dist/sql/parse-sql-statement.d.ts +50 -0
  247. package/dist/sql/parse-sql-statement.d.ts.map +1 -0
  248. package/dist/sql/parse-sql-statement.js +182 -0
  249. package/dist/sql/parse-sql-statement.js.map +1 -0
  250. package/dist/sql/query-types.d.ts +56 -0
  251. package/dist/sql/query-types.d.ts.map +1 -0
  252. package/dist/sql/query-types.js +5 -0
  253. package/dist/sql/query-types.js.map +1 -0
  254. package/dist/sql/sql-parse-error.d.ts +13 -0
  255. package/dist/sql/sql-parse-error.d.ts.map +1 -0
  256. package/dist/sql/sql-parse-error.js +20 -0
  257. package/dist/sql/sql-parse-error.js.map +1 -0
  258. package/dist/sql/sql-predicate-schema.d.ts +164 -0
  259. package/dist/sql/sql-predicate-schema.d.ts.map +1 -0
  260. package/dist/sql/sql-predicate-schema.js +249 -0
  261. package/dist/sql/sql-predicate-schema.js.map +1 -0
  262. package/dist/sql/sql-predicate-types.d.ts +48 -0
  263. package/dist/sql/sql-predicate-types.d.ts.map +1 -0
  264. package/dist/sql/sql-predicate-types.js +9 -0
  265. package/dist/sql/sql-predicate-types.js.map +1 -0
  266. package/dist/sql/sql-predicate.d.ts +6 -0
  267. package/dist/sql/sql-predicate.d.ts.map +1 -0
  268. package/dist/sql/sql-predicate.js +8 -0
  269. package/dist/sql/sql-predicate.js.map +1 -0
  270. package/package.json +92 -4
  271. package/src/arrow/aggregates.ts +386 -0
  272. package/src/arrow/buffers.ts +177 -0
  273. package/src/arrow/cast.ts +160 -0
  274. package/src/arrow/compiler.ts +1659 -0
  275. package/src/arrow/float16.ts +25 -0
  276. package/src/arrow/index.ts +22 -0
  277. package/src/arrow/like.ts +72 -0
  278. package/src/arrow/list-values.ts +200 -0
  279. package/src/arrow/predicate.ts +19 -0
  280. package/src/arrow/query-arrow-aggregate-snapshots.ts +107 -0
  281. package/src/arrow/query-arrow-sql.ts +227 -0
  282. package/src/arrow/query-arrow-table.ts +298 -0
  283. package/src/arrow/query-worker-entry.ts +8 -0
  284. package/src/arrow/query-worker.ts +190 -0
  285. package/src/arrow/registry.ts +86 -0
  286. package/src/arrow/relational-query.ts +247 -0
  287. package/src/arrow/replace-arrow-columns.ts +71 -0
  288. package/src/arrow/signature.ts +50 -0
  289. package/src/arrow/temporal-cast.ts +66 -0
  290. package/src/arrow/types.ts +76 -0
  291. package/src/arrow/worker-entry.ts +10 -0
  292. package/src/arrow/worker.ts +139 -0
  293. package/src/color/index.ts +405 -0
  294. package/src/diagnostic-log.ts +20 -0
  295. package/src/expressions/ast.ts +141 -0
  296. package/src/expressions/columnar-predicate.ts +293 -0
  297. package/src/expressions/evaluation-error.ts +29 -0
  298. package/src/expressions/expression-eval.ts +480 -0
  299. package/src/expressions/function-libraries.ts +126 -0
  300. package/src/expressions/function-registry.ts +171 -0
  301. package/src/expressions/get.ts +37 -0
  302. package/src/expressions/index.ts +40 -0
  303. package/src/expressions/numeric-functions.ts +99 -0
  304. package/src/expressions/parse-expression-string.ts +80 -0
  305. package/src/expressions/predicate-expression.ts +128 -0
  306. package/src/expressions/scalar-type.ts +39 -0
  307. package/src/expressions/vendor/jsep/LICENSE.txt +23 -0
  308. package/src/expressions/vendor/jsep/README.md +22 -0
  309. package/src/expressions/vendor/jsep/runtime.ts +949 -0
  310. package/src/expressions/vendor/jsep/types.ts +191 -0
  311. package/src/index.ts +40 -0
  312. package/src/math/index.ts +235 -0
  313. package/src/scales/arrow-domains.ts +131 -0
  314. package/src/scales/arrow-scales.ts +156 -0
  315. package/src/scales/compile-scale.ts +217 -0
  316. package/src/scales/hdr-colors.ts +126 -0
  317. package/src/scales/index.ts +35 -0
  318. package/src/scales/palettes.ts +86 -0
  319. package/src/scales/parse-sql-scale.ts +195 -0
  320. package/src/scales/quantile-sketch.ts +106 -0
  321. package/src/scales/scale-types.ts +224 -0
  322. package/src/scales/streaming-domains.ts +133 -0
  323. package/src/sql/bind-sql-predicate.ts +21 -0
  324. package/src/sql/index.ts +28 -0
  325. package/src/sql/parse-sql-expression.ts +457 -0
  326. package/src/sql/parse-sql-predicate.ts +454 -0
  327. package/src/sql/parse-sql-query.ts +72 -0
  328. package/src/sql/parse-sql-select.ts +266 -0
  329. package/src/sql/parse-sql-statement.ts +242 -0
  330. package/src/sql/query-types.ts +71 -0
  331. package/src/sql/sql-parse-error.ts +33 -0
  332. package/src/sql/sql-predicate-schema.ts +279 -0
  333. package/src/sql/sql-predicate-types.ts +91 -0
  334. package/src/sql/sql-predicate.ts +28 -0
@@ -0,0 +1,3837 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // dist/scales/arrow-scales.js
20
+ var arrow_scales_exports = {};
21
+ __export(arrow_scales_exports, {
22
+ compileArrowScale: () => compileArrowScale,
23
+ compileArrowScales: () => compileArrowScales,
24
+ createStreamingDomainAccumulator: () => createStreamingDomainAccumulator
25
+ });
26
+ module.exports = __toCommonJS(arrow_scales_exports);
27
+ var import_apache_arrow7 = require("apache-arrow");
28
+
29
+ // dist/arrow/compiler.js
30
+ var import_apache_arrow6 = require("apache-arrow");
31
+ var import_utf82 = require("@math.gl/arrow/utf8");
32
+
33
+ // dist/diagnostic-log.js
34
+ function reportDiagnosticError(log, error) {
35
+ if (log) {
36
+ try {
37
+ log.error(error instanceof Error ? error.message : String(error), error)();
38
+ } catch {
39
+ }
40
+ }
41
+ }
42
+
43
+ // dist/expressions/vendor/jsep/runtime.js
44
+ var Hooks = class {
45
+ /**
46
+ * @callback HookCallback
47
+ * @this {*|Jsep} this
48
+ * @param {Jsep} env
49
+ * @returns: void
50
+ */
51
+ /**
52
+ * Adds the given callback to the list of callbacks for the given hook.
53
+ *
54
+ * The callback will be invoked when the hook it is registered for is run.
55
+ *
56
+ * One callback function can be registered to multiple hooks and the same hook multiple times.
57
+ *
58
+ * @param {string|object} name The name of the hook, or an object of callbacks keyed by name
59
+ * @param {HookCallback|boolean} callback The callback function which is given environment variables.
60
+ * @param {?boolean} [first=false] Will add the hook to the top of the list (defaults to the bottom)
61
+ * @public
62
+ */
63
+ add(name, callback, first) {
64
+ if (typeof arguments[0] != "string") {
65
+ for (let name2 in arguments[0]) {
66
+ this.add(name2, arguments[0][name2], arguments[1]);
67
+ }
68
+ } else {
69
+ (Array.isArray(name) ? name : [name]).forEach(function(name2) {
70
+ this[name2] = this[name2] || [];
71
+ if (callback) {
72
+ this[name2][first ? "unshift" : "push"](callback);
73
+ }
74
+ }, this);
75
+ }
76
+ }
77
+ /**
78
+ * Runs a hook invoking all registered callbacks with the given environment variables.
79
+ *
80
+ * Callbacks will be invoked synchronously and in the order in which they were registered.
81
+ *
82
+ * @param {string} name The name of the hook.
83
+ * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
84
+ * @public
85
+ */
86
+ run(name, env) {
87
+ this[name] = this[name] || [];
88
+ this[name].forEach(function(callback) {
89
+ callback.call(env && env.context ? env.context : env, env);
90
+ });
91
+ }
92
+ };
93
+ var Plugins = class {
94
+ constructor(jsep22) {
95
+ this.jsep = jsep22;
96
+ this.registered = {};
97
+ }
98
+ /**
99
+ * @callback PluginSetup
100
+ * @this {Jsep} jsep
101
+ * @returns: void
102
+ */
103
+ /**
104
+ * Adds the given plugin(s) to the registry
105
+ *
106
+ * @param {object} plugins
107
+ * @param {string} plugins.name The name of the plugin
108
+ * @param {PluginSetup} plugins.init The init function
109
+ * @public
110
+ */
111
+ register(...plugins) {
112
+ plugins.forEach((plugin) => {
113
+ if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
114
+ throw new Error("Invalid JSEP plugin format");
115
+ }
116
+ if (this.registered[plugin.name]) {
117
+ return;
118
+ }
119
+ plugin.init(this.jsep);
120
+ this.registered[plugin.name] = plugin;
121
+ });
122
+ }
123
+ };
124
+ var Jsep = class _Jsep {
125
+ /**
126
+ * @returns {string}
127
+ */
128
+ static get version() {
129
+ return "1.4.0";
130
+ }
131
+ /**
132
+ * @returns {string}
133
+ */
134
+ static toString() {
135
+ return "JavaScript Expression Parser (JSEP) v" + _Jsep.version;
136
+ }
137
+ // ==================== CONFIG ================================
138
+ /**
139
+ * @method addUnaryOp
140
+ * @param {string} op_name The name of the unary op to add
141
+ * @returns {Jsep}
142
+ */
143
+ static addUnaryOp(op_name) {
144
+ _Jsep.max_unop_len = Math.max(op_name.length, _Jsep.max_unop_len);
145
+ _Jsep.unary_ops[op_name] = 1;
146
+ return _Jsep;
147
+ }
148
+ /**
149
+ * @method jsep.addBinaryOp
150
+ * @param {string} op_name The name of the binary op to add
151
+ * @param {number} precedence The precedence of the binary op (can be a float). Higher number = higher precedence
152
+ * @param {boolean} [isRightAssociative=false] whether operator is right-associative
153
+ * @returns {Jsep}
154
+ */
155
+ static addBinaryOp(op_name, precedence, isRightAssociative) {
156
+ _Jsep.max_binop_len = Math.max(op_name.length, _Jsep.max_binop_len);
157
+ _Jsep.binary_ops[op_name] = precedence;
158
+ if (isRightAssociative) {
159
+ _Jsep.right_associative.add(op_name);
160
+ } else {
161
+ _Jsep.right_associative.delete(op_name);
162
+ }
163
+ return _Jsep;
164
+ }
165
+ /**
166
+ * @method addIdentifierChar
167
+ * @param {string} char The additional character to treat as a valid part of an identifier
168
+ * @returns {Jsep}
169
+ */
170
+ static addIdentifierChar(char) {
171
+ _Jsep.additional_identifier_chars.add(char);
172
+ return _Jsep;
173
+ }
174
+ /**
175
+ * @method addLiteral
176
+ * @param {string} literal_name The name of the literal to add
177
+ * @param {*} literal_value The value of the literal
178
+ * @returns {Jsep}
179
+ */
180
+ static addLiteral(literal_name, literal_value) {
181
+ _Jsep.literals[literal_name] = literal_value;
182
+ return _Jsep;
183
+ }
184
+ /**
185
+ * @method removeUnaryOp
186
+ * @param {string} op_name The name of the unary op to remove
187
+ * @returns {Jsep}
188
+ */
189
+ static removeUnaryOp(op_name) {
190
+ delete _Jsep.unary_ops[op_name];
191
+ if (op_name.length === _Jsep.max_unop_len) {
192
+ _Jsep.max_unop_len = _Jsep.getMaxKeyLen(_Jsep.unary_ops);
193
+ }
194
+ return _Jsep;
195
+ }
196
+ /**
197
+ * @method removeAllUnaryOps
198
+ * @returns {Jsep}
199
+ */
200
+ static removeAllUnaryOps() {
201
+ _Jsep.unary_ops = {};
202
+ _Jsep.max_unop_len = 0;
203
+ return _Jsep;
204
+ }
205
+ /**
206
+ * @method removeIdentifierChar
207
+ * @param {string} char The additional character to stop treating as a valid part of an identifier
208
+ * @returns {Jsep}
209
+ */
210
+ static removeIdentifierChar(char) {
211
+ _Jsep.additional_identifier_chars.delete(char);
212
+ return _Jsep;
213
+ }
214
+ /**
215
+ * @method removeBinaryOp
216
+ * @param {string} op_name The name of the binary op to remove
217
+ * @returns {Jsep}
218
+ */
219
+ static removeBinaryOp(op_name) {
220
+ delete _Jsep.binary_ops[op_name];
221
+ if (op_name.length === _Jsep.max_binop_len) {
222
+ _Jsep.max_binop_len = _Jsep.getMaxKeyLen(_Jsep.binary_ops);
223
+ }
224
+ _Jsep.right_associative.delete(op_name);
225
+ return _Jsep;
226
+ }
227
+ /**
228
+ * @method removeAllBinaryOps
229
+ * @returns {Jsep}
230
+ */
231
+ static removeAllBinaryOps() {
232
+ _Jsep.binary_ops = {};
233
+ _Jsep.max_binop_len = 0;
234
+ return _Jsep;
235
+ }
236
+ /**
237
+ * @method removeLiteral
238
+ * @param {string} literal_name The name of the literal to remove
239
+ * @returns {Jsep}
240
+ */
241
+ static removeLiteral(literal_name) {
242
+ delete _Jsep.literals[literal_name];
243
+ return _Jsep;
244
+ }
245
+ /**
246
+ * @method removeAllLiterals
247
+ * @returns {Jsep}
248
+ */
249
+ static removeAllLiterals() {
250
+ _Jsep.literals = {};
251
+ return _Jsep;
252
+ }
253
+ // ==================== END CONFIG ============================
254
+ /**
255
+ * @returns {string}
256
+ */
257
+ get char() {
258
+ return this.expr.charAt(this.index);
259
+ }
260
+ /**
261
+ * @returns {number}
262
+ */
263
+ get code() {
264
+ return this.expr.charCodeAt(this.index);
265
+ }
266
+ /**
267
+ * @param {string} expr a string with the passed in express
268
+ * @returns Jsep
269
+ */
270
+ constructor(expr) {
271
+ this.expr = expr;
272
+ this.index = 0;
273
+ }
274
+ /**
275
+ * static top-level parser
276
+ * @returns {jsep.Expression}
277
+ */
278
+ static parse(expr) {
279
+ return new _Jsep(expr).parse();
280
+ }
281
+ /**
282
+ * Get the longest key length of any object
283
+ * @param {object} obj
284
+ * @returns {number}
285
+ */
286
+ static getMaxKeyLen(obj) {
287
+ return Math.max(0, ...Object.keys(obj).map((k) => k.length));
288
+ }
289
+ /**
290
+ * `ch` is a character code in the next three functions
291
+ * @param {number} ch
292
+ * @returns {boolean}
293
+ */
294
+ static isDecimalDigit(ch) {
295
+ return ch >= 48 && ch <= 57;
296
+ }
297
+ /**
298
+ * Returns the precedence of a binary operator or `0` if it isn't a binary operator. Can be float.
299
+ * @param {string} op_val
300
+ * @returns {number}
301
+ */
302
+ static binaryPrecedence(op_val) {
303
+ return _Jsep.binary_ops[op_val] || 0;
304
+ }
305
+ /**
306
+ * Looks for start of identifier
307
+ * @param {number} ch
308
+ * @returns {boolean}
309
+ */
310
+ static isIdentifierStart(ch) {
311
+ return ch >= 65 && ch <= 90 || // A...Z
312
+ ch >= 97 && ch <= 122 || // a...z
313
+ ch >= 128 && !_Jsep.binary_ops[String.fromCharCode(ch)] || // any non-ASCII that is not an operator
314
+ _Jsep.additional_identifier_chars.has(String.fromCharCode(ch));
315
+ }
316
+ /**
317
+ * @param {number} ch
318
+ * @returns {boolean}
319
+ */
320
+ static isIdentifierPart(ch) {
321
+ return _Jsep.isIdentifierStart(ch) || _Jsep.isDecimalDigit(ch);
322
+ }
323
+ /**
324
+ * throw error at index of the expression
325
+ * @param {string} message
326
+ * @throws
327
+ */
328
+ throwError(message) {
329
+ const error = new Error(message + " at character " + this.index);
330
+ error.index = this.index;
331
+ error.description = message;
332
+ throw error;
333
+ }
334
+ /**
335
+ * Run a given hook
336
+ * @param {string} name
337
+ * @param {jsep.Expression|false} [node]
338
+ * @returns {?jsep.Expression}
339
+ */
340
+ runHook(name, node) {
341
+ if (_Jsep.hooks[name]) {
342
+ const env = { context: this, node };
343
+ _Jsep.hooks.run(name, env);
344
+ return env.node;
345
+ }
346
+ return node;
347
+ }
348
+ /**
349
+ * Runs a given hook until one returns a node
350
+ * @param {string} name
351
+ * @returns {?jsep.Expression}
352
+ */
353
+ searchHook(name) {
354
+ if (_Jsep.hooks[name]) {
355
+ const env = { context: this };
356
+ _Jsep.hooks[name].find(function(callback) {
357
+ callback.call(env.context, env);
358
+ return env.node;
359
+ });
360
+ return env.node;
361
+ }
362
+ }
363
+ /**
364
+ * Push `index` up to the next non-space character
365
+ */
366
+ gobbleSpaces() {
367
+ let ch = this.code;
368
+ while (ch === _Jsep.SPACE_CODE || ch === _Jsep.TAB_CODE || ch === _Jsep.LF_CODE || ch === _Jsep.CR_CODE) {
369
+ ch = this.expr.charCodeAt(++this.index);
370
+ }
371
+ this.runHook("gobble-spaces");
372
+ }
373
+ /**
374
+ * Top-level method to parse all expressions and returns compound or single node
375
+ * @returns {jsep.Expression}
376
+ */
377
+ parse() {
378
+ this.runHook("before-all");
379
+ const nodes = this.gobbleExpressions();
380
+ const node = nodes.length === 1 ? nodes[0] : {
381
+ type: _Jsep.COMPOUND,
382
+ body: nodes
383
+ };
384
+ return this.runHook("after-all", node);
385
+ }
386
+ /**
387
+ * top-level parser (but can be reused within as well)
388
+ * @param {number} [untilICode]
389
+ * @returns {jsep.Expression[]}
390
+ */
391
+ gobbleExpressions(untilICode) {
392
+ let nodes = [], ch_i, node;
393
+ while (this.index < this.expr.length) {
394
+ ch_i = this.code;
395
+ if (ch_i === _Jsep.SEMCOL_CODE || ch_i === _Jsep.COMMA_CODE) {
396
+ this.index++;
397
+ } else {
398
+ if (node = this.gobbleExpression()) {
399
+ nodes.push(node);
400
+ } else if (this.index < this.expr.length) {
401
+ if (ch_i === untilICode) {
402
+ break;
403
+ }
404
+ this.throwError('Unexpected "' + this.char + '"');
405
+ }
406
+ }
407
+ }
408
+ return nodes;
409
+ }
410
+ /**
411
+ * The main parsing function.
412
+ * @returns {?jsep.Expression}
413
+ */
414
+ gobbleExpression() {
415
+ const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
416
+ this.gobbleSpaces();
417
+ return this.runHook("after-expression", node);
418
+ }
419
+ /**
420
+ * Search for the operation portion of the string (e.g. `+`, `===`)
421
+ * Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
422
+ * and move down from 3 to 2 to 1 character until a matching binary operation is found
423
+ * then, return that binary operation
424
+ * @returns {string|boolean}
425
+ */
426
+ gobbleBinaryOp() {
427
+ this.gobbleSpaces();
428
+ let to_check = this.expr.substr(this.index, _Jsep.max_binop_len);
429
+ let tc_len = to_check.length;
430
+ while (tc_len > 0) {
431
+ if (_Jsep.binary_ops.hasOwnProperty(to_check) && (!_Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !_Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
432
+ this.index += tc_len;
433
+ return to_check;
434
+ }
435
+ to_check = to_check.substr(0, --tc_len);
436
+ }
437
+ return false;
438
+ }
439
+ /**
440
+ * This function is responsible for gobbling an individual expression,
441
+ * e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
442
+ * @returns {?jsep.BinaryExpression}
443
+ */
444
+ gobbleBinaryExpression() {
445
+ let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
446
+ left = this.gobbleToken();
447
+ if (!left) {
448
+ return left;
449
+ }
450
+ biop = this.gobbleBinaryOp();
451
+ if (!biop) {
452
+ return left;
453
+ }
454
+ biop_info = { value: biop, prec: _Jsep.binaryPrecedence(biop), right_a: _Jsep.right_associative.has(biop) };
455
+ right = this.gobbleToken();
456
+ if (!right) {
457
+ this.throwError("Expected expression after " + biop);
458
+ }
459
+ stack = [left, biop_info, right];
460
+ while (biop = this.gobbleBinaryOp()) {
461
+ prec = _Jsep.binaryPrecedence(biop);
462
+ if (prec === 0) {
463
+ this.index -= biop.length;
464
+ break;
465
+ }
466
+ biop_info = { value: biop, prec, right_a: _Jsep.right_associative.has(biop) };
467
+ cur_biop = biop;
468
+ const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
469
+ while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
470
+ right = stack.pop();
471
+ biop = stack.pop().value;
472
+ left = stack.pop();
473
+ node = {
474
+ type: _Jsep.BINARY_EXP,
475
+ operator: biop,
476
+ left,
477
+ right
478
+ };
479
+ stack.push(node);
480
+ }
481
+ node = this.gobbleToken();
482
+ if (!node) {
483
+ this.throwError("Expected expression after " + cur_biop);
484
+ }
485
+ stack.push(biop_info, node);
486
+ }
487
+ i = stack.length - 1;
488
+ node = stack[i];
489
+ while (i > 1) {
490
+ node = {
491
+ type: _Jsep.BINARY_EXP,
492
+ operator: stack[i - 1].value,
493
+ left: stack[i - 2],
494
+ right: node
495
+ };
496
+ i -= 2;
497
+ }
498
+ return node;
499
+ }
500
+ /**
501
+ * An individual part of a binary expression:
502
+ * e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
503
+ * @returns {boolean|jsep.Expression}
504
+ */
505
+ gobbleToken() {
506
+ let ch, to_check, tc_len, node;
507
+ this.gobbleSpaces();
508
+ node = this.searchHook("gobble-token");
509
+ if (node) {
510
+ return this.runHook("after-token", node);
511
+ }
512
+ ch = this.code;
513
+ if (_Jsep.isDecimalDigit(ch) || ch === _Jsep.PERIOD_CODE) {
514
+ return this.gobbleNumericLiteral();
515
+ }
516
+ if (ch === _Jsep.SQUOTE_CODE || ch === _Jsep.DQUOTE_CODE) {
517
+ node = this.gobbleStringLiteral();
518
+ } else if (ch === _Jsep.OBRACK_CODE) {
519
+ node = this.gobbleArray();
520
+ } else {
521
+ to_check = this.expr.substr(this.index, _Jsep.max_unop_len);
522
+ tc_len = to_check.length;
523
+ while (tc_len > 0) {
524
+ if (_Jsep.unary_ops.hasOwnProperty(to_check) && (!_Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !_Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
525
+ this.index += tc_len;
526
+ const argument = this.gobbleToken();
527
+ if (!argument) {
528
+ this.throwError("missing unaryOp argument");
529
+ }
530
+ return this.runHook("after-token", {
531
+ type: _Jsep.UNARY_EXP,
532
+ operator: to_check,
533
+ argument,
534
+ prefix: true
535
+ });
536
+ }
537
+ to_check = to_check.substr(0, --tc_len);
538
+ }
539
+ if (_Jsep.isIdentifierStart(ch)) {
540
+ node = this.gobbleIdentifier();
541
+ if (_Jsep.literals.hasOwnProperty(node.name)) {
542
+ node = {
543
+ type: _Jsep.LITERAL,
544
+ value: _Jsep.literals[node.name],
545
+ raw: node.name
546
+ };
547
+ } else if (node.name === _Jsep.this_str) {
548
+ node = { type: _Jsep.THIS_EXP };
549
+ }
550
+ } else if (ch === _Jsep.OPAREN_CODE) {
551
+ node = this.gobbleGroup();
552
+ }
553
+ }
554
+ if (!node) {
555
+ return this.runHook("after-token", false);
556
+ }
557
+ node = this.gobbleTokenProperty(node);
558
+ return this.runHook("after-token", node);
559
+ }
560
+ /**
561
+ * Gobble properties of of identifiers/strings/arrays/groups.
562
+ * e.g. `foo`, `bar.baz`, `foo['bar'].baz`
563
+ * It also gobbles function calls:
564
+ * e.g. `Math.acos(obj.angle)`
565
+ * @param {jsep.Expression} node
566
+ * @returns {jsep.Expression}
567
+ */
568
+ gobbleTokenProperty(node) {
569
+ this.gobbleSpaces();
570
+ let ch = this.code;
571
+ while (ch === _Jsep.PERIOD_CODE || ch === _Jsep.OBRACK_CODE || ch === _Jsep.OPAREN_CODE || ch === _Jsep.QUMARK_CODE) {
572
+ let optional;
573
+ if (ch === _Jsep.QUMARK_CODE) {
574
+ if (this.expr.charCodeAt(this.index + 1) !== _Jsep.PERIOD_CODE) {
575
+ break;
576
+ }
577
+ optional = true;
578
+ this.index += 2;
579
+ this.gobbleSpaces();
580
+ ch = this.code;
581
+ }
582
+ this.index++;
583
+ if (ch === _Jsep.OBRACK_CODE) {
584
+ node = {
585
+ type: _Jsep.MEMBER_EXP,
586
+ computed: true,
587
+ object: node,
588
+ property: this.gobbleExpression()
589
+ };
590
+ if (!node.property) {
591
+ this.throwError('Unexpected "' + this.char + '"');
592
+ }
593
+ this.gobbleSpaces();
594
+ ch = this.code;
595
+ if (ch !== _Jsep.CBRACK_CODE) {
596
+ this.throwError("Unclosed [");
597
+ }
598
+ this.index++;
599
+ } else if (ch === _Jsep.OPAREN_CODE) {
600
+ node = {
601
+ type: _Jsep.CALL_EXP,
602
+ "arguments": this.gobbleArguments(_Jsep.CPAREN_CODE),
603
+ callee: node
604
+ };
605
+ } else if (ch === _Jsep.PERIOD_CODE || optional) {
606
+ if (optional) {
607
+ this.index--;
608
+ }
609
+ this.gobbleSpaces();
610
+ node = {
611
+ type: _Jsep.MEMBER_EXP,
612
+ computed: false,
613
+ object: node,
614
+ property: this.gobbleIdentifier()
615
+ };
616
+ }
617
+ if (optional) {
618
+ node.optional = true;
619
+ }
620
+ this.gobbleSpaces();
621
+ ch = this.code;
622
+ }
623
+ return node;
624
+ }
625
+ /**
626
+ * Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
627
+ * keep track of everything in the numeric literal and then calling `parseFloat` on that string
628
+ * @returns {jsep.Literal}
629
+ */
630
+ gobbleNumericLiteral() {
631
+ let number = "", ch, chCode;
632
+ while (_Jsep.isDecimalDigit(this.code)) {
633
+ number += this.expr.charAt(this.index++);
634
+ }
635
+ if (this.code === _Jsep.PERIOD_CODE) {
636
+ number += this.expr.charAt(this.index++);
637
+ while (_Jsep.isDecimalDigit(this.code)) {
638
+ number += this.expr.charAt(this.index++);
639
+ }
640
+ }
641
+ ch = this.char;
642
+ if (ch === "e" || ch === "E") {
643
+ number += this.expr.charAt(this.index++);
644
+ ch = this.char;
645
+ if (ch === "+" || ch === "-") {
646
+ number += this.expr.charAt(this.index++);
647
+ }
648
+ while (_Jsep.isDecimalDigit(this.code)) {
649
+ number += this.expr.charAt(this.index++);
650
+ }
651
+ if (!_Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
652
+ this.throwError("Expected exponent (" + number + this.char + ")");
653
+ }
654
+ }
655
+ chCode = this.code;
656
+ if (_Jsep.isIdentifierStart(chCode)) {
657
+ this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
658
+ } else if (chCode === _Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === _Jsep.PERIOD_CODE) {
659
+ this.throwError("Unexpected period");
660
+ }
661
+ return {
662
+ type: _Jsep.LITERAL,
663
+ value: parseFloat(number),
664
+ raw: number
665
+ };
666
+ }
667
+ /**
668
+ * Parses a string literal, staring with single or double quotes with basic support for escape codes
669
+ * e.g. `"hello world"`, `'this is\nJSEP'`
670
+ * @returns {jsep.Literal}
671
+ */
672
+ gobbleStringLiteral() {
673
+ let str = "";
674
+ const startIndex = this.index;
675
+ const quote = this.expr.charAt(this.index++);
676
+ let closed = false;
677
+ while (this.index < this.expr.length) {
678
+ let ch = this.expr.charAt(this.index++);
679
+ if (ch === quote) {
680
+ closed = true;
681
+ break;
682
+ } else if (ch === "\\") {
683
+ ch = this.expr.charAt(this.index++);
684
+ switch (ch) {
685
+ case "n":
686
+ str += "\n";
687
+ break;
688
+ case "r":
689
+ str += "\r";
690
+ break;
691
+ case "t":
692
+ str += " ";
693
+ break;
694
+ case "b":
695
+ str += "\b";
696
+ break;
697
+ case "f":
698
+ str += "\f";
699
+ break;
700
+ case "v":
701
+ str += "\v";
702
+ break;
703
+ default:
704
+ str += ch;
705
+ }
706
+ } else {
707
+ str += ch;
708
+ }
709
+ }
710
+ if (!closed) {
711
+ this.throwError('Unclosed quote after "' + str + '"');
712
+ }
713
+ return {
714
+ type: _Jsep.LITERAL,
715
+ value: str,
716
+ raw: this.expr.substring(startIndex, this.index)
717
+ };
718
+ }
719
+ /**
720
+ * Gobbles only identifiers
721
+ * e.g.: `foo`, `_value`, `$x1`
722
+ * Also, this function checks if that identifier is a literal:
723
+ * (e.g. `true`, `false`, `null`) or `this`
724
+ * @returns {jsep.Identifier}
725
+ */
726
+ gobbleIdentifier() {
727
+ let ch = this.code, start = this.index;
728
+ if (_Jsep.isIdentifierStart(ch)) {
729
+ this.index++;
730
+ } else {
731
+ this.throwError("Unexpected " + this.char);
732
+ }
733
+ while (this.index < this.expr.length) {
734
+ ch = this.code;
735
+ if (_Jsep.isIdentifierPart(ch)) {
736
+ this.index++;
737
+ } else {
738
+ break;
739
+ }
740
+ }
741
+ return {
742
+ type: _Jsep.IDENTIFIER,
743
+ name: this.expr.slice(start, this.index)
744
+ };
745
+ }
746
+ /**
747
+ * Gobbles a list of arguments within the context of a function call
748
+ * or array literal. This function also assumes that the opening character
749
+ * `(` or `[` has already been gobbled, and gobbles expressions and commas
750
+ * until the terminator character `)` or `]` is encountered.
751
+ * e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
752
+ * @param {number} termination
753
+ * @returns {jsep.Expression[]}
754
+ */
755
+ gobbleArguments(termination) {
756
+ const args = [];
757
+ let closed = false;
758
+ let separator_count = 0;
759
+ while (this.index < this.expr.length) {
760
+ this.gobbleSpaces();
761
+ let ch_i = this.code;
762
+ if (ch_i === termination) {
763
+ closed = true;
764
+ this.index++;
765
+ if (termination === _Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
766
+ this.throwError("Unexpected token " + String.fromCharCode(termination));
767
+ }
768
+ break;
769
+ } else if (ch_i === _Jsep.COMMA_CODE) {
770
+ this.index++;
771
+ separator_count++;
772
+ if (separator_count !== args.length) {
773
+ if (termination === _Jsep.CPAREN_CODE) {
774
+ this.throwError("Unexpected token ,");
775
+ } else if (termination === _Jsep.CBRACK_CODE) {
776
+ for (let arg = args.length; arg < separator_count; arg++) {
777
+ args.push(null);
778
+ }
779
+ }
780
+ }
781
+ } else if (args.length !== separator_count && separator_count !== 0) {
782
+ this.throwError("Expected comma");
783
+ } else {
784
+ const node = this.gobbleExpression();
785
+ if (!node || node.type === _Jsep.COMPOUND) {
786
+ this.throwError("Expected comma");
787
+ }
788
+ args.push(node);
789
+ }
790
+ }
791
+ if (!closed) {
792
+ this.throwError("Expected " + String.fromCharCode(termination));
793
+ }
794
+ return args;
795
+ }
796
+ /**
797
+ * Responsible for parsing a group of things within parentheses `()`
798
+ * that have no identifier in front (so not a function call)
799
+ * This function assumes that it needs to gobble the opening parenthesis
800
+ * and then tries to gobble everything within that parenthesis, assuming
801
+ * that the next thing it should see is the close parenthesis. If not,
802
+ * then the expression probably doesn't have a `)`
803
+ * @returns {boolean|jsep.Expression}
804
+ */
805
+ gobbleGroup() {
806
+ this.index++;
807
+ let nodes = this.gobbleExpressions(_Jsep.CPAREN_CODE);
808
+ if (this.code === _Jsep.CPAREN_CODE) {
809
+ this.index++;
810
+ if (nodes.length === 1) {
811
+ return nodes[0];
812
+ } else if (!nodes.length) {
813
+ return false;
814
+ } else {
815
+ return {
816
+ type: _Jsep.SEQUENCE_EXP,
817
+ expressions: nodes
818
+ };
819
+ }
820
+ } else {
821
+ this.throwError("Unclosed (");
822
+ }
823
+ }
824
+ /**
825
+ * Responsible for parsing Array literals `[1, 2, 3]`
826
+ * This function assumes that it needs to gobble the opening bracket
827
+ * and then tries to gobble the expressions as arguments.
828
+ * @returns {jsep.ArrayExpression}
829
+ */
830
+ gobbleArray() {
831
+ this.index++;
832
+ return {
833
+ type: _Jsep.ARRAY_EXP,
834
+ elements: this.gobbleArguments(_Jsep.CBRACK_CODE)
835
+ };
836
+ }
837
+ };
838
+ var hooks = new Hooks();
839
+ Object.assign(Jsep, {
840
+ hooks,
841
+ plugins: new Plugins(Jsep),
842
+ // Node Types
843
+ // ----------
844
+ // This is the full set of types that any JSEP node can be.
845
+ // Store them here to save space when minified
846
+ COMPOUND: "Compound",
847
+ SEQUENCE_EXP: "SequenceExpression",
848
+ IDENTIFIER: "Identifier",
849
+ MEMBER_EXP: "MemberExpression",
850
+ LITERAL: "Literal",
851
+ THIS_EXP: "ThisExpression",
852
+ CALL_EXP: "CallExpression",
853
+ UNARY_EXP: "UnaryExpression",
854
+ BINARY_EXP: "BinaryExpression",
855
+ ARRAY_EXP: "ArrayExpression",
856
+ TAB_CODE: 9,
857
+ LF_CODE: 10,
858
+ CR_CODE: 13,
859
+ SPACE_CODE: 32,
860
+ PERIOD_CODE: 46,
861
+ // '.'
862
+ COMMA_CODE: 44,
863
+ // ','
864
+ SQUOTE_CODE: 39,
865
+ // single quote
866
+ DQUOTE_CODE: 34,
867
+ // double quotes
868
+ OPAREN_CODE: 40,
869
+ // (
870
+ CPAREN_CODE: 41,
871
+ // )
872
+ OBRACK_CODE: 91,
873
+ // [
874
+ CBRACK_CODE: 93,
875
+ // ]
876
+ QUMARK_CODE: 63,
877
+ // ?
878
+ SEMCOL_CODE: 59,
879
+ // ;
880
+ COLON_CODE: 58,
881
+ // :
882
+ // Operations
883
+ // ----------
884
+ // Use a quickly-accessible map to store all of the unary operators
885
+ // Values are set to `1` (it really doesn't matter)
886
+ unary_ops: {
887
+ "-": 1,
888
+ "!": 1,
889
+ "~": 1,
890
+ "+": 1
891
+ },
892
+ // Also use a map for the binary operations but set their values to their
893
+ // binary precedence for quick reference (higher number = higher precedence)
894
+ // see [Order of operations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
895
+ binary_ops: {
896
+ "||": 1,
897
+ "??": 1,
898
+ "&&": 2,
899
+ "|": 3,
900
+ "^": 4,
901
+ "&": 5,
902
+ "==": 6,
903
+ "!=": 6,
904
+ "===": 6,
905
+ "!==": 6,
906
+ "<": 7,
907
+ ">": 7,
908
+ "<=": 7,
909
+ ">=": 7,
910
+ "<<": 8,
911
+ ">>": 8,
912
+ ">>>": 8,
913
+ "+": 9,
914
+ "-": 9,
915
+ "*": 10,
916
+ "/": 10,
917
+ "%": 10,
918
+ "**": 11
919
+ },
920
+ // sets specific binary_ops as right-associative
921
+ right_associative: /* @__PURE__ */ new Set(["**"]),
922
+ // Additional valid identifier chars, apart from a-z, A-Z and 0-9 (except on the starting char)
923
+ additional_identifier_chars: /* @__PURE__ */ new Set(["$", "_"]),
924
+ // Literals
925
+ // ----------
926
+ // Store the values to return for the various literals we may encounter
927
+ literals: {
928
+ "true": true,
929
+ "false": false,
930
+ "null": null
931
+ },
932
+ // Except for `this`, which is special. This could be changed to something like `'self'` as well
933
+ this_str: "this"
934
+ });
935
+ Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
936
+ Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
937
+ var jsep = (expr) => new Jsep(expr).parse();
938
+ var stdClassProps = Object.getOwnPropertyNames(class Test {
939
+ });
940
+ Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === void 0).forEach((m) => {
941
+ jsep[m] = Jsep[m];
942
+ });
943
+ jsep.Jsep = Jsep;
944
+ var CONDITIONAL_EXP = "ConditionalExpression";
945
+ var ternary = {
946
+ name: "ternary",
947
+ init(jsep22) {
948
+ jsep22.hooks.add("after-expression", function gobbleTernary(env) {
949
+ if (env.node && this.code === jsep22.QUMARK_CODE) {
950
+ this.index++;
951
+ const test = env.node;
952
+ const consequent = this.gobbleExpression();
953
+ if (!consequent) {
954
+ this.throwError("Expected expression");
955
+ }
956
+ this.gobbleSpaces();
957
+ if (this.code === jsep22.COLON_CODE) {
958
+ this.index++;
959
+ const alternate = this.gobbleExpression();
960
+ if (!alternate) {
961
+ this.throwError("Expected expression");
962
+ }
963
+ env.node = {
964
+ type: CONDITIONAL_EXP,
965
+ test,
966
+ consequent,
967
+ alternate
968
+ };
969
+ if (test.operator && jsep22.binary_ops[test.operator] <= 0.9) {
970
+ let newTest = test;
971
+ while (newTest.right.operator && jsep22.binary_ops[newTest.right.operator] <= 0.9) {
972
+ newTest = newTest.right;
973
+ }
974
+ env.node.test = newTest.right;
975
+ newTest.right = env.node;
976
+ env.node = test;
977
+ }
978
+ } else {
979
+ this.throwError("Expected :");
980
+ }
981
+ }
982
+ });
983
+ }
984
+ };
985
+ jsep.plugins.register(ternary);
986
+ var runtime_default = jsep;
987
+
988
+ // dist/expressions/expression-eval.js
989
+ var jsep2 = runtime_default;
990
+ function parse(expression, options) {
991
+ try {
992
+ return typeof expression === "string" ? jsep2(expression) : expression;
993
+ } catch (error) {
994
+ reportDiagnosticError(options == null ? void 0 : options.log, error);
995
+ throw error;
996
+ }
997
+ }
998
+
999
+ // dist/expressions/scalar-type.js
1000
+ var COLUMNAR_SCALAR_TYPES = Object.freeze([
1001
+ "int8",
1002
+ "int16",
1003
+ "int32",
1004
+ "int64",
1005
+ "uint8",
1006
+ "uint16",
1007
+ "uint32",
1008
+ "uint64",
1009
+ "float16",
1010
+ "float32",
1011
+ "float64",
1012
+ "bool",
1013
+ "utf8"
1014
+ ]);
1015
+ function isColumnarScalarType(value) {
1016
+ return typeof value === "string" && COLUMNAR_SCALAR_TYPES.includes(value);
1017
+ }
1018
+
1019
+ // dist/expressions/ast.js
1020
+ var MAXIMUM_EXPRESSION_NODES = 16384;
1021
+ var MAXIMUM_EXPRESSION_DEPTH = 192;
1022
+ function validateExpressionAST(value, options = {}) {
1023
+ visitExpressionAST(value, () => {
1024
+ }, options);
1025
+ }
1026
+ function visitExpressionAST(value, visit, options) {
1027
+ var _a2;
1028
+ const maxNodes = options.maxNodes ?? MAXIMUM_EXPRESSION_NODES, maxDepth = options.maxDepth ?? MAXIMUM_EXPRESSION_DEPTH;
1029
+ if (!Number.isSafeInteger(maxNodes) || maxNodes < 1 || maxNodes > MAXIMUM_EXPRESSION_NODES || !Number.isSafeInteger(maxDepth) || maxDepth < 0 || maxDepth > MAXIMUM_EXPRESSION_DEPTH)
1030
+ throw new Error(`Expression AST limits must not exceed ${MAXIMUM_EXPRESSION_NODES} nodes and ${MAXIMUM_EXPRESSION_DEPTH} levels`);
1031
+ const stack = [{ node: value, depth: 0 }];
1032
+ const ancestors = /* @__PURE__ */ new Set();
1033
+ let count = 0;
1034
+ while (stack.length) {
1035
+ const { node: input, depth, exit } = stack.pop();
1036
+ if (!input || typeof input !== "object" || Array.isArray(input))
1037
+ throw new Error("Invalid expression AST node");
1038
+ if (exit) {
1039
+ ancestors.delete(input);
1040
+ continue;
1041
+ }
1042
+ if (++count > maxNodes || depth > maxDepth)
1043
+ throw new Error("Expression AST exceeds node or depth limit");
1044
+ if (ancestors.has(input))
1045
+ throw new Error("Expression AST contains a cycle");
1046
+ ancestors.add(input);
1047
+ stack.push({ node: input, depth, exit: true });
1048
+ const node = input;
1049
+ const children = [];
1050
+ switch (node.type) {
1051
+ case "Identifier":
1052
+ if (typeof node.name !== "string" || !node.name.length || node.name.length > 65536)
1053
+ throw new Error("Invalid expression identifier");
1054
+ break;
1055
+ case "Literal":
1056
+ if (node.value !== null && !["number", "bigint", "boolean", "string"].includes(typeof node.value))
1057
+ throw new Error("Unsupported expression literal");
1058
+ if (node.raw !== void 0 && typeof node.raw !== "string")
1059
+ throw new Error("Invalid literal annotation");
1060
+ break;
1061
+ case "UnaryExpression":
1062
+ if (typeof node.operator !== "string" || !node.operator.length || node.operator.length > 32)
1063
+ throw new Error("Invalid expression operator");
1064
+ if (node.prefix !== void 0 && typeof node.prefix !== "boolean")
1065
+ throw new Error("Invalid unary annotation");
1066
+ children.push(node.argument);
1067
+ break;
1068
+ case "LogicalExpression":
1069
+ if (node.operator !== "&&" && node.operator !== "||")
1070
+ throw new Error("Invalid logical operator");
1071
+ children.push(node.left, node.right);
1072
+ break;
1073
+ case "BinaryExpression":
1074
+ if (typeof node.operator !== "string" || !node.operator.length || node.operator.length > 32)
1075
+ throw new Error("Invalid expression operator");
1076
+ children.push(node.left, node.right);
1077
+ break;
1078
+ case "ConditionalExpression":
1079
+ children.push(node.test, node.consequent, node.alternate);
1080
+ break;
1081
+ case "ArrayExpression":
1082
+ if (!Array.isArray(node.elements))
1083
+ throw new Error("Invalid expression array");
1084
+ if (node.elements.length + count > maxNodes)
1085
+ throw new Error("Expression AST exceeds node limit");
1086
+ for (const element of node.elements) {
1087
+ if (element == null)
1088
+ throw new Error("Expression array contains holes");
1089
+ children.push(element);
1090
+ }
1091
+ break;
1092
+ case "CallExpression":
1093
+ if (((_a2 = node.callee) == null ? void 0 : _a2.type) !== "Identifier" || typeof node.callee.name !== "string" || !node.callee.name.length || node.callee.name.length > 65536 || !Array.isArray(node.arguments) || node.sqlFunction !== void 0 && node.sqlFunction !== true)
1094
+ throw new Error("Expressions require named function calls");
1095
+ if (node.arguments.length + count > maxNodes)
1096
+ throw new Error("Expression AST exceeds node limit");
1097
+ children.push(...node.arguments);
1098
+ break;
1099
+ default:
1100
+ throw new Error(`Unsupported portable expression AST node: ${node.type}`);
1101
+ }
1102
+ if (children.length + count + stack.length - ancestors.size > maxNodes)
1103
+ throw new Error("Expression AST exceeds node limit");
1104
+ visit(node);
1105
+ for (let index = children.length - 1; index >= 0; index--)
1106
+ stack.push({ node: children[index], depth: depth + 1 });
1107
+ }
1108
+ }
1109
+
1110
+ // dist/expressions/evaluation-error.js
1111
+ var _a;
1112
+ var brand = /* @__PURE__ */ Symbol.for("@math.gl/core/ExpressionEvaluationError");
1113
+ var codes = ["domain", "conversion", "overflow", "divisionByZero"];
1114
+ var ExpressionEvaluationError = class extends Error {
1115
+ constructor(code, message) {
1116
+ super(message);
1117
+ this.code = code;
1118
+ this.name = "ExpressionEvaluationError";
1119
+ this[_a] = true;
1120
+ if (!codes.includes(code))
1121
+ throw new TypeError("Unknown Arrow evaluation error code");
1122
+ }
1123
+ };
1124
+ _a = brand;
1125
+ function isExpressionEvaluationError(error) {
1126
+ return typeof error === "object" && error !== null && error[brand] === true && codes.includes(error.code);
1127
+ }
1128
+
1129
+ // dist/arrow/buffers.js
1130
+ var import_apache_arrow = require("apache-arrow");
1131
+
1132
+ // dist/arrow/float16.js
1133
+ var import_core = require("@math.gl/core");
1134
+ function requireFloat16() {
1135
+ if (!(0, import_core.isFloat16ArrayConstructor)((0, import_core.getFloat16ArrayConstructor)()))
1136
+ throw new Error("Arrow Float16 expressions require native Float16Array support");
1137
+ }
1138
+ function float16Values(values) {
1139
+ if ((0, import_core.isFloat16Array)(values))
1140
+ return values;
1141
+ requireFloat16();
1142
+ const Constructor = (0, import_core.getFloat16ArrayConstructor)();
1143
+ return new Constructor(values.buffer, values.byteOffset, values.length);
1144
+ }
1145
+ function roundFloat16() {
1146
+ const cell = float16Values(new Uint16Array(1));
1147
+ return (value) => {
1148
+ cell[0] = value;
1149
+ return cell[0];
1150
+ };
1151
+ }
1152
+
1153
+ // dist/arrow/buffers.js
1154
+ function valueType(type) {
1155
+ return import_apache_arrow.DataType.isDictionary(type) ? valueType(type.dictionary) : type;
1156
+ }
1157
+ function typeKey(type) {
1158
+ type = valueType(type);
1159
+ if (import_apache_arrow.DataType.isInt(type))
1160
+ return `${type.isSigned ? "i" : "u"}${type.bitWidth}`;
1161
+ if (import_apache_arrow.DataType.isFloat(type)) {
1162
+ if (type.precision === import_apache_arrow.Precision.HALF)
1163
+ requireFloat16();
1164
+ return `f${type.precision}`;
1165
+ }
1166
+ if (import_apache_arrow.DataType.isBool(type))
1167
+ return "bool";
1168
+ if (import_apache_arrow.DataType.isUtf8(type))
1169
+ return "utf8";
1170
+ if (import_apache_arrow.DataType.isDate(type) && type.unit === import_apache_arrow.DateUnit.DAY)
1171
+ return "date32";
1172
+ if (import_apache_arrow.DataType.isTimestamp(type) && type.unit === import_apache_arrow.TimeUnit.MICROSECOND)
1173
+ return `timestamp_us:${type.timezone ?? ""}`;
1174
+ if (import_apache_arrow.DataType.isBinary(type))
1175
+ return "binary";
1176
+ if (import_apache_arrow.DataType.isFixedSizeBinary(type))
1177
+ return `fixedsizebinary:${type.byteWidth}`;
1178
+ if (import_apache_arrow.DataType.isNull(type))
1179
+ return "null";
1180
+ throw new Error(`Unsupported Arrow expression type: ${type}`);
1181
+ }
1182
+ var ColumnReader = class _ColumnReader {
1183
+ constructor(vector) {
1184
+ this.vector = vector;
1185
+ this.ends = [];
1186
+ this.location = [null, 0];
1187
+ this.range = [null, 0, 0];
1188
+ this.half = /* @__PURE__ */ new Map();
1189
+ this.dictionaries = /* @__PURE__ */ new Map();
1190
+ this.decoder = new TextDecoder();
1191
+ let end = 0;
1192
+ for (const data of vector.data) {
1193
+ end += data.length;
1194
+ this.ends.push(end);
1195
+ if (import_apache_arrow.DataType.isFloat(data.type) && data.type.precision === import_apache_arrow.Precision.HALF)
1196
+ this.half.set(data, float16Values(data.values));
1197
+ if (import_apache_arrow.DataType.isDictionary(data.type))
1198
+ this.dictionaries.set(data, new _ColumnReader(data.dictionary));
1199
+ }
1200
+ }
1201
+ /** Locates a chunk without constructing row objects. */
1202
+ chunk(row) {
1203
+ let index = 0;
1204
+ while (row >= this.ends[index])
1205
+ index++;
1206
+ this.location[0] = this.vector.data[index];
1207
+ this.location[1] = row - (index ? this.ends[index - 1] : 0);
1208
+ return this.location;
1209
+ }
1210
+ /** Tests validity with the physical bit offset. */
1211
+ isValid(row) {
1212
+ const [data, index] = this.chunk(row);
1213
+ if (import_apache_arrow.DataType.isNull(data.type))
1214
+ return false;
1215
+ const bit = data.offset + index;
1216
+ if (data.nullCount && !(data.nullBitmap[bit >> 3] & 1 << (bit & 7)))
1217
+ return false;
1218
+ return !import_apache_arrow.DataType.isDictionary(data.type) || this.dictionaries.get(data).isValid(Number(data.values[index]));
1219
+ }
1220
+ /** Reads a primitive; UTF-8 is decoded only for scalar callbacks or output materialization. */
1221
+ get(row) {
1222
+ if (!this.isValid(row))
1223
+ return null;
1224
+ const [data, index] = this.chunk(row);
1225
+ if (import_apache_arrow.DataType.isDictionary(data.type))
1226
+ return this.dictionaries.get(data).get(Number(data.values[index]));
1227
+ if (import_apache_arrow.DataType.isUtf8(data.type))
1228
+ return this.decoder.decode(data.values.subarray(data.valueOffsets[index], data.valueOffsets[index + 1]));
1229
+ if (import_apache_arrow.DataType.isBinary(data.type))
1230
+ return data.values.subarray(data.valueOffsets[index], data.valueOffsets[index + 1]);
1231
+ if (import_apache_arrow.DataType.isFixedSizeBinary(data.type))
1232
+ return data.values.subarray(data.stride * index, data.stride * (index + 1));
1233
+ if (import_apache_arrow.DataType.isBool(data.type)) {
1234
+ const bit = data.offset + index;
1235
+ return Boolean(data.values[bit >> 3] & 1 << (bit & 7));
1236
+ }
1237
+ return this.half.has(data) ? this.half.get(data)[index] : data.values[index];
1238
+ }
1239
+ /** Resolves UTF-8 buffers, including dictionary values, without decoding. */
1240
+ utf8(row) {
1241
+ const [data, index] = this.chunk(row);
1242
+ if (import_apache_arrow.DataType.isDictionary(data.type))
1243
+ return this.dictionaries.get(data).utf8(Number(data.values[index]));
1244
+ this.range[0] = data.values;
1245
+ this.range[1] = Number(data.valueOffsets[index]);
1246
+ this.range[2] = Number(data.valueOffsets[index + 1]);
1247
+ return this.range;
1248
+ }
1249
+ };
1250
+ function createValueValidator(inputType) {
1251
+ const type = valueType(inputType), key = typeKey(type);
1252
+ if (import_apache_arrow.DataType.isInt(type)) {
1253
+ if (type.bitWidth === 64) {
1254
+ const bits = BigInt(type.bitWidth), min2 = type.isSigned ? -(1n << bits - 1n) : 0n;
1255
+ const max2 = type.isSigned ? (1n << bits - 1n) - 1n : (1n << bits) - 1n;
1256
+ return (value) => {
1257
+ if (value === null)
1258
+ return;
1259
+ if (typeof value !== "bigint")
1260
+ throw new Error("64-bit integers require bigint values");
1261
+ if (value < min2 || value > max2)
1262
+ throw new ExpressionEvaluationError("overflow", "Integer expression overflow");
1263
+ };
1264
+ }
1265
+ const min = type.isSigned ? -(2 ** (type.bitWidth - 1)) : 0;
1266
+ const max = type.isSigned ? 2 ** (type.bitWidth - 1) - 1 : 2 ** type.bitWidth - 1;
1267
+ return (value) => {
1268
+ if (value === null)
1269
+ return;
1270
+ if (typeof value !== "number")
1271
+ throw new TypeError("Integer expressions require numeric values");
1272
+ if (!Number.isInteger(value))
1273
+ throw new ExpressionEvaluationError("conversion", "Integer expression requires integral numbers");
1274
+ if (value < min || value > max)
1275
+ throw new ExpressionEvaluationError("overflow", "Integer expression overflow");
1276
+ };
1277
+ }
1278
+ if (key === "date32") {
1279
+ return (value) => {
1280
+ if (value === null)
1281
+ return;
1282
+ if (typeof value !== "number" || !Number.isInteger(value) || value < -2147483648 || value > 2147483647)
1283
+ throw new ExpressionEvaluationError("overflow", "Invalid Date32 epoch day");
1284
+ };
1285
+ }
1286
+ if (key.startsWith("timestamp_us:")) {
1287
+ return (value) => {
1288
+ if (value === null)
1289
+ return;
1290
+ if (typeof value !== "bigint" || value !== BigInt.asIntN(64, value))
1291
+ throw new ExpressionEvaluationError("overflow", "Invalid timestamp epoch microseconds");
1292
+ };
1293
+ }
1294
+ if (import_apache_arrow.DataType.isBinary(type) || import_apache_arrow.DataType.isFixedSizeBinary(type)) {
1295
+ return (value) => {
1296
+ if (value === null)
1297
+ return;
1298
+ if (!(value instanceof Uint8Array) || import_apache_arrow.DataType.isFixedSizeBinary(type) && value.byteLength !== type.byteWidth)
1299
+ throw new Error(`Invalid value for ${type}`);
1300
+ };
1301
+ }
1302
+ const expected = import_apache_arrow.DataType.isFloat(type) ? "number" : key === "bool" ? "boolean" : "string";
1303
+ return (value) => {
1304
+ if (value !== null && (key === "null" || typeof value !== expected))
1305
+ throw new Error(`Invalid value for ${type}`);
1306
+ };
1307
+ }
1308
+ function validateValue(value, type) {
1309
+ createValueValidator(type)(value);
1310
+ }
1311
+
1312
+ // dist/arrow/cast.js
1313
+ var import_apache_arrow3 = require("apache-arrow");
1314
+ var import_utf8 = require("@math.gl/arrow/utf8");
1315
+
1316
+ // dist/arrow/temporal-cast.js
1317
+ var import_apache_arrow2 = require("apache-arrow");
1318
+ var DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
1319
+ var TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(Z|[+-]\d{2}:\d{2})?$/;
1320
+ function bindTemporalCast(source, target) {
1321
+ const dateOnly = target === "date";
1322
+ const zoned = target === "timestamp_utc";
1323
+ const type = dateOnly ? new import_apache_arrow2.DateDay() : new import_apache_arrow2.TimestampMicrosecond(zoned ? "UTC" : void 0);
1324
+ const sourceKey = typeKey(source);
1325
+ if (sourceKey !== "utf8" && sourceKey !== "null" && sourceKey !== typeKey(type))
1326
+ throw new Error("Temporal CAST requires UTF8 or an input of the requested Arrow type");
1327
+ return {
1328
+ type,
1329
+ textInput: false,
1330
+ evaluate(value) {
1331
+ return typeof value === "string" ? parseTemporalValue(value, dateOnly, zoned) : value;
1332
+ }
1333
+ };
1334
+ }
1335
+ function parseTemporalValue(text, dateOnly, zoned) {
1336
+ const match = (dateOnly ? DATE : TIMESTAMP).exec(text.trim());
1337
+ const invalid = () => new ExpressionEvaluationError("conversion", "Invalid text for temporal CAST");
1338
+ if (!match)
1339
+ throw invalid();
1340
+ const [, yearText, monthText, dayText, hourText, minuteText, secondText, fraction, zone] = match;
1341
+ const year = Number(yearText);
1342
+ const month = Number(monthText);
1343
+ const day = Number(dayText);
1344
+ const calendar = /* @__PURE__ */ new Date(0);
1345
+ calendar.setUTCFullYear(year, month - 1, day);
1346
+ if (calendar.getUTCFullYear() !== year || calendar.getUTCMonth() !== month - 1 || calendar.getUTCDate() !== day)
1347
+ throw invalid();
1348
+ if (dateOnly)
1349
+ return calendar.getTime() / 864e5;
1350
+ const hour = Number(hourText);
1351
+ const minute = Number(minuteText);
1352
+ const second = Number(secondText);
1353
+ if (hour > 23 || minute > 59 || second > 59 || zoned !== Boolean(zone))
1354
+ throw invalid();
1355
+ let offsetMinutes = 0;
1356
+ if (zone && zone !== "Z") {
1357
+ const offsetHour = Number(zone.slice(1, 3));
1358
+ const offsetMinute = Number(zone.slice(4));
1359
+ if (offsetHour > 23 || offsetMinute > 59)
1360
+ throw invalid();
1361
+ offsetMinutes = (zone.startsWith("-") ? -1 : 1) * (offsetHour * 60 + offsetMinute);
1362
+ }
1363
+ const seconds = hour * 3600 + minute * 60 + second - offsetMinutes * 60;
1364
+ return BigInt(calendar.getTime() + seconds * 1e3) * 1000n + BigInt((fraction ?? "").padEnd(6, "0"));
1365
+ }
1366
+
1367
+ // dist/arrow/cast.js
1368
+ var CAST_TYPES = {
1369
+ int8: import_apache_arrow3.Int8,
1370
+ int16: import_apache_arrow3.Int16,
1371
+ int32: import_apache_arrow3.Int32,
1372
+ int64: import_apache_arrow3.Int64,
1373
+ uint8: import_apache_arrow3.Uint8,
1374
+ uint16: import_apache_arrow3.Uint16,
1375
+ uint32: import_apache_arrow3.Uint32,
1376
+ uint64: import_apache_arrow3.Uint64,
1377
+ float16: import_apache_arrow3.Float16,
1378
+ float32: import_apache_arrow3.Float32,
1379
+ float64: import_apache_arrow3.Float64,
1380
+ bool: import_apache_arrow3.Bool,
1381
+ utf8: import_apache_arrow3.Utf8
1382
+ };
1383
+ function bindCast(source, target) {
1384
+ if (target === "date" || target === "timestamp" || target === "timestamp_utc")
1385
+ return bindTemporalCast(source, target);
1386
+ const binaryTarget = typeof target === "string" && /^(varbinary|fixedsizebinary):([1-9]\d*)$/.exec(target);
1387
+ if (target === "binary" || binaryTarget) {
1388
+ const byteWidth = binaryTarget ? Number(binaryTarget[2]) : void 0;
1389
+ if (byteWidth !== void 0 && byteWidth > 2147483647)
1390
+ throw new Error("Binary CAST requires a positive 32-bit byte width");
1391
+ const type2 = binaryTarget && binaryTarget[1] === "fixedsizebinary" ? new import_apache_arrow3.FixedSizeBinary(byteWidth) : new import_apache_arrow3.Binary();
1392
+ const sourceKey2 = typeKey(source);
1393
+ const textInput2 = sourceKey2 === "utf8";
1394
+ if (!textInput2 && sourceKey2 !== "null" && sourceKey2 !== "binary" && !sourceKey2.startsWith("fixedsizebinary:"))
1395
+ throw new Error("Binary CAST requires binary or UTF8 input");
1396
+ return {
1397
+ type: type2,
1398
+ textInput: textInput2,
1399
+ evaluate(value, range) {
1400
+ const bytes2 = range ? range[0].subarray(range[1], range[2]) : value;
1401
+ if (bytes2 === null || byteWidth === void 0)
1402
+ return bytes2;
1403
+ if (bytes2.byteLength > byteWidth)
1404
+ throw new ExpressionEvaluationError("overflow", `Binary CAST exceeds ${byteWidth} bytes`);
1405
+ if (import_apache_arrow3.DataType.isFixedSizeBinary(type2) && bytes2.byteLength < byteWidth) {
1406
+ const padded = new Uint8Array(byteWidth);
1407
+ padded.set(bytes2);
1408
+ return padded;
1409
+ }
1410
+ return bytes2;
1411
+ }
1412
+ };
1413
+ }
1414
+ const dictionary = target === "dictionary_utf8_int32";
1415
+ if (dictionary)
1416
+ target = "utf8";
1417
+ if (!isColumnarScalarType(target))
1418
+ throw new Error("Unsupported scalar CAST target");
1419
+ const type = new CAST_TYPES[target]();
1420
+ const integer = import_apache_arrow3.DataType.isInt(type);
1421
+ const wideInteger = integer && type.bitWidth === 64;
1422
+ const sourceKey = typeKey(source);
1423
+ const textInput = sourceKey === "utf8";
1424
+ if (sourceKey === "date32" || sourceKey.startsWith("timestamp_us:"))
1425
+ throw new Error("Temporal CAST requires a matching temporal target");
1426
+ if (sourceKey === "binary" || sourceKey.startsWith("fixedsizebinary:"))
1427
+ throw new Error("CAST from binary requires a binary target");
1428
+ if (sourceKey !== "null" && (sourceKey === "bool" && !["bool", "utf8"].includes(target) || target === "bool" && !["bool", "utf8"].includes(sourceKey)))
1429
+ throw new Error("CAST between Boolean and numeric values is not supported");
1430
+ const validate = createValueValidator(type);
1431
+ const halfRound = target === "float16" ? roundFloat16() : void 0;
1432
+ const encoder2 = new TextEncoder();
1433
+ return {
1434
+ type: dictionary ? new import_apache_arrow3.Dictionary(new import_apache_arrow3.Utf8(), new import_apache_arrow3.Int32()) : type,
1435
+ textInput,
1436
+ evaluate(value, range) {
1437
+ if (value === null && !range)
1438
+ return null;
1439
+ let result;
1440
+ if (target === "utf8") {
1441
+ if (typeof value === "boolean")
1442
+ return value ? "TRUE" : "FALSE";
1443
+ return String(value);
1444
+ }
1445
+ if (textInput) {
1446
+ const input = range ?? (() => {
1447
+ const bytes3 = encoder2.encode(value);
1448
+ return [bytes3, 0, bytes3.length];
1449
+ })();
1450
+ const [bytes2, start, end] = input;
1451
+ result = target === "bool" ? (0, import_utf8.parseUTF8Boolean)(bytes2, start, end) ?? null : integer ? (0, import_utf8.parseUTF8BigInt)(bytes2, start, end) ?? null : (0, import_utf8.parseUTF8Number)(bytes2, start, end) ?? null;
1452
+ if (result === null)
1453
+ throw new ExpressionEvaluationError("conversion", `Invalid text for CAST to ${target}`);
1454
+ if (integer && !wideInteger)
1455
+ result = Number(result);
1456
+ } else if (target === "bool")
1457
+ result = value;
1458
+ else if (wideInteger) {
1459
+ if (typeof value === "number" && !Number.isFinite(value))
1460
+ throw new ExpressionEvaluationError("conversion", "Non-finite integer CAST");
1461
+ result = typeof value === "bigint" ? value : BigInt(Math.trunc(value));
1462
+ } else if (integer)
1463
+ result = Math.trunc(Number(value));
1464
+ else
1465
+ result = Number(value);
1466
+ if (halfRound)
1467
+ result = halfRound(result);
1468
+ if (target === "float32")
1469
+ result = Math.fround(result);
1470
+ if ((target === "float16" || target === "float32" || target === "float64") && !Number.isFinite(result))
1471
+ throw new ExpressionEvaluationError("overflow", "Floating CAST overflow or non-finite value");
1472
+ validate(result);
1473
+ return result;
1474
+ }
1475
+ };
1476
+ }
1477
+
1478
+ // dist/arrow/like.js
1479
+ function compileUTF8Like(pattern, insensitive, escape) {
1480
+ if (escape !== void 0 && [...escape].length !== 1) {
1481
+ throw new Error("LIKE ESCAPE requires one character");
1482
+ }
1483
+ const tokens = [];
1484
+ let escaped = false;
1485
+ for (const character of pattern) {
1486
+ if (!escaped && character === escape) {
1487
+ escaped = true;
1488
+ continue;
1489
+ }
1490
+ tokens.push(!escaped && character === "%" ? -1 : !escaped && character === "_" ? -2 : fold(character.codePointAt(0), insensitive));
1491
+ escaped = false;
1492
+ }
1493
+ if (escaped)
1494
+ throw new Error("LIKE pattern ends with ESCAPE");
1495
+ return (bytes2, start, end) => {
1496
+ let offset = start;
1497
+ let token = 0;
1498
+ let wildcard = -1;
1499
+ let retry = start;
1500
+ while (offset < end) {
1501
+ if (tokens[token] === -1) {
1502
+ wildcard = token++;
1503
+ retry = offset;
1504
+ continue;
1505
+ }
1506
+ const [point, next] = readCodePoint(bytes2, offset);
1507
+ if (tokens[token] === -2 || tokens[token] === fold(point, insensitive)) {
1508
+ token++;
1509
+ offset = next;
1510
+ } else if (wildcard >= 0) {
1511
+ retry = readCodePoint(bytes2, retry)[1];
1512
+ offset = retry;
1513
+ token = wildcard + 1;
1514
+ } else {
1515
+ return false;
1516
+ }
1517
+ }
1518
+ while (tokens[token] === -1)
1519
+ token++;
1520
+ return token === tokens.length;
1521
+ };
1522
+ }
1523
+ function fold(point, insensitive) {
1524
+ if (!insensitive)
1525
+ return point;
1526
+ if (point < 128)
1527
+ return point >= 65 && point <= 90 ? point + 32 : point;
1528
+ const folded = String.fromCodePoint(point).toLowerCase();
1529
+ return folded.length === 1 && folded.charCodeAt(0) < 128 ? folded.charCodeAt(0) : folded;
1530
+ }
1531
+ function readCodePoint(bytes2, offset) {
1532
+ const first = bytes2[offset++];
1533
+ if (first < 128)
1534
+ return [first, offset];
1535
+ const count = first < 224 ? 1 : first < 240 ? 2 : 3;
1536
+ let point = first & (count === 1 ? 31 : count === 2 ? 15 : 7);
1537
+ for (let index = 0; index < count; index++)
1538
+ point = point << 6 | bytes2[offset++] & 63;
1539
+ return [point, offset];
1540
+ }
1541
+
1542
+ // dist/arrow/signature.js
1543
+ var import_apache_arrow4 = require("apache-arrow");
1544
+ function physicalKey(type) {
1545
+ var _a2;
1546
+ try {
1547
+ return import_apache_arrow4.DataType.isDictionary(type) ? `dictionary:${typeKey(type.indices)}:${typeKey(type.dictionary)}:${type.isOrdered}` : typeKey(type);
1548
+ } catch {
1549
+ const properties = [
1550
+ "bitWidth",
1551
+ "isSigned",
1552
+ "precision",
1553
+ "scale",
1554
+ "unit",
1555
+ "timezone",
1556
+ "byteWidth",
1557
+ "listSize",
1558
+ "keysSorted",
1559
+ "isOrdered",
1560
+ "mode"
1561
+ ].map((key) => type[key]);
1562
+ return JSON.stringify([
1563
+ type.typeId,
1564
+ properties,
1565
+ import_apache_arrow4.DataType.isUnion(type) ? Array.from(type.typeIds) : null,
1566
+ import_apache_arrow4.DataType.isDictionary(type) ? [physicalKey(type.indices), physicalKey(type.dictionary), type.isOrdered] : null,
1567
+ (_a2 = type.children) == null ? void 0 : _a2.map((field) => [
1568
+ field.name,
1569
+ physicalKey(field.type),
1570
+ field.nullable,
1571
+ extensionKey(field)
1572
+ ])
1573
+ ]);
1574
+ }
1575
+ }
1576
+ function extensionKey(field) {
1577
+ return JSON.stringify([
1578
+ field.metadata.get("ARROW:extension:name"),
1579
+ field.metadata.get("ARROW:extension:metadata")
1580
+ ]);
1581
+ }
1582
+
1583
+ // dist/arrow/registry.js
1584
+ function createFunctionLookup(declarations = []) {
1585
+ var _a2;
1586
+ const functions = /* @__PURE__ */ new Map();
1587
+ for (const declaration of declarations) {
1588
+ const name = declaration == null ? void 0 : declaration.name;
1589
+ if (typeof name !== "string" || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name))
1590
+ throw new Error("Invalid Arrow function name");
1591
+ if ([
1592
+ "TRY",
1593
+ "COALESCE",
1594
+ "array",
1595
+ "array_float16",
1596
+ "array_float32",
1597
+ "array_float64",
1598
+ "array_uint8",
1599
+ "PACK_UNORM8",
1600
+ "LIST_EXTRACT",
1601
+ "STRUCT_EXTRACT",
1602
+ "cast",
1603
+ "in",
1604
+ "isNull",
1605
+ "isNotNull",
1606
+ "parseNumber",
1607
+ "parseBigInt",
1608
+ "parseBoolean",
1609
+ "toFloat64",
1610
+ "toInt32",
1611
+ "toInt64"
1612
+ ].includes(name))
1613
+ throw new Error(`Reserved Arrow function: ${name}`);
1614
+ if (!Array.isArray(declaration.prototypes) || !declaration.prototypes.length)
1615
+ throw new Error("Arrow functions require one or more prototypes");
1616
+ const prototypes = [...((_a2 = functions.get(name)) == null ? void 0 : _a2.prototypes) ?? []];
1617
+ for (const prototype of declaration.prototypes) {
1618
+ if (!prototype || typeof prototype !== "object" || !Array.isArray(prototype.arguments) || !prototype.result || typeof prototype.evaluate !== "function")
1619
+ throw new Error("Arrow prototypes require argument fields, a result field and evaluate");
1620
+ if (prototype.nullHandling !== void 0 && !["propagate", "call"].includes(prototype.nullHandling))
1621
+ throw new Error("Unsupported null handling");
1622
+ if (prototype.evaluateScalar !== void 0 && typeof prototype.evaluateScalar !== "function")
1623
+ throw new Error("Arrow function evaluateScalar must be a function");
1624
+ const key = JSON.stringify(prototype.arguments.map((field) => [
1625
+ physicalKey(field.type),
1626
+ [...field.metadata].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
1627
+ ]));
1628
+ if (prototypes.some((existing) => JSON.stringify(existing.arguments.map((field) => [
1629
+ physicalKey(field.type),
1630
+ [...field.metadata].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
1631
+ ])) === key))
1632
+ throw new Error(`Duplicate Arrow function signature: ${name}`);
1633
+ prototypes.push(Object.freeze({ ...prototype, arguments: Object.freeze([...prototype.arguments]) }));
1634
+ }
1635
+ functions.set(name, Object.freeze({ name, prototypes: Object.freeze(prototypes) }));
1636
+ }
1637
+ return functions;
1638
+ }
1639
+
1640
+ // dist/arrow/list-values.js
1641
+ var import_apache_arrow5 = require("apache-arrow");
1642
+ function isTupleType(type) {
1643
+ if (!import_apache_arrow5.DataType.isFixedSizeList(type))
1644
+ return false;
1645
+ const child = type.children[0];
1646
+ if (!Number.isSafeInteger(type.listSize) || type.listSize <= 0 || !child || child.nullable)
1647
+ return false;
1648
+ if (!import_apache_arrow5.DataType.isInt(child.type) && !import_apache_arrow5.DataType.isFloat(child.type))
1649
+ return false;
1650
+ typeKey(child.type);
1651
+ return true;
1652
+ }
1653
+ function nullTupleVector(type, length) {
1654
+ const childType = type.children[0].type;
1655
+ const child = (0, import_apache_arrow5.makeData)({
1656
+ type: childType,
1657
+ length: length * type.listSize,
1658
+ data: new childType.ArrayType(length * type.listSize)
1659
+ });
1660
+ return (0, import_apache_arrow5.makeVector)((0, import_apache_arrow5.makeData)({
1661
+ type,
1662
+ length,
1663
+ child,
1664
+ nullCount: length,
1665
+ nullBitmap: new Uint8Array(Math.ceil(length / 8))
1666
+ }));
1667
+ }
1668
+ function maskTupleVector(vector, active) {
1669
+ if (!active.some((value) => !value))
1670
+ return vector;
1671
+ let start = 0;
1672
+ const chunks = vector.data.map((data) => {
1673
+ const bitmap = new Uint8Array(Math.ceil((data.offset + data.length) / 8));
1674
+ let nullCount = 0;
1675
+ for (let row = 0; row < data.length; row++) {
1676
+ if (active[start + row] && data.getValid(row)) {
1677
+ const bit = data.offset + row;
1678
+ bitmap[bit >> 3] |= 1 << (bit & 7);
1679
+ } else
1680
+ nullCount++;
1681
+ }
1682
+ start += data.length;
1683
+ const buffers = data.buffers;
1684
+ buffers[2] = bitmap;
1685
+ return data.clone(data.type, data.offset, data.length, nullCount, buffers);
1686
+ });
1687
+ return new import_apache_arrow5.Vector(chunks);
1688
+ }
1689
+ function validateTupleVector(vector, field, active) {
1690
+ const type = field.type;
1691
+ let start = 0;
1692
+ for (const data of vector.data) {
1693
+ const child = data.children[0];
1694
+ if (!child || child.length < data.length * type.listSize)
1695
+ throw new Error("Invalid fixed-size list child length");
1696
+ for (let row = 0; row < data.length; row++) {
1697
+ if (!active[start + row])
1698
+ continue;
1699
+ if (!data.getValid(row)) {
1700
+ if (!field.nullable)
1701
+ throw new Error(`Function ${field.name} returned null for a non-nullable result`);
1702
+ continue;
1703
+ }
1704
+ for (let component = 0; component < type.listSize; component++) {
1705
+ if (!child.getValid(row * type.listSize + component))
1706
+ throw new Error("Fixed-size list result contains a null non-nullable component");
1707
+ }
1708
+ }
1709
+ start += data.length;
1710
+ }
1711
+ }
1712
+ function selectTupleVectors(type, yes, no, selected, active) {
1713
+ const result = nullTupleVector(type, active.length);
1714
+ const data = result.data[0];
1715
+ const child = data.children[0];
1716
+ const values = import_apache_arrow5.DataType.isFloat(child.type) && child.type.precision === import_apache_arrow5.Precision.HALF ? float16Values(child.values) : child.values;
1717
+ const a = new ColumnReader(yes.getChildAt(0));
1718
+ const b = new ColumnReader(no.getChildAt(0));
1719
+ const aValid = new ColumnReader(yes);
1720
+ const bValid = new ColumnReader(no);
1721
+ for (let row = 0; row < active.length; row++) {
1722
+ if (!active[row])
1723
+ continue;
1724
+ const reader = selected[row] ? a : b;
1725
+ if (!(selected[row] ? aValid : bValid).isValid(row))
1726
+ continue;
1727
+ data.setValid(row, true);
1728
+ for (let component = 0; component < type.listSize; component++) {
1729
+ const index = row * type.listSize + component;
1730
+ values[index] = reader.get(index);
1731
+ }
1732
+ }
1733
+ return result;
1734
+ }
1735
+ function compileArrayLiteral(ast, type) {
1736
+ if (!import_apache_arrow5.DataType.isList(type) && !import_apache_arrow5.DataType.isFixedSizeList(type))
1737
+ throw new Error("Array literals require a declared List or FixedSizeList argument");
1738
+ const listType = type;
1739
+ const child = listType.children[0];
1740
+ if (import_apache_arrow5.DataType.isDictionary(child.type))
1741
+ throw new Error("Array literal elements require primitive types");
1742
+ typeKey(child.type);
1743
+ if (ast.elements.length > 4096)
1744
+ throw new Error("Array literal exceeds 4096 elements");
1745
+ if (import_apache_arrow5.DataType.isFixedSizeList(type) && ast.elements.length !== type.listSize)
1746
+ throw new Error("Array literal length must match its FixedSizeList type");
1747
+ if (import_apache_arrow5.DataType.isFixedSizeList(type) && !isTupleType(type))
1748
+ throw new Error("Fixed-size array literals require non-nullable numeric elements");
1749
+ const round = import_apache_arrow5.DataType.isFloat(child.type) ? child.type.precision === import_apache_arrow5.Precision.HALF ? roundFloat16() : child.type.precision === import_apache_arrow5.Precision.SINGLE ? Math.fround : void 0 : void 0;
1750
+ const values = Array.from(ast.elements, (element) => {
1751
+ var _a2;
1752
+ let value;
1753
+ if ((element == null ? void 0 : element.type) === "Literal")
1754
+ value = element.value;
1755
+ else if ((element == null ? void 0 : element.type) === "UnaryExpression" && ["+", "-"].includes(element.operator) && ((_a2 = element.argument) == null ? void 0 : _a2.type) === "Literal" && typeof element.argument.value === "number")
1756
+ value = element.operator === "-" ? -element.argument.value : element.argument.value;
1757
+ else
1758
+ throw new Error("Array elements must be scalar literals");
1759
+ if (value === null && !child.nullable)
1760
+ throw new Error("Array literal contains a null non-nullable element");
1761
+ validateValue(value, child.type);
1762
+ if (round && typeof value === "number") {
1763
+ const rounded = round(value);
1764
+ if (Number.isFinite(value) && !Number.isFinite(rounded))
1765
+ throw new Error(`Numeric literal overflow for ${child.type}`);
1766
+ return rounded;
1767
+ }
1768
+ return value;
1769
+ });
1770
+ const literal = (0, import_apache_arrow5.vectorFromArray)([values], listType);
1771
+ const dictionaryType = new import_apache_arrow5.Dictionary(listType, new import_apache_arrow5.Uint8());
1772
+ let cached;
1773
+ return (length) => {
1774
+ if (!import_apache_arrow5.DataType.isFixedSizeList(listType) && (cached == null ? void 0 : cached.length) === length)
1775
+ return cached;
1776
+ if (import_apache_arrow5.DataType.isFixedSizeList(listType)) {
1777
+ const result = nullTupleVector(listType, length);
1778
+ const data = result.data[0];
1779
+ const childData = data.children[0];
1780
+ const components = import_apache_arrow5.DataType.isFloat(childData.type) && childData.type.precision === import_apache_arrow5.Precision.HALF ? float16Values(childData.values) : childData.values;
1781
+ for (let row = 0; row < length; row++) {
1782
+ data.setValid(row, true);
1783
+ for (let component = 0; component < listType.listSize; component++)
1784
+ components[row * listType.listSize + component] = values[component];
1785
+ }
1786
+ cached = result;
1787
+ } else {
1788
+ cached = (0, import_apache_arrow5.makeVector)((0, import_apache_arrow5.makeData)({ type: dictionaryType, length, data: new Uint8Array(length), dictionary: literal }));
1789
+ }
1790
+ return cached;
1791
+ };
1792
+ }
1793
+
1794
+ // dist/arrow/compiler.js
1795
+ var encoder = new TextEncoder();
1796
+ var bool = new import_apache_arrow6.Bool();
1797
+ function compileArrowExpression(expression, options) {
1798
+ const fields = [...options.inputSchema.fields];
1799
+ if (new Set(fields.map((field) => field.name)).size !== fields.length)
1800
+ throw new Error("Expression input field names must be unique");
1801
+ const ast = parse(expression);
1802
+ validateExpressionAST(ast);
1803
+ const root = bind(ast, {
1804
+ ...options,
1805
+ functionLookup: createFunctionLookup(options.functions)
1806
+ });
1807
+ const keys = fields.map((field) => ({
1808
+ name: field.name,
1809
+ type: physicalKey(field.type),
1810
+ nullable: field.nullable,
1811
+ extension: extensionKey(field)
1812
+ }));
1813
+ const validateSchema = (schema) => {
1814
+ if (schema.fields.length !== keys.length || schema.fields.some((field, index) => {
1815
+ const expected = keys[index];
1816
+ return field.name !== expected.name || physicalKey(field.type) !== expected.type || field.nullable !== expected.nullable || extensionKey(field) !== expected.extension;
1817
+ }))
1818
+ throw new Error("Arrow expression input schema mismatch");
1819
+ };
1820
+ const validateMask = (mask, length) => {
1821
+ if (mask && (mask.length !== length || mask.some((value) => value !== 0 && value !== 1)))
1822
+ throw new Error("activeRows must contain one 0 or 1 per input row");
1823
+ };
1824
+ const evaluate = (batch, evaluation = {}) => {
1825
+ var _a2, _b;
1826
+ (_a2 = evaluation.signal) == null ? void 0 : _a2.throwIfAborted();
1827
+ validateSchema(batch.schema);
1828
+ validateMask(evaluation.activeRows, batch.numRows);
1829
+ const active = evaluation.activeRows ? evaluation.activeRows.slice() : new Uint8Array(batch.numRows).fill(1);
1830
+ const prepared = root.prepare(batch, active, {});
1831
+ const result = isTupleType(root.field.type) ? maskTupleVector(prepared.vector, active) : isNestedType(root.field.type) ? nestedVector(prepared.vector, root.field.type, active) : prepared.vector && !import_apache_arrow6.DataType.isDictionary(prepared.vector.type) && !active.some((value) => !value) ? prepared.vector : output(root.field, active, prepared.get);
1832
+ (_b = evaluation.signal) == null ? void 0 : _b.throwIfAborted();
1833
+ return result;
1834
+ };
1835
+ return Object.freeze({
1836
+ outputField: root.field,
1837
+ evaluate,
1838
+ evaluateTable(arrowTable, evaluation = {}) {
1839
+ var _a2;
1840
+ (_a2 = evaluation.signal) == null ? void 0 : _a2.throwIfAborted();
1841
+ validateSchema(arrowTable.schema);
1842
+ validateMask(evaluation.activeRows, arrowTable.numRows);
1843
+ let offset = 0;
1844
+ const chunks = arrowTable.batches.flatMap((batch) => {
1845
+ var _a3;
1846
+ const activeRows = (_a3 = evaluation.activeRows) == null ? void 0 : _a3.subarray(offset, offset + batch.numRows);
1847
+ offset += batch.numRows;
1848
+ return evaluate(batch, { ...evaluation, activeRows }).data;
1849
+ });
1850
+ return chunks.length ? new import_apache_arrow6.Vector(chunks) : isTupleType(root.field.type) ? nullTupleVector(root.field.type, 0) : isNestedType(root.field.type) ? (0, import_apache_arrow6.vectorFromArray)([], root.field.type) : output(root.field, new Uint8Array(0), () => null);
1851
+ }
1852
+ });
1853
+ }
1854
+ function output(field, active, evaluate) {
1855
+ const type = valueType(field.type);
1856
+ const validate = createValueValidator(type);
1857
+ if (import_apache_arrow6.DataType.isUtf8(type) || import_apache_arrow6.DataType.isBinary(type) || import_apache_arrow6.DataType.isFixedSizeBinary(type)) {
1858
+ const values = new Array(active.length).fill(null);
1859
+ for (let row = 0; row < active.length; row++)
1860
+ if (active[row]) {
1861
+ const value = evaluate(row);
1862
+ if (value === null && !field.nullable)
1863
+ throw new Error(`Non-nullable expression ${field.name} returned null`);
1864
+ validate(value);
1865
+ values[row] = value;
1866
+ }
1867
+ return (0, import_apache_arrow6.vectorFromArray)(values, field.type);
1868
+ }
1869
+ if (import_apache_arrow6.DataType.isNull(type)) {
1870
+ for (let row = 0; row < active.length; row++)
1871
+ if (active[row])
1872
+ validate(evaluate(row));
1873
+ return (0, import_apache_arrow6.makeVector)((0, import_apache_arrow6.makeData)({ type, length: active.length }));
1874
+ }
1875
+ const isBoolean = import_apache_arrow6.DataType.isBool(type);
1876
+ const data = isBoolean ? new Uint8Array(Math.ceil(active.length / 8)) : new type.ArrayType(active.length);
1877
+ const numericData = import_apache_arrow6.DataType.isFloat(type) && type.precision === import_apache_arrow6.Precision.HALF ? float16Values(data) : data;
1878
+ const validity = new Uint8Array(Math.ceil(active.length / 8));
1879
+ let nullCount = 0;
1880
+ for (let row = 0; row < active.length; row++) {
1881
+ if (!active[row]) {
1882
+ nullCount++;
1883
+ continue;
1884
+ }
1885
+ const value = evaluate(row);
1886
+ if (value === null) {
1887
+ if (!field.nullable)
1888
+ throw new Error(`Non-nullable expression ${field.name} returned null`);
1889
+ nullCount++;
1890
+ continue;
1891
+ }
1892
+ validate(value);
1893
+ validity[row >> 3] |= 1 << (row & 7);
1894
+ if (isBoolean) {
1895
+ if (value)
1896
+ data[row >> 3] |= 1 << (row & 7);
1897
+ } else
1898
+ numericData[row] = value;
1899
+ }
1900
+ return (0, import_apache_arrow6.makeVector)((0, import_apache_arrow6.makeData)({
1901
+ type,
1902
+ data,
1903
+ length: active.length,
1904
+ nullBitmap: validity,
1905
+ nullCount
1906
+ }));
1907
+ }
1908
+ function sourceReader(vector) {
1909
+ const data = vector.data[0];
1910
+ if (vector.data.length === 1 && (import_apache_arrow6.DataType.isInt(data.type) || import_apache_arrow6.DataType.isFloat(data.type) && data.type.precision !== import_apache_arrow6.Precision.HALF)) {
1911
+ const values = data.values, bitmap = data.nullBitmap, offset = data.offset;
1912
+ const valid = data.nullCount ? (row) => Boolean(bitmap[offset + row >> 3] & 1 << (offset + row & 7)) : () => true;
1913
+ return {
1914
+ vector,
1915
+ get: (row) => valid(row) ? values[row] : null,
1916
+ isNull: (row) => !valid(row)
1917
+ };
1918
+ }
1919
+ const reader = new ColumnReader(vector);
1920
+ return {
1921
+ vector,
1922
+ get: (row) => reader.get(row),
1923
+ isNull: (row) => !reader.isValid(row),
1924
+ bytes: typeKey(vector.type) === "utf8" ? (row) => reader.isValid(row) ? reader.utf8(row) : null : void 0
1925
+ };
1926
+ }
1927
+ function vectorReader(vector) {
1928
+ try {
1929
+ typeKey(vector.type);
1930
+ return sourceReader(vector);
1931
+ } catch {
1932
+ }
1933
+ const reader = new ColumnReader(vector);
1934
+ return {
1935
+ vector,
1936
+ isNull: (row) => !reader.isValid(row),
1937
+ get: () => {
1938
+ throw new Error("Nested values require a vector kernel");
1939
+ }
1940
+ };
1941
+ }
1942
+ function bytes(value, row) {
1943
+ if (value.bytes)
1944
+ return value.bytes(row);
1945
+ const text = value.get(row);
1946
+ if (text === null)
1947
+ return null;
1948
+ const encoded = encoder.encode(text);
1949
+ return [encoded, 0, encoded.length];
1950
+ }
1951
+ function bind(ast, options, expected, vectorInput = false) {
1952
+ const node = bindNode(ast, options, expected, vectorInput);
1953
+ return {
1954
+ ...node,
1955
+ prepare(batch, active, context) {
1956
+ const mask = context.failed ? active.map((value, row) => value && !context.failed[row] ? 1 : 0) : active;
1957
+ const prepared = node.prepare(batch, mask, context);
1958
+ if (!context.failed)
1959
+ return prepared;
1960
+ const guard = (row, read) => {
1961
+ if (!mask[row] || context.failed[row])
1962
+ return null;
1963
+ try {
1964
+ const value = read();
1965
+ return context.failed[row] ? null : value;
1966
+ } catch (error) {
1967
+ if (!isExpressionEvaluationError(error))
1968
+ throw error;
1969
+ context.failed[row] = 1;
1970
+ return null;
1971
+ }
1972
+ };
1973
+ return {
1974
+ ...prepared,
1975
+ get: (row) => guard(row, () => prepared.get(row)),
1976
+ bytes: prepared.bytes ? (row) => guard(row, () => prepared.bytes(row)) : void 0,
1977
+ isNull: (row) => guard(row, () => prepared.isNull ? prepared.isNull(row) : prepared.get(row) === null) ?? true
1978
+ };
1979
+ }
1980
+ };
1981
+ }
1982
+ function prepareInput(node, batch, active, context, force) {
1983
+ const prepared = node.prepare(batch, active, context);
1984
+ if (!context.failed || !force || prepared.vector)
1985
+ return prepared;
1986
+ const mask = active.map((value, row) => value && !context.failed[row] ? 1 : 0);
1987
+ const field = new import_apache_arrow6.Field(node.field.name, node.field.type, true, node.field.metadata);
1988
+ return sourceReader(output(field, mask, prepared.get));
1989
+ }
1990
+ function bindNode(ast, options, expected, vectorInput = false) {
1991
+ if (isSignedLiteral(ast)) {
1992
+ const value = ast.operator === "-" ? -ast.argument.value : ast.argument.value;
1993
+ return bind({ type: "Literal", value }, options, expected, vectorInput);
1994
+ }
1995
+ if (ast.type === "ArrayExpression") {
1996
+ if (!expected)
1997
+ throw new Error("Array literals require a declared list type");
1998
+ const materialize = compileArrayLiteral(ast, expected);
1999
+ return {
2000
+ field: new import_apache_arrow6.Field("literal", expected, false),
2001
+ hasKernel: false,
2002
+ prepare: (_batch, active) => vectorReader(materialize(active.length))
2003
+ };
2004
+ }
2005
+ if (ast.type === "Identifier") {
2006
+ const index = options.inputSchema.fields.findIndex((field) => field.name === ast.name);
2007
+ if (index < 0)
2008
+ throw new Error(`Unknown Arrow expression field: ${ast.name}`);
2009
+ const source = options.inputSchema.fields[index];
2010
+ const tuple = isTupleType(source.type);
2011
+ if (!vectorInput && !tuple)
2012
+ typeKey(source.type);
2013
+ return {
2014
+ field: new import_apache_arrow6.Field(source.name, vectorInput ? source.type : valueType(source.type), source.nullable, source.metadata),
2015
+ hasKernel: false,
2016
+ prepare: (batch) => {
2017
+ const vector = batch.getChildAt(index);
2018
+ return vectorInput || tuple ? vectorReader(vector) : sourceReader(vector);
2019
+ }
2020
+ };
2021
+ }
2022
+ if (ast.type === "Literal") {
2023
+ if (vectorInput && expected && import_apache_arrow6.DataType.isDictionary(expected))
2024
+ throw new Error("Dictionary function arguments require a dictionary-encoded source column");
2025
+ let value = ast.value;
2026
+ if (expected && import_apache_arrow6.DataType.isInt(expected) && expected.bitWidth === 64 && typeof value === "number" && Number.isSafeInteger(value))
2027
+ value = BigInt(value);
2028
+ const type = expected ?? (value === null ? new import_apache_arrow6.Null() : typeof value === "boolean" ? bool : typeof value === "number" ? new import_apache_arrow6.Float64() : typeof value === "bigint" ? new import_apache_arrow6.Int64() : new import_apache_arrow6.Utf8());
2029
+ if (value === null && isTupleType(type))
2030
+ return {
2031
+ field: new import_apache_arrow6.Field("literal", type, true),
2032
+ hasKernel: false,
2033
+ prepare: (_batch, active) => vectorReader(nullTupleVector(type, active.length))
2034
+ };
2035
+ if (value === null && import_apache_arrow6.DataType.isList(type)) {
2036
+ const dictionary = (0, import_apache_arrow6.vectorFromArray)([null], type);
2037
+ return {
2038
+ field: new import_apache_arrow6.Field("literal", type, true),
2039
+ hasKernel: false,
2040
+ prepare: (_batch, active) => vectorReader((0, import_apache_arrow6.makeVector)((0, import_apache_arrow6.makeData)({
2041
+ type: new import_apache_arrow6.Dictionary(type, new import_apache_arrow6.Int32()),
2042
+ length: active.length,
2043
+ data: new Int32Array(active.length),
2044
+ dictionary
2045
+ })))
2046
+ };
2047
+ }
2048
+ if (value === null && isNestedType(type))
2049
+ return {
2050
+ field: new import_apache_arrow6.Field("literal", type, true),
2051
+ hasKernel: false,
2052
+ prepare: (_batch, active) => vectorReader((0, import_apache_arrow6.vectorFromArray)(Array(active.length).fill(null), type))
2053
+ };
2054
+ validateValue(value, type);
2055
+ const rounded = roundToType(type)(value);
2056
+ if (typeof value === "number" && Number.isFinite(value) && !Number.isFinite(rounded))
2057
+ throw new Error(`Numeric literal overflow for ${type}`);
2058
+ const encoded = typeof value === "string" ? encoder.encode(value) : void 0;
2059
+ const range = encoded ? [encoded, 0, encoded.length] : void 0;
2060
+ return {
2061
+ field: new import_apache_arrow6.Field("literal", type, value === null),
2062
+ hasKernel: false,
2063
+ prepare: () => ({
2064
+ get: () => rounded,
2065
+ isNull: () => value === null,
2066
+ bytes: range ? () => range : void 0
2067
+ })
2068
+ };
2069
+ }
2070
+ if (ast.type === "CallExpression")
2071
+ return bindCall(ast, options, expected);
2072
+ if (ast.type === "ConditionalExpression") {
2073
+ const condition = bind(ast.test, options, bool);
2074
+ requireType(condition, "bool");
2075
+ let yes, no;
2076
+ if (isContextualLiteral(ast.consequent) && !isContextualLiteral(ast.alternate)) {
2077
+ no = bind(ast.alternate, options, expected);
2078
+ yes = bind(ast.consequent, options, no.field.type);
2079
+ } else {
2080
+ yes = bind(ast.consequent, options, expected);
2081
+ no = bind(ast.alternate, options, isContextualLiteral(ast.alternate) && !import_apache_arrow6.DataType.isNull(yes.field.type) ? yes.field.type : expected);
2082
+ if (isContextualLiteral(ast.consequent) && !import_apache_arrow6.DataType.isNull(no.field.type))
2083
+ yes = bind(ast.consequent, options, no.field.type);
2084
+ }
2085
+ const tuple = isTupleType(yes.field.type);
2086
+ const list = import_apache_arrow6.DataType.isList(yes.field.type);
2087
+ const nested = isNestedType(yes.field.type);
2088
+ if (nested) {
2089
+ if (physicalKey(yes.field.type) !== physicalKey(no.field.type))
2090
+ throw new Error("Arrow expression operand types must match");
2091
+ if (!isContextualLiteral(ast.consequent) && !isContextualLiteral(ast.alternate) && extensionKey(yes.field) !== extensionKey(no.field))
2092
+ throw new Error("Arrow expression branch extension metadata must match");
2093
+ } else
2094
+ sameType(yes, no);
2095
+ const metadata = isContextualLiteral(ast.consequent) ? no.field.metadata : yes.field.metadata;
2096
+ const field = new import_apache_arrow6.Field("conditional", yes.field.type, yes.field.nullable || no.field.nullable, metadata);
2097
+ return {
2098
+ field,
2099
+ hasKernel: nested || condition.hasKernel || yes.hasKernel || no.hasKernel,
2100
+ prepare(batch, active, context) {
2101
+ const test = condition.prepare(batch, active, context);
2102
+ const selected = nested || yes.hasKernel || no.hasKernel ? active.map((value, row) => value && test.get(row) === true ? 1 : 0) : void 0;
2103
+ const a = yes.prepare(batch, selected ?? active, context);
2104
+ const b = no.prepare(batch, selected ? active.map((value, row) => value && !selected[row] ? 1 : 0) : active, context);
2105
+ if (list && import_apache_arrow6.DataType.isDictionary(a.vector.type) && import_apache_arrow6.DataType.isDictionary(b.vector.type))
2106
+ return vectorReader(selectListVectors(field.type, a.vector, b.vector, selected, active));
2107
+ if (tuple) {
2108
+ const validActive = context.failed ? active.map((value, row) => value && !context.failed[row] ? 1 : 0) : active;
2109
+ const yesMask = validActive.map((value, row) => value && selected[row] ? 1 : 0);
2110
+ const noMask = validActive.map((value, row) => value && !selected[row] ? 1 : 0);
2111
+ validateTupleVector(a.vector, yes.field, yesMask);
2112
+ validateTupleVector(b.vector, no.field, noMask);
2113
+ return vectorReader(selectTupleVectors(field.type, a.vector, b.vector, yesMask, validActive));
2114
+ }
2115
+ if (nested) {
2116
+ const values = Array.from(active, (valid, row) => {
2117
+ var _a2;
2118
+ return valid && !((_a2 = context.failed) == null ? void 0 : _a2[row]) ? nestedValue((selected[row] ? a : b).vector.get(row), field.type) : null;
2119
+ });
2120
+ return vectorReader((0, import_apache_arrow6.vectorFromArray)(values, field.type));
2121
+ }
2122
+ const choose = (row) => (selected ? selected[row] : test.get(row) === true) ? a : b;
2123
+ return {
2124
+ get: (row) => choose(row).get(row),
2125
+ isNull: (row) => {
2126
+ const branch = choose(row);
2127
+ return branch.isNull ? branch.isNull(row) : branch.get(row) === null;
2128
+ },
2129
+ bytes: typeKey(field.type) === "utf8" ? (row) => bytes(choose(row), row) : void 0
2130
+ };
2131
+ }
2132
+ };
2133
+ }
2134
+ if (ast.type === "UnaryExpression") {
2135
+ const argument = bind(ast.argument, options, ast.operator === "!" ? bool : void 0);
2136
+ if (ast.operator === "!")
2137
+ requireType(argument, "bool");
2138
+ else if (ast.operator === "+" || ast.operator === "-")
2139
+ requireNumeric(argument);
2140
+ else
2141
+ throw new Error(`Unsupported unary operator: ${ast.operator}`);
2142
+ const validate = createValueValidator(argument.field.type);
2143
+ const round = roundToType(argument.field.type);
2144
+ return {
2145
+ field: new import_apache_arrow6.Field("unary", argument.field.type, argument.field.nullable),
2146
+ hasKernel: argument.hasKernel,
2147
+ prepare(batch, active, context) {
2148
+ const child = argument.prepare(batch, active, context);
2149
+ return {
2150
+ get: (row) => {
2151
+ const value = child.get(row);
2152
+ if (value === null)
2153
+ return null;
2154
+ const result = ast.operator === "!" ? !value : ast.operator === "+" ? value : -value;
2155
+ validate(result);
2156
+ return round(result);
2157
+ }
2158
+ };
2159
+ }
2160
+ };
2161
+ }
2162
+ if (ast.type === "BinaryExpression" || ast.type === "LogicalExpression")
2163
+ return bindBinary(ast, options);
2164
+ throw new Error(`Unsupported Arrow expression syntax: ${ast.type}`);
2165
+ }
2166
+ function sameType(a, b) {
2167
+ if (typeKey(a.field.type) !== typeKey(b.field.type))
2168
+ throw new Error("Arrow expression operand types must match");
2169
+ }
2170
+ function requireType(node, key) {
2171
+ if (typeKey(node.field.type) !== key)
2172
+ throw new Error(`Arrow expression requires ${key}`);
2173
+ }
2174
+ function requireNumeric(node) {
2175
+ if (!import_apache_arrow6.DataType.isInt(node.field.type) && !import_apache_arrow6.DataType.isFloat(node.field.type))
2176
+ throw new Error("Arrow expression requires numeric operands");
2177
+ }
2178
+ function bindBinary(ast, options) {
2179
+ const op = ast.operator, logical = op === "&&" || op === "||";
2180
+ let left = bind(ast.left, options, logical ? bool : void 0), right = bind(ast.right, options, logical ? bool : void 0);
2181
+ if (!logical) {
2182
+ if (isContextualLiteral(ast.left) && !import_apache_arrow6.DataType.isNull(right.field.type))
2183
+ left = bind(ast.left, options, right.field.type);
2184
+ if (isContextualLiteral(ast.right))
2185
+ right = bind(ast.right, options, left.field.type);
2186
+ }
2187
+ sameType(left, right);
2188
+ const comparison = ["==", "===", "!=", "!==", "<", "<=", ">", ">="].includes(op);
2189
+ if (logical)
2190
+ requireType(left, "bool");
2191
+ else if (!comparison) {
2192
+ if (!["+", "-", "*", "/", "%"].includes(op))
2193
+ throw new Error(`Unsupported binary operator: ${op}`);
2194
+ requireNumeric(left);
2195
+ }
2196
+ const type = left.field.type, utf8 = typeKey(type) === "utf8", binary = import_apache_arrow6.DataType.isBinary(type) || import_apache_arrow6.DataType.isFixedSizeBinary(type), integer = import_apache_arrow6.DataType.isInt(type);
2197
+ const validate = createValueValidator(type);
2198
+ const round = roundToType(type);
2199
+ const field = new import_apache_arrow6.Field("expression", logical || comparison ? bool : type, left.field.nullable || right.field.nullable);
2200
+ return {
2201
+ field,
2202
+ hasKernel: left.hasKernel || right.hasKernel,
2203
+ prepare(batch, active, context) {
2204
+ const a = prepareInput(left, batch, active, context, left.hasKernel || right.hasKernel);
2205
+ let truth;
2206
+ let mask = active;
2207
+ if (logical && right.hasKernel) {
2208
+ truth = new Uint8Array(active.length);
2209
+ mask = active.map((value, row) => {
2210
+ if (!value)
2211
+ return 0;
2212
+ const x = a.get(row);
2213
+ truth[row] = x === null ? 2 : x ? 1 : 0;
2214
+ return (op === "&&" ? x !== false : x !== true) ? 1 : 0;
2215
+ });
2216
+ }
2217
+ const b = right.prepare(batch, mask, context);
2218
+ return {
2219
+ get: (row) => {
2220
+ if (logical) {
2221
+ const x2 = truth ? truth[row] === 2 ? null : truth[row] === 1 : a.get(row);
2222
+ if (op === "&&" && x2 === false)
2223
+ return false;
2224
+ if (op === "||" && x2 === true)
2225
+ return true;
2226
+ const y2 = b.get(row);
2227
+ return op === "&&" ? y2 === false ? false : x2 === null || y2 === null ? null : true : y2 === true ? true : x2 === null || y2 === null ? null : false;
2228
+ }
2229
+ if (utf8) {
2230
+ const x2 = bytes(a, row), y2 = bytes(b, row);
2231
+ if (!x2 || !y2)
2232
+ return null;
2233
+ return compare(op, (0, import_utf82.compareUTF8)(x2[0], x2[1], x2[2], y2[0], y2[1], y2[2]), 0);
2234
+ }
2235
+ const x = a.get(row), y = b.get(row);
2236
+ if (x === null || y === null)
2237
+ return null;
2238
+ if (binary)
2239
+ return compare(op, (0, import_utf82.compareUTF8)(x, 0, x.length, y, 0, y.length), 0);
2240
+ if (comparison)
2241
+ return compare(op, x, y);
2242
+ if ((op === "/" || op === "%") && (y === 0 || y === 0n))
2243
+ throw new ExpressionEvaluationError("divisionByZero", "Division by zero");
2244
+ const result = op === "+" ? x + y : op === "-" ? x - y : op === "*" ? x * y : op === "/" ? integer && typeof x === "number" ? Math.trunc(x / y) : x / y : x % y;
2245
+ validate(result);
2246
+ const rounded = round(result);
2247
+ if (!integer && Number.isFinite(x) && Number.isFinite(y) && !Number.isFinite(rounded))
2248
+ throw new ExpressionEvaluationError("overflow", "Floating expression overflow");
2249
+ return rounded;
2250
+ }
2251
+ };
2252
+ }
2253
+ };
2254
+ }
2255
+ function compare(op, a, b) {
2256
+ switch (op) {
2257
+ case "==":
2258
+ case "===":
2259
+ return a === b;
2260
+ case "!=":
2261
+ case "!==":
2262
+ return a !== b;
2263
+ case "<":
2264
+ return a < b;
2265
+ case "<=":
2266
+ return a <= b;
2267
+ case ">":
2268
+ return a > b;
2269
+ case ">=":
2270
+ return a >= b;
2271
+ default:
2272
+ throw new Error("Invalid comparison");
2273
+ }
2274
+ }
2275
+ function selectListVectors(type, left, right, selected, active) {
2276
+ if (!import_apache_arrow6.DataType.isDictionary(left.type) || !import_apache_arrow6.DataType.isDictionary(right.type))
2277
+ throw new Error("Computed List arguments require array literal branches");
2278
+ const a = left.data[0], b = right.data[0];
2279
+ const leftDictionary = a.dictionary, rightDictionary = b.dictionary;
2280
+ const indices = new Int32Array(active.length);
2281
+ const valid = new Uint8Array(active.length);
2282
+ for (let row = 0; row < active.length; row++) {
2283
+ if (!active[row])
2284
+ continue;
2285
+ if (selected[row]) {
2286
+ indices[row] = Number(a.values[row]);
2287
+ valid[row] = a.getValid(row) ? 1 : 0;
2288
+ } else {
2289
+ indices[row] = leftDictionary.length + Number(b.values[row]);
2290
+ valid[row] = b.getValid(row) ? 1 : 0;
2291
+ }
2292
+ }
2293
+ return maskTupleVector((0, import_apache_arrow6.makeVector)((0, import_apache_arrow6.makeData)({
2294
+ type: new import_apache_arrow6.Dictionary(type, new import_apache_arrow6.Int32()),
2295
+ length: active.length,
2296
+ data: indices,
2297
+ dictionary: leftDictionary.concat(rightDictionary)
2298
+ })), valid);
2299
+ }
2300
+ function bindRecovery(name, expressions, options, expected) {
2301
+ if (expected && import_apache_arrow6.DataType.isDictionary(expected))
2302
+ throw new Error("Dictionary function arguments require a dictionary-encoded source column");
2303
+ if (name === "TRY" ? expressions.length < 1 || expressions.length > 2 : !expressions.length)
2304
+ throw new Error(`${name} has an invalid argument count`);
2305
+ const indices = expressions.map((_, index) => index);
2306
+ const ordered = [
2307
+ ...indices.filter((index) => !isContextualLiteral(expressions[index])),
2308
+ ...indices.filter((index) => isContextualLiteral(expressions[index]))
2309
+ ];
2310
+ let anchor = 0;
2311
+ let candidate;
2312
+ for (const index of ordered) {
2313
+ const expression = expressions[index];
2314
+ if (!expected && isContextualLiteral(expression) && containsContextualArray(expression))
2315
+ continue;
2316
+ const node = bind(expression, options, expected);
2317
+ if (!candidate || !import_apache_arrow6.DataType.isNull(node.field.type)) {
2318
+ anchor = index;
2319
+ candidate = node;
2320
+ }
2321
+ if (!import_apache_arrow6.DataType.isNull(node.field.type))
2322
+ break;
2323
+ }
2324
+ const first = candidate ?? bind(expressions[anchor], options, expected);
2325
+ const nodes = expressions.map((expression, index) => index === anchor ? first : bind(expression, options, first.field.type));
2326
+ for (const [index, node] of nodes.entries()) {
2327
+ if (physicalKey(node.field.type) !== physicalKey(first.field.type) || !isContextualLiteral(expressions[index]) && extensionKey(node.field) !== extensionKey(first.field))
2328
+ throw new Error(`${name} arguments must have matching types and metadata`);
2329
+ }
2330
+ const field = new import_apache_arrow6.Field(name.toLowerCase(), first.field.type, true, first.field.metadata);
2331
+ const tuple = isTupleType(field.type);
2332
+ const list = Boolean(expected && import_apache_arrow6.DataType.isList(expected) && import_apache_arrow6.DataType.isList(field.type));
2333
+ if (!tuple && !list)
2334
+ typeKey(field.type);
2335
+ return {
2336
+ field,
2337
+ hasKernel: true,
2338
+ prepare(batch, active, context) {
2339
+ const failed = new Uint8Array(active.length);
2340
+ const childContext = name === "TRY" ? { failed } : context;
2341
+ const child = nodes[0].prepare(batch, active, childContext);
2342
+ const nullable = (node) => new import_apache_arrow6.Field(node.field.name, node.field.type, true, node.field.metadata);
2343
+ const materialize = (node, prepared, mask) => tuple || list ? maskTupleVector(prepared.vector, mask) : output(nullable(node), mask, prepared.get);
2344
+ const original = materialize(nodes[0], child, active);
2345
+ const reader = tuple ? void 0 : new ColumnReader(original);
2346
+ let result = original;
2347
+ let pending = active.map((value, row) => value && (name === "TRY" ? failed[row] : tuple ? !original.isValid(row) : !reader.isValid(row)) ? 1 : 0);
2348
+ if ((tuple || list) && name === "TRY")
2349
+ result = maskTupleVector(result, active.map((value, row) => value && !failed[row] ? 1 : 0));
2350
+ for (let index = 1; index < nodes.length && pending.some(Boolean); index++) {
2351
+ const node = nodes[index];
2352
+ const fallback = node.prepare(batch, pending, context);
2353
+ const vector = materialize(node, fallback, pending);
2354
+ const keep = active.map((value, row) => value && !pending[row] ? 1 : 0);
2355
+ if (tuple)
2356
+ result = selectTupleVectors(field.type, result, vector, keep, active);
2357
+ else if (list)
2358
+ result = selectListVectors(field.type, result, vector, keep, active);
2359
+ else {
2360
+ const a = new ColumnReader(result), b = new ColumnReader(vector);
2361
+ result = output(field, active, (row) => pending[row] ? b.get(row) : a.get(row));
2362
+ }
2363
+ const next = tuple ? void 0 : new ColumnReader(vector);
2364
+ pending = pending.map((value, row) => value && (tuple ? !vector.isValid(row) : !next.isValid(row)) ? 1 : 0);
2365
+ }
2366
+ return vectorReader(result);
2367
+ }
2368
+ };
2369
+ }
2370
+ function bindGeometryCast(argument) {
2371
+ const source = valueType(argument.field.type);
2372
+ const metadata = new Map(argument.field.metadata);
2373
+ const extension = metadata.get("ARROW:extension:name");
2374
+ if (!import_apache_arrow6.DataType.isBinary(source) && !import_apache_arrow6.DataType.isNull(source) || extension && extension !== "geoarrow.wkb")
2375
+ throw new Error("GEOMETRY CAST requires Binary WKB input");
2376
+ metadata.set("ARROW:extension:name", "geoarrow.wkb");
2377
+ return {
2378
+ ...argument,
2379
+ field: new import_apache_arrow6.Field("cast", new import_apache_arrow6.Binary(), argument.field.nullable, metadata),
2380
+ prepare(batch, active, context) {
2381
+ const child = argument.prepare(batch, active, context);
2382
+ return { get: (row) => child.get(row) };
2383
+ }
2384
+ };
2385
+ }
2386
+ function bindMembership(arguments_, options) {
2387
+ if (arguments_.length < 2 || arguments_.length > 4097 || arguments_.slice(1).some((value) => value.type !== "Literal" && !isSignedLiteral(value)))
2388
+ throw new Error("IN requires a value and 1 to 4096 scalar literals");
2389
+ const argument = bind(arguments_[0], options);
2390
+ const utf8 = typeKey(argument.field.type) === "utf8";
2391
+ const literals = arguments_.slice(1).map((value) => bind(value, options, argument.field.type));
2392
+ return {
2393
+ field: new import_apache_arrow6.Field("in", bool, argument.field.nullable || literals.some((value) => value.field.nullable)),
2394
+ hasKernel: argument.hasKernel,
2395
+ prepare(batch, active, context) {
2396
+ const source = argument.prepare(batch, active, context);
2397
+ const constantMask = Uint8Array.of(1);
2398
+ const prepared = literals.map((value) => value.prepare(batch, constantMask, {}));
2399
+ const values = new Set(prepared.map((value) => value.get(0)));
2400
+ const ranges = utf8 ? prepared.map((value) => bytes(value, 0)).filter((range) => range !== null) : [];
2401
+ return {
2402
+ get(row) {
2403
+ if (utf8) {
2404
+ const value = bytes(source, row);
2405
+ if (!value)
2406
+ return null;
2407
+ if (ranges.some((range) => (0, import_utf82.compareUTF8)(value[0], value[1], value[2], range[0], range[1], range[2]) === 0))
2408
+ return true;
2409
+ } else {
2410
+ const value = source.get(row);
2411
+ if (value === null)
2412
+ return null;
2413
+ if (!Number.isNaN(value) && values.has(value))
2414
+ return true;
2415
+ }
2416
+ return values.has(null) ? null : false;
2417
+ }
2418
+ };
2419
+ }
2420
+ };
2421
+ }
2422
+ function bindLike(args, options, insensitive) {
2423
+ if (args.length < 2 || args.length > 3)
2424
+ throw new Error("LIKE requires two or three arguments");
2425
+ const value = bind(args[0], options, new import_apache_arrow6.Utf8());
2426
+ const pattern = bind(args[1], options, new import_apache_arrow6.Utf8());
2427
+ requireType(value, "utf8");
2428
+ requireType(pattern, "utf8");
2429
+ const escape = args[2];
2430
+ if (escape && (escape.type !== "Literal" || typeof escape.value !== "string")) {
2431
+ throw new Error("LIKE ESCAPE requires a literal character");
2432
+ }
2433
+ const compile2 = (text) => compileUTF8Like(text, insensitive, escape == null ? void 0 : escape.value);
2434
+ const literal = args[1].type === "Literal" && typeof args[1].value === "string";
2435
+ const matcher = literal ? compile2(args[1].value) : void 0;
2436
+ return {
2437
+ field: new import_apache_arrow6.Field("like", bool, value.field.nullable || pattern.field.nullable),
2438
+ hasKernel: value.hasKernel || pattern.hasKernel,
2439
+ prepare(batch, active, context) {
2440
+ const source = value.prepare(batch, active, context);
2441
+ const patterns = pattern.prepare(batch, active, context);
2442
+ return {
2443
+ get(row) {
2444
+ const range = bytes(source, row);
2445
+ const text = patterns.get(row);
2446
+ if (!range || text === null)
2447
+ return null;
2448
+ return (matcher || compile2(text))(...range);
2449
+ }
2450
+ };
2451
+ }
2452
+ };
2453
+ }
2454
+ function convertByte(value, normalized) {
2455
+ if (!Number.isFinite(value))
2456
+ throw new ExpressionEvaluationError("conversion", "Byte conversion requires a finite number");
2457
+ if (normalized) {
2458
+ if (value < 0 || value > 1)
2459
+ throw new ExpressionEvaluationError("domain", "PACK_UNORM8 requires values in [0, 1]");
2460
+ return Math.round(value * 255);
2461
+ }
2462
+ const integer = Math.trunc(value);
2463
+ if (integer < 0 || integer > 255)
2464
+ throw new ExpressionEvaluationError("overflow", "UINT8 cast overflow");
2465
+ return integer;
2466
+ }
2467
+ function bindPackUnorm8(arguments_, options) {
2468
+ if (arguments_.length !== 1)
2469
+ throw new Error("PACK_UNORM8 requires one fixed-size numeric array");
2470
+ const argument = bind(arguments_[0], options, void 0, true);
2471
+ const inputType = argument.field.type;
2472
+ if (!import_apache_arrow6.DataType.isFixedSizeList(inputType) || !inputType.listSize || inputType.listSize > 4096)
2473
+ throw new Error("PACK_UNORM8 requires a fixed-size numeric array of 1 to 4096 components");
2474
+ const width = inputType.listSize;
2475
+ const child = inputType.children[0];
2476
+ if (!import_apache_arrow6.DataType.isInt(valueType(child.type)) && !import_apache_arrow6.DataType.isFloat(valueType(child.type)))
2477
+ throw new Error("PACK_UNORM8 requires numeric components");
2478
+ const type = new import_apache_arrow6.FixedSizeList(width, new import_apache_arrow6.Field("value", new import_apache_arrow6.Uint8(), false));
2479
+ const field = new import_apache_arrow6.Field("pack_unorm8", type, argument.field.nullable || child.nullable);
2480
+ return {
2481
+ field,
2482
+ hasKernel: true,
2483
+ prepare(batch, active, context) {
2484
+ var _a2;
2485
+ const input = argument.prepare(batch, active, context).vector;
2486
+ const parent = new ColumnReader(input);
2487
+ const components = new ColumnReader(input.getChildAt(0));
2488
+ const result = nullTupleVector(type, active.length);
2489
+ const data = result.data[0];
2490
+ const bytes2 = data.children[0].values;
2491
+ const rowValues = new Float64Array(width);
2492
+ for (let row = 0; row < active.length; row++) {
2493
+ if (!active[row] || ((_a2 = context.failed) == null ? void 0 : _a2[row]) || !parent.isValid(row))
2494
+ continue;
2495
+ const start = row * width;
2496
+ let valid = true;
2497
+ for (let component = 0; component < width; component++) {
2498
+ const value = components.get(start + component);
2499
+ if (value === null) {
2500
+ valid = false;
2501
+ break;
2502
+ }
2503
+ rowValues[component] = Number(value);
2504
+ }
2505
+ if (!valid)
2506
+ continue;
2507
+ try {
2508
+ for (let component = 0; component < width; component++)
2509
+ bytes2[start + component] = convertByte(rowValues[component], true);
2510
+ } catch (error) {
2511
+ if (!context.failed || !isExpressionEvaluationError(error))
2512
+ throw error;
2513
+ context.failed[row] = 1;
2514
+ bytes2.fill(0, start, start + width);
2515
+ continue;
2516
+ }
2517
+ data.setValid(row, true);
2518
+ }
2519
+ return vectorReader(result);
2520
+ }
2521
+ };
2522
+ }
2523
+ function isNestedType(type) {
2524
+ return import_apache_arrow6.DataType.isStruct(type) || import_apache_arrow6.DataType.isList(type) || import_apache_arrow6.DataType.isFixedSizeList(type);
2525
+ }
2526
+ function nestedValue(value, type) {
2527
+ if (value == null)
2528
+ return null;
2529
+ if (import_apache_arrow6.DataType.isList(type) || import_apache_arrow6.DataType.isFixedSizeList(type))
2530
+ return Array.from(value, (item) => nestedValue(item, type.valueType));
2531
+ if (import_apache_arrow6.DataType.isStruct(type))
2532
+ return Object.fromEntries(type.children.map((field) => [field.name, nestedValue(value[field.name], field.type)]));
2533
+ return value;
2534
+ }
2535
+ function nestedVector(vector, type, active) {
2536
+ if (!active.includes(0))
2537
+ return vector;
2538
+ return (0, import_apache_arrow6.vectorFromArray)(Array.from(active, (valid, row) => valid ? nestedValue(vector.get(row), type) : null), type);
2539
+ }
2540
+ function bindNestedExtract(name, args, options) {
2541
+ if (args.length !== 2)
2542
+ throw new Error(`${name} requires two arguments`);
2543
+ const input = bind(args[0], options, void 0, true);
2544
+ const inputType = input.field.type;
2545
+ const selector = args[1];
2546
+ let child;
2547
+ let index;
2548
+ if (name === "LIST_EXTRACT") {
2549
+ if (!import_apache_arrow6.DataType.isList(inputType) && !import_apache_arrow6.DataType.isFixedSizeList(inputType))
2550
+ throw new Error("LIST_EXTRACT requires an Arrow List or FixedSizeList");
2551
+ child = inputType.children[0];
2552
+ index = bind(selector, options);
2553
+ if (!import_apache_arrow6.DataType.isInt(index.field.type) && !import_apache_arrow6.DataType.isFloat(index.field.type) && !import_apache_arrow6.DataType.isNull(index.field.type))
2554
+ throw new Error("LIST_EXTRACT requires an integer index");
2555
+ } else {
2556
+ if (!import_apache_arrow6.DataType.isStruct(inputType))
2557
+ throw new Error("STRUCT_EXTRACT requires an Arrow Struct");
2558
+ if (selector.type !== "Literal" || typeof selector.value !== "string")
2559
+ throw new Error("STRUCT_EXTRACT requires a literal field name");
2560
+ const field2 = inputType.children.find((candidate) => candidate.name === selector.value);
2561
+ if (!field2)
2562
+ throw new Error(`Unknown Arrow struct field: ${selector.value}`);
2563
+ child = field2;
2564
+ }
2565
+ const field = new import_apache_arrow6.Field(child.name, valueType(child.type), true, child.metadata);
2566
+ return {
2567
+ field,
2568
+ hasKernel: true,
2569
+ prepare(batch, active, context) {
2570
+ const inputValues = input.prepare(batch, active, context).vector;
2571
+ const positions = index == null ? void 0 : index.prepare(batch, active, context);
2572
+ const childValues = index ? void 0 : inputValues.getChild(child.name);
2573
+ const values = Array.from(active, (valid, row) => {
2574
+ if (!valid || !inputValues.isValid(row))
2575
+ return null;
2576
+ if (!positions)
2577
+ return nestedValue(childValues.get(row), field.type);
2578
+ const position = positions.get(row);
2579
+ if (position === null)
2580
+ return null;
2581
+ const offset = Number(position);
2582
+ if (!Number.isSafeInteger(offset))
2583
+ return null;
2584
+ const list = inputValues.get(row);
2585
+ const element = offset < 0 ? list.length + offset : offset - 1;
2586
+ return element >= 0 && element < list.length ? nestedValue(list.get(element), field.type) : null;
2587
+ });
2588
+ return vectorReader((0, import_apache_arrow6.vectorFromArray)(values, field.type));
2589
+ }
2590
+ };
2591
+ }
2592
+ function bindCall(ast, options, expected) {
2593
+ var _a2, _b;
2594
+ if (ast.callee.type !== "Identifier")
2595
+ throw new Error("Only registered named function calls are supported");
2596
+ let name = ast.callee.name;
2597
+ const recovery = recoveryName(ast);
2598
+ if (recovery)
2599
+ return bindRecovery(recovery, ast.arguments, options, expected);
2600
+ if (ast.sqlFunction) {
2601
+ const matches = [
2602
+ ...options.functionLookup.keys(),
2603
+ "array",
2604
+ "array_float16",
2605
+ "array_float32",
2606
+ "array_float64",
2607
+ "array_uint8",
2608
+ "PACK_UNORM8",
2609
+ "LIST_EXTRACT",
2610
+ "STRUCT_EXTRACT",
2611
+ "cast",
2612
+ "like",
2613
+ "ilike",
2614
+ "concat",
2615
+ "concatStrict",
2616
+ "upper",
2617
+ "lower",
2618
+ "capitalize",
2619
+ "isNull",
2620
+ "isNotNull",
2621
+ "parseNumber",
2622
+ "parseBigInt",
2623
+ "parseBoolean",
2624
+ "toFloat64",
2625
+ "toInt32",
2626
+ "toInt64"
2627
+ ].filter((key) => key.toUpperCase() === name.toUpperCase());
2628
+ if (matches.length > 1)
2629
+ throw new Error(`Ambiguous SQL function: ${name}`);
2630
+ name = matches[0] ?? name;
2631
+ }
2632
+ if (name === "LIST_EXTRACT" || name === "STRUCT_EXTRACT")
2633
+ return bindNestedExtract(name, ast.arguments, options);
2634
+ if (name === "PACK_UNORM8")
2635
+ return bindPackUnorm8(ast.arguments, options);
2636
+ if (["array", "array_float16", "array_float32", "array_float64", "array_uint8"].includes(name)) {
2637
+ if (!ast.arguments.length || ast.arguments.length > 4096)
2638
+ throw new Error("ARRAY requires 1 to 4096 numeric expressions");
2639
+ const arguments_2 = ast.arguments.map((value) => bind(value, options));
2640
+ if (arguments_2.some((value) => !import_apache_arrow6.DataType.isFloat(valueType(value.field.type)) && !import_apache_arrow6.DataType.isInt(valueType(value.field.type))))
2641
+ throw new Error("ARRAY requires numeric expressions");
2642
+ const component = name === "array_uint8" ? new import_apache_arrow6.Uint8() : name === "array_float16" ? new import_apache_arrow6.Float16() : name === "array_float32" ? new import_apache_arrow6.Float32() : name === "array_float64" || arguments_2.every((value) => import_apache_arrow6.DataType.isInt(valueType(value.field.type))) || arguments_2.some((value) => typeKey(value.field.type) === "f2") ? new import_apache_arrow6.Float64() : arguments_2.some((value) => typeKey(value.field.type) === "f1") ? new import_apache_arrow6.Float32() : new import_apache_arrow6.Float16();
2643
+ const type = new import_apache_arrow6.FixedSizeList(arguments_2.length, new import_apache_arrow6.Field("value", component, false));
2644
+ const field2 = new import_apache_arrow6.Field("array", type, arguments_2.some((value) => value.field.nullable));
2645
+ return {
2646
+ field: field2,
2647
+ hasKernel: true,
2648
+ prepare(batch, active, context) {
2649
+ const values = arguments_2.map((value) => prepareInput(value, batch, active, context, arguments_2.some((argument) => argument.hasKernel)));
2650
+ const vector = nullTupleVector(type, active.length), data = vector.data[0], output2 = import_apache_arrow6.DataType.isFloat(component) && component.precision === import_apache_arrow6.Precision.HALF ? float16Values(data.children[0].values) : data.children[0].values;
2651
+ const rowValues = new Array(values.length);
2652
+ for (let row = 0; row < active.length; row++) {
2653
+ if (!active[row])
2654
+ continue;
2655
+ for (let column = 0; column < values.length; column++)
2656
+ rowValues[column] = values[column].get(row);
2657
+ if (rowValues.some((value) => value === null))
2658
+ continue;
2659
+ try {
2660
+ for (let column = 0; column < values.length; column++) {
2661
+ const index = row * values.length + column;
2662
+ const value = Number(rowValues[column]);
2663
+ output2[index] = name === "array_uint8" ? convertByte(value, false) : value;
2664
+ if (Number.isFinite(value) && !Number.isFinite(output2[index]))
2665
+ throw new ExpressionEvaluationError("overflow", "ARRAY cast overflow");
2666
+ }
2667
+ } catch (error) {
2668
+ if (!context.failed || !isExpressionEvaluationError(error))
2669
+ throw error;
2670
+ context.failed[row] = 1;
2671
+ output2.fill(0, row * values.length, (row + 1) * values.length);
2672
+ continue;
2673
+ }
2674
+ data.setValid(row, true);
2675
+ }
2676
+ return vectorReader(vector);
2677
+ }
2678
+ };
2679
+ }
2680
+ if (name === "like" || name === "ilike")
2681
+ return bindLike(ast.arguments, options, name === "ilike");
2682
+ if (name === "upper" || name === "lower" || name === "capitalize") {
2683
+ if (ast.arguments.length !== 1)
2684
+ throw new Error("Case conversion requires one argument");
2685
+ const arg = bind(ast.arguments[0], options, new import_apache_arrow6.Utf8());
2686
+ requireType(arg, "utf8");
2687
+ return {
2688
+ field: new import_apache_arrow6.Field(name, new import_apache_arrow6.Utf8(), arg.field.nullable),
2689
+ hasKernel: arg.hasKernel,
2690
+ prepare(batch, active, context) {
2691
+ const input = arg.prepare(batch, active, context);
2692
+ return {
2693
+ get(row) {
2694
+ const value = input.get(row);
2695
+ if (!value)
2696
+ return value;
2697
+ if (name === "upper")
2698
+ return value.toUpperCase();
2699
+ if (name === "lower")
2700
+ return value.toLowerCase();
2701
+ const first = String.fromCodePoint(value.codePointAt(0));
2702
+ return first.toUpperCase() + value.slice(first.length);
2703
+ }
2704
+ };
2705
+ }
2706
+ };
2707
+ }
2708
+ if (name === "concat" || name === "concatStrict") {
2709
+ if (!ast.arguments.length)
2710
+ throw new Error("CONCAT requires at least one argument");
2711
+ const args = ast.arguments.map((arg) => bind(arg, options, new import_apache_arrow6.Utf8()));
2712
+ for (const arg of args)
2713
+ requireType(arg, "utf8");
2714
+ const strict = name === "concatStrict";
2715
+ return {
2716
+ field: new import_apache_arrow6.Field("concat", new import_apache_arrow6.Utf8(), strict && args.some((arg) => arg.field.nullable)),
2717
+ hasKernel: args.some((arg) => arg.hasKernel),
2718
+ prepare(batch, active, context) {
2719
+ const inputs = args.map((arg) => arg.prepare(batch, active, context));
2720
+ return {
2721
+ get(row) {
2722
+ let result2 = "";
2723
+ for (const input of inputs) {
2724
+ const value = input.get(row);
2725
+ if (value === null && strict)
2726
+ return null;
2727
+ if (value !== null)
2728
+ result2 += value;
2729
+ }
2730
+ return result2;
2731
+ }
2732
+ };
2733
+ }
2734
+ };
2735
+ }
2736
+ if (name === "in")
2737
+ return bindMembership(ast.arguments, options);
2738
+ if (name === "cast") {
2739
+ if (ast.arguments.length !== 2 || ((_a2 = ast.arguments[1]) == null ? void 0 : _a2.type) !== "Literal")
2740
+ throw new Error("cast requires a value and a literal scalar target");
2741
+ const argument = bind(ast.arguments[0], options);
2742
+ const target = ast.arguments[1].value;
2743
+ if (target === "geometry")
2744
+ return bindGeometryCast(argument);
2745
+ const cast = bindCast(argument.field.type, target);
2746
+ return {
2747
+ field: new import_apache_arrow6.Field("cast", cast.type, argument.field.nullable),
2748
+ hasKernel: argument.hasKernel,
2749
+ prepare(batch, active, context) {
2750
+ const child = argument.prepare(batch, active, context);
2751
+ return {
2752
+ get: (row) => cast.textInput && !import_apache_arrow6.DataType.isUtf8(valueType(cast.type)) ? cast.evaluate(null, bytes(child, row)) : cast.evaluate(child.get(row))
2753
+ };
2754
+ }
2755
+ };
2756
+ }
2757
+ const conversion = ["toFloat64", "toInt32", "toInt64"].includes(name);
2758
+ const nullTest = name === "isNull" || name === "isNotNull";
2759
+ if (conversion || nullTest || ["parseNumber", "parseBigInt", "parseBoolean"].includes(name)) {
2760
+ if (ast.arguments.length !== 1)
2761
+ throw new Error(`${name} requires one argument`);
2762
+ const argument = bind(ast.arguments[0], options);
2763
+ if (conversion)
2764
+ requireNumeric(argument);
2765
+ else if (!nullTest)
2766
+ requireType(argument, "utf8");
2767
+ const type = name === "parseNumber" || name === "toFloat64" ? new import_apache_arrow6.Float64() : name === "toInt32" ? new import_apache_arrow6.Int32() : name === "parseBigInt" || name === "toInt64" ? new import_apache_arrow6.Int64() : bool;
2768
+ const validate2 = createValueValidator(type);
2769
+ const round2 = roundToType(type);
2770
+ const field2 = new import_apache_arrow6.Field(name, type, conversion ? argument.field.nullable : !nullTest);
2771
+ return {
2772
+ field: field2,
2773
+ hasKernel: argument.hasKernel,
2774
+ prepare(batch, active, context) {
2775
+ const child = argument.prepare(batch, active, context);
2776
+ return {
2777
+ get: (row) => {
2778
+ if (nullTest) {
2779
+ const missing = child.isNull ? child.isNull(row) : child.get(row) === null;
2780
+ return name === "isNull" ? missing : !missing;
2781
+ }
2782
+ if (conversion) {
2783
+ const value = child.get(row);
2784
+ if (value === null)
2785
+ return null;
2786
+ if (name === "toInt64" && typeof value === "number" && !Number.isInteger(value))
2787
+ throw new ExpressionEvaluationError("conversion", "Int64 conversion requires a finite integer");
2788
+ const result3 = name === "toInt64" ? BigInt(value) : Number(value);
2789
+ validate2(result3);
2790
+ return result3;
2791
+ }
2792
+ const range = bytes(child, row);
2793
+ if (!range)
2794
+ return null;
2795
+ const [buffer, start, end] = range;
2796
+ const result2 = (name === "parseNumber" ? (0, import_utf82.parseUTF8Number)(buffer, start, end) : name === "parseBigInt" ? (0, import_utf82.parseUTF8BigInt)(buffer, start, end) : (0, import_utf82.parseUTF8Boolean)(buffer, start, end)) ?? null;
2797
+ validate2(result2);
2798
+ return round2(result2);
2799
+ }
2800
+ };
2801
+ }
2802
+ };
2803
+ }
2804
+ const group = options.functionLookup.get(name);
2805
+ if (!group)
2806
+ throw new Error(`Unknown Arrow function: ${name}`);
2807
+ const inferred = ast.arguments.map((argument) => needsArgumentContext(argument) ? void 0 : bind(argument, options, void 0, true));
2808
+ const candidates = [];
2809
+ const allLiteralArguments = ast.arguments.every(isContextualLiteral);
2810
+ let contextualError;
2811
+ for (const prototype of group.prototypes) {
2812
+ if (ast.arguments.length !== prototype.arguments.length)
2813
+ continue;
2814
+ let cost = 0;
2815
+ const arguments_2 = [];
2816
+ let compatible = true;
2817
+ for (let index = 0; index < ast.arguments.length; index++) {
2818
+ const argument = ast.arguments[index], field2 = prototype.arguments[index], source = inferred[index];
2819
+ let bound;
2820
+ if (isContextualLiteral(argument) || !source) {
2821
+ try {
2822
+ bound = bind(argument, options, field2.type, !prototype.evaluateScalar);
2823
+ } catch (error) {
2824
+ contextualError = error;
2825
+ compatible = false;
2826
+ break;
2827
+ }
2828
+ if (source && allLiteralArguments && physicalKey(valueType(source.field.type)) !== physicalKey(field2.type))
2829
+ cost += 4;
2830
+ } else {
2831
+ bound = source;
2832
+ }
2833
+ const sourceType = valueType(bound.field.type);
2834
+ if (import_apache_arrow6.DataType.isDictionary(bound.field.type) && !import_apache_arrow6.DataType.isDictionary(field2.type))
2835
+ cost += 1;
2836
+ if (physicalKey(import_apache_arrow6.DataType.isDictionary(field2.type) ? bound.field.type : sourceType) !== physicalKey(field2.type)) {
2837
+ if (import_apache_arrow6.DataType.isFloat(sourceType) && import_apache_arrow6.DataType.isFloat(field2.type) && sourceType.precision < field2.type.precision) {
2838
+ cost += field2.type.precision - sourceType.precision;
2839
+ const child = bound, round2 = roundToType(field2.type);
2840
+ bound = {
2841
+ field: new import_apache_arrow6.Field(child.field.name, field2.type, child.field.nullable, child.field.metadata),
2842
+ hasKernel: child.hasKernel,
2843
+ prepare(batch, active, context) {
2844
+ const prepared = child.prepare(batch, active, context);
2845
+ return { get: (row) => round2(prepared.get(row)) };
2846
+ }
2847
+ };
2848
+ } else {
2849
+ compatible = false;
2850
+ break;
2851
+ }
2852
+ }
2853
+ if ([...field2.metadata].some(([key, value]) => bound.field.metadata.get(key) !== value) || prototype.nullHandling === "call" && bound.field.nullable && !field2.nullable) {
2854
+ compatible = false;
2855
+ break;
2856
+ }
2857
+ arguments_2.push(bound);
2858
+ }
2859
+ if (compatible)
2860
+ candidates.push({ prototype, arguments: arguments_2, cost });
2861
+ }
2862
+ const untypedNumeric = (value) => value.type === "Literal" && (value.value === null || typeof value.value === "number") || isSignedLiteral(value) || Boolean(recoveryName(value) && value.arguments.every(untypedNumeric)) || value.type === "ConditionalExpression" && untypedNumeric(value.consequent) && untypedNumeric(value.alternate);
2863
+ const allFloat64 = (prototype) => prototype.arguments.every((field2) => import_apache_arrow6.DataType.isFloat(field2.type) && field2.type.precision === import_apache_arrow6.Precision.DOUBLE);
2864
+ if (ast.arguments.every(untypedNumeric) && candidates.every((candidate) => candidate.prototype.arguments.every((field2) => import_apache_arrow6.DataType.isInt(field2.type) || import_apache_arrow6.DataType.isFloat(field2.type))) && candidates.some((candidate) => allFloat64(candidate.prototype))) {
2865
+ for (const candidate of candidates)
2866
+ if (!allFloat64(candidate.prototype))
2867
+ candidate.cost++;
2868
+ }
2869
+ candidates.sort((a, b) => a.cost - b.cost);
2870
+ if (!candidates.length && group.prototypes.length === 1 && contextualError)
2871
+ throw contextualError;
2872
+ if (!candidates.length)
2873
+ throw new Error(`Argument type mismatch or wrong argument count for ${name}`);
2874
+ if (((_b = candidates[1]) == null ? void 0 : _b.cost) === candidates[0].cost)
2875
+ throw new Error(`Ambiguous Arrow function call: ${name}`);
2876
+ const declaration = candidates[0].prototype;
2877
+ const arguments_ = candidates[0].arguments;
2878
+ const evaluateVector = declaration.evaluateScalar ? void 0 : declaration.evaluate;
2879
+ const result = declaration.result;
2880
+ const tuple = isTupleType(result.type);
2881
+ if (tuple && declaration.evaluateScalar)
2882
+ throw new Error("Fixed-size list results require a vector-only function");
2883
+ if (declaration.evaluateScalar)
2884
+ for (const argument of arguments_)
2885
+ typeKey(argument.field.type);
2886
+ if (!tuple)
2887
+ typeKey(result.type);
2888
+ const validate = tuple ? void 0 : createValueValidator(result.type);
2889
+ const round = tuple ? void 0 : roundToType(result.type);
2890
+ const field = new import_apache_arrow6.Field(result.name, valueType(result.type), result.nullable || declaration.nullHandling !== "call" && arguments_.some((argument) => argument.field.nullable), result.metadata);
2891
+ return {
2892
+ field,
2893
+ hasKernel: Boolean(evaluateVector) || arguments_.some((argument) => argument.hasKernel),
2894
+ prepare(batch, active, context) {
2895
+ const children = arguments_.map((argument) => prepareInput(argument, batch, active, context, Boolean(evaluateVector) || arguments_.some((value) => value.hasKernel)));
2896
+ let kernel;
2897
+ let mask = active;
2898
+ if (evaluateVector && active.some(Boolean)) {
2899
+ const vectors = children.map((child, index) => child.vector ?? output(arguments_[index].field, context.failed ? active.map((value, row) => value && !context.failed[row] ? 1 : 0) : active, child.get));
2900
+ const readers = vectors.map((vector) => new ColumnReader(vector));
2901
+ mask = active.map((value, row) => {
2902
+ var _a3;
2903
+ return value && !((_a3 = context.failed) == null ? void 0 : _a3[row]) && (declaration.nullHandling === "call" || readers.every((reader) => reader.isValid(row))) ? 1 : 0;
2904
+ });
2905
+ if (mask.some(Boolean)) {
2906
+ const vector = evaluateVector(vectors, {
2907
+ activeRows: mask,
2908
+ length: active.length,
2909
+ reportError(row, error) {
2910
+ if (!Number.isInteger(row) || row < 0 || row >= active.length || !mask[row])
2911
+ throw new Error("Kernel reported an inactive or invalid row");
2912
+ if (!context.failed || !isExpressionEvaluationError(error))
2913
+ throw error;
2914
+ context.failed[row] = 1;
2915
+ mask[row] = 0;
2916
+ }
2917
+ });
2918
+ if (vector.length !== active.length || (tuple ? physicalKey(vector.type) !== physicalKey(result.type) : typeKey(vector.type) !== typeKey(result.type)))
2919
+ throw new Error(`Invalid kernel result for ${name}`);
2920
+ if (tuple) {
2921
+ validateTupleVector(vector, result, mask);
2922
+ return vectorReader(maskTupleVector(vector, mask));
2923
+ }
2924
+ kernel = sourceReader(vector);
2925
+ }
2926
+ }
2927
+ if (isTupleType(result.type))
2928
+ return vectorReader(nullTupleVector(result.type, active.length));
2929
+ return {
2930
+ get: (row) => {
2931
+ var _a3;
2932
+ let value;
2933
+ if (evaluateVector) {
2934
+ if (!mask[row] || !kernel)
2935
+ return null;
2936
+ value = kernel.get(row);
2937
+ } else {
2938
+ const args = children.map((child) => child.get(row));
2939
+ if ((_a3 = context.failed) == null ? void 0 : _a3[row])
2940
+ return null;
2941
+ if (declaration.nullHandling !== "call" && args.some((value2) => value2 === null))
2942
+ return null;
2943
+ value = declaration.evaluateScalar(...args);
2944
+ }
2945
+ if (value === null && !result.nullable)
2946
+ throw new Error(`Function ${name} returned null for a non-nullable result`);
2947
+ validate(value);
2948
+ return round(value);
2949
+ }
2950
+ };
2951
+ }
2952
+ };
2953
+ }
2954
+ function roundToType(type) {
2955
+ if (typeKey(type) === "f0") {
2956
+ const round = roundFloat16();
2957
+ return (value) => value === null ? null : round(value);
2958
+ }
2959
+ return typeKey(type) === "f1" ? (value) => value === null ? null : Math.fround(value) : (value) => value;
2960
+ }
2961
+ function isSignedLiteral(ast) {
2962
+ return ast.type === "UnaryExpression" && (ast.operator === "+" || ast.operator === "-") && ast.argument.type === "Literal" && typeof ast.argument.value === "number";
2963
+ }
2964
+ function recoveryName(ast) {
2965
+ if (ast.type !== "CallExpression" || ast.callee.type !== "Identifier")
2966
+ return void 0;
2967
+ const name = ast.sqlFunction ? ast.callee.name.toUpperCase() : ast.callee.name;
2968
+ return name === "TRY" || name === "COALESCE" ? name : void 0;
2969
+ }
2970
+ function containsContextualArray(ast) {
2971
+ return ast.type === "ArrayExpression" || ast.type === "ConditionalExpression" && (containsContextualArray(ast.consequent) || containsContextualArray(ast.alternate)) || Boolean(recoveryName(ast) && ast.arguments.some(containsContextualArray));
2972
+ }
2973
+ function isContextualLiteral(ast) {
2974
+ return ast.type === "Literal" || ast.type === "ArrayExpression" || isSignedLiteral(ast) || Boolean(recoveryName(ast) && ast.arguments.every(isContextualLiteral)) || ast.type === "ConditionalExpression" && isContextualLiteral(ast.consequent) && isContextualLiteral(ast.alternate);
2975
+ }
2976
+ function needsArgumentContext(ast) {
2977
+ return ast.type === "ArrayExpression" || ast.type === "Literal" && ast.value === null || Boolean(recoveryName(ast) && ast.arguments.some(containsContextualArray)) || ast.type === "ConditionalExpression" && (needsArgumentContext(ast.consequent) || needsArgumentContext(ast.alternate));
2978
+ }
2979
+
2980
+ // dist/scales/scale-types.js
2981
+ function assertFinite(value, description) {
2982
+ if (!Number.isFinite(value))
2983
+ throw new Error(`${description} must be finite`);
2984
+ }
2985
+ function checkColor(color, label) {
2986
+ if (!Array.isArray(color) || color.length !== 4) {
2987
+ throw new Error(`${label} must contain four channels`);
2988
+ }
2989
+ color.forEach((channel, index) => assertFinite(channel, `${label}[${index}]`));
2990
+ }
2991
+ function validateScaleSpec(spec) {
2992
+ var _a2;
2993
+ if (!spec || typeof spec !== "object")
2994
+ throw new Error("Scale specification is required");
2995
+ const kinds = [
2996
+ "linear",
2997
+ "sqrt",
2998
+ "log",
2999
+ "symlog",
3000
+ "sequential",
3001
+ "diverging",
3002
+ "ordinal",
3003
+ "quantize",
3004
+ "quantile",
3005
+ "threshold",
3006
+ "piecewise"
3007
+ ];
3008
+ if (!kinds.includes(spec.type))
3009
+ throw new Error(`Unsupported scale type: ${spec.type}`);
3010
+ const minimumStops = spec.type === "ordinal" ? 1 : 2;
3011
+ const domain = spec.domain;
3012
+ if (!domain || typeof domain !== "object")
3013
+ throw new Error("Scale domain is required");
3014
+ switch (domain.type) {
3015
+ case "fixed":
3016
+ if (!Array.isArray(domain.values) || domain.values.length < minimumStops || domain.values.some((value) => typeof value !== "string" && (typeof value !== "number" || !Number.isFinite(value))))
3017
+ throw new Error(`Fixed scale domain requires at least ${minimumStops} finite or string values`);
3018
+ break;
3019
+ case "extent":
3020
+ case "categories":
3021
+ if (typeof domain.column !== "string" || !domain.column) {
3022
+ throw new Error("Scale domain requires a column");
3023
+ }
3024
+ break;
3025
+ case "symmetric":
3026
+ if (!domain.column)
3027
+ throw new Error("Symmetric domain requires a column");
3028
+ assertFinite(domain.pivot, "Scale pivot");
3029
+ break;
3030
+ case "percentile":
3031
+ if (!domain.column || !Number.isFinite(domain.lower) || !Number.isFinite(domain.upper) || domain.lower < 0 || domain.upper > 1 || domain.lower >= domain.upper) {
3032
+ throw new Error("Percentile domain requires 0 <= lower < upper <= 1");
3033
+ }
3034
+ break;
3035
+ default:
3036
+ throw new Error("Unsupported scale domain");
3037
+ }
3038
+ if (!spec.range)
3039
+ throw new Error("Scale range is required");
3040
+ switch (spec.range.type) {
3041
+ case "numeric":
3042
+ if (spec.range.values.length < minimumStops)
3043
+ throw new Error(`Numeric range requires at least ${minimumStops} values`);
3044
+ spec.range.values.forEach((value) => assertFinite(value, "Numeric range"));
3045
+ break;
3046
+ case "colors":
3047
+ if (spec.range.values.length < minimumStops)
3048
+ throw new Error(`Color range requires at least ${minimumStops} colors`);
3049
+ spec.range.values.forEach((value, index) => checkColor(value, `Color stop ${index}`));
3050
+ break;
3051
+ case "palette":
3052
+ if (!spec.range.name || spec.range.count !== void 0 && (!Number.isSafeInteger(spec.range.count) || spec.range.count < 2)) {
3053
+ throw new Error("Palette requires a name and optional positive count >= 2");
3054
+ }
3055
+ break;
3056
+ default:
3057
+ throw new Error("Unsupported scale range");
3058
+ }
3059
+ if (spec.pivot !== void 0)
3060
+ assertFinite(spec.pivot, "Scale pivot");
3061
+ if (((_a2 = spec.encoding) == null ? void 0 : _a2.referenceWhiteNits) !== void 0 && (!Number.isFinite(spec.encoding.referenceWhiteNits) || spec.encoding.referenceWhiteNits <= 0)) {
3062
+ throw new Error("referenceWhiteNits must be a positive finite number");
3063
+ }
3064
+ for (const key of ["nullColor", "underColor", "overColor"]) {
3065
+ if (spec[key])
3066
+ checkColor(spec[key], key);
3067
+ }
3068
+ return spec;
3069
+ }
3070
+ function createResolvedScale(descriptor, sample) {
3071
+ validateScaleSpec({
3072
+ ...descriptor,
3073
+ domain: { type: "fixed", values: descriptor.domain }
3074
+ });
3075
+ if (descriptor.thresholds) {
3076
+ if (descriptor.thresholds.some((value, i) => !Number.isFinite(value) || i > 0 && value <= descriptor.thresholds[i - 1])) {
3077
+ throw new Error("Thresholds must be finite and strictly ordered");
3078
+ }
3079
+ }
3080
+ return Object.freeze({ descriptor, sample });
3081
+ }
3082
+
3083
+ // dist/scales/palettes.js
3084
+ var rgba = (hex) => {
3085
+ const hexValue = hex.slice(1);
3086
+ return [
3087
+ parseInt(hexValue.slice(0, 2), 16) / 255,
3088
+ parseInt(hexValue.slice(2, 4), 16) / 255,
3089
+ parseInt(hexValue.slice(4, 6), 16) / 255,
3090
+ 1
3091
+ ];
3092
+ };
3093
+ var PALETTES = {
3094
+ viridis: ["#440154", "#414487", "#2a788e", "#22a884", "#7ad151", "#fde725"],
3095
+ plasma: ["#0d0887", "#7e03a8", "#cc4778", "#f89540", "#f0f921"],
3096
+ inferno: ["#000004", "#420a68", "#932667", "#dd513a", "#fca50a", "#fcffa4"],
3097
+ cividis: ["#00204c", "#414d6b", "#7a7b78", "#bcae6c", "#fee838"],
3098
+ blues: ["#eff3ff", "#bdd7e7", "#6baed6", "#3182bd", "#08519c"],
3099
+ rdbu: [
3100
+ "#b2182b",
3101
+ "#d6604d",
3102
+ "#f4a582",
3103
+ "#fddbc7",
3104
+ "#f7f7f7",
3105
+ "#d1e5f0",
3106
+ "#92c5de",
3107
+ "#4393c3",
3108
+ "#2166ac"
3109
+ ],
3110
+ ylorrd: ["#ffffb2", "#fecc5c", "#fd8d3c", "#f03b20", "#bd0026"],
3111
+ tableau10: [
3112
+ "#4e79a7",
3113
+ "#f28e2b",
3114
+ "#e15759",
3115
+ "#76b7b2",
3116
+ "#59a14f",
3117
+ "#edc948",
3118
+ "#b07aa1",
3119
+ "#ff9da7",
3120
+ "#9c755f",
3121
+ "#bab0ab"
3122
+ ]
3123
+ };
3124
+ function interpolate(a, b, t) {
3125
+ return [
3126
+ a[0] + (b[0] - a[0]) * t,
3127
+ a[1] + (b[1] - a[1]) * t,
3128
+ a[2] + (b[2] - a[2]) * t,
3129
+ a[3] + (b[3] - a[3]) * t
3130
+ ];
3131
+ }
3132
+ function resolvePalette(range, count) {
3133
+ if (range.type === "numeric")
3134
+ throw new Error("A numeric range is not a color palette");
3135
+ if (range.type === "colors")
3136
+ return range.values;
3137
+ const key = range.name.toLowerCase();
3138
+ const colors = Object.prototype.hasOwnProperty.call(PALETTES, key) ? PALETTES[key] : void 0;
3139
+ if (!colors)
3140
+ throw new Error(`Unknown color palette: ${range.name}`);
3141
+ const target = count ?? range.count;
3142
+ if (target === void 0)
3143
+ return colors.map(rgba);
3144
+ if (!Number.isSafeInteger(target) || target < 2 || target > 256) {
3145
+ throw new Error("Palette count must be between 2 and 256");
3146
+ }
3147
+ if (target === colors.length)
3148
+ return colors.map(rgba);
3149
+ const decoded = colors.map(rgba);
3150
+ return Array.from({ length: target }, (_, i) => {
3151
+ const position = i * (decoded.length - 1) / (target - 1);
3152
+ const index = Math.min(Math.floor(position), decoded.length - 2);
3153
+ return interpolate(decoded[index], decoded[index + 1], position - index);
3154
+ });
3155
+ }
3156
+
3157
+ // dist/scales/hdr-colors.js
3158
+ var TO_XYZ = {
3159
+ srgb: [
3160
+ 0.4124564,
3161
+ 0.3575761,
3162
+ 0.1804375,
3163
+ 0.2126729,
3164
+ 0.7151522,
3165
+ 0.072175,
3166
+ 0.0193339,
3167
+ 0.119192,
3168
+ 0.9503041
3169
+ ],
3170
+ "display-p3": [
3171
+ 0.48657095,
3172
+ 0.26566769,
3173
+ 0.19821729,
3174
+ 0.22897456,
3175
+ 0.69173852,
3176
+ 0.07928691,
3177
+ 0,
3178
+ 0.04511338,
3179
+ 1.04394437
3180
+ ],
3181
+ rec2020: [
3182
+ 0.63695805,
3183
+ 0.1446169,
3184
+ 0.16888098,
3185
+ 0.26270021,
3186
+ 0.67799807,
3187
+ 0.05930172,
3188
+ 0,
3189
+ 0.02807269,
3190
+ 1.06098506
3191
+ ]
3192
+ };
3193
+ var FROM_XYZ = {
3194
+ srgb: [
3195
+ 3.2404542,
3196
+ -1.5371385,
3197
+ -0.4985314,
3198
+ -0.969266,
3199
+ 1.8760108,
3200
+ 0.041556,
3201
+ 0.0556434,
3202
+ -0.2040259,
3203
+ 1.0572252
3204
+ ],
3205
+ "display-p3": [
3206
+ 2.49349691,
3207
+ -0.93138362,
3208
+ -0.40271078,
3209
+ -0.82948897,
3210
+ 1.76266406,
3211
+ 0.02362469,
3212
+ 0.03584583,
3213
+ -0.07617239,
3214
+ 0.95688452
3215
+ ],
3216
+ rec2020: [
3217
+ 1.71665119,
3218
+ -0.35567078,
3219
+ -0.25336628,
3220
+ -0.66668435,
3221
+ 1.61648124,
3222
+ 0.01576855,
3223
+ 0.01763986,
3224
+ -0.04277061,
3225
+ 0.94210312
3226
+ ]
3227
+ };
3228
+ function transform(m, [r, g, b]) {
3229
+ return [
3230
+ m[0] * r + m[1] * g + m[2] * b,
3231
+ m[3] * r + m[4] * g + m[5] * b,
3232
+ m[6] * r + m[7] * g + m[8] * b
3233
+ ];
3234
+ }
3235
+ function decodeSRGB(v) {
3236
+ const x = Math.abs(v);
3237
+ return Math.sign(v) * (x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4);
3238
+ }
3239
+ function encodeSRGB(v) {
3240
+ const x = Math.abs(v);
3241
+ return Math.sign(v) * (x <= 31308e-7 ? 12.92 * x : 1.055 * x ** (1 / 2.4) - 0.055);
3242
+ }
3243
+ function decode(v, transfer) {
3244
+ if (transfer === "linear")
3245
+ return v;
3246
+ if (transfer === "srgb")
3247
+ return decodeSRGB(v);
3248
+ throw new Error(`Transfer ${transfer} requires an explicit HDR display-referred conversion`);
3249
+ }
3250
+ function encode(v, transfer) {
3251
+ if (transfer === "linear")
3252
+ return v;
3253
+ if (transfer === "srgb")
3254
+ return encodeSRGB(v);
3255
+ throw new Error(`Transfer ${transfer} requires an explicit HDR display-referred conversion`);
3256
+ }
3257
+ function convertScaleColor(color, from, to) {
3258
+ if (color.some((channel) => !Number.isFinite(channel))) {
3259
+ throw new Error("Color channels must be finite");
3260
+ }
3261
+ if (from.transfer === "pq" || from.transfer === "hlg" || to.transfer === "pq" || to.transfer === "hlg") {
3262
+ throw new Error("PQ/HLG conversions require explicit luminance and display assumptions");
3263
+ }
3264
+ const linear = color.slice(0, 3).map((v) => decode(v, from.transfer));
3265
+ const converted = from.primaries === to.primaries ? linear : transform(FROM_XYZ[to.primaries], transform(TO_XYZ[from.primaries], linear));
3266
+ return [
3267
+ encode(converted[0], to.transfer),
3268
+ encode(converted[1], to.transfer),
3269
+ encode(converted[2], to.transfer),
3270
+ color[3]
3271
+ ];
3272
+ }
3273
+
3274
+ // dist/scales/compile-scale.js
3275
+ var SRGB = { primaries: "srgb", transfer: "srgb", format: "rgba32float" };
3276
+ var clamp01 = (value) => Math.min(1, Math.max(0, value));
3277
+ function toOklab(color) {
3278
+ const [r, g, b] = color.slice(0, 3).map(decodeSRGB);
3279
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
3280
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
3281
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
3282
+ return [
3283
+ 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
3284
+ 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
3285
+ 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s
3286
+ ];
3287
+ }
3288
+ function fromOklab([L, a, b]) {
3289
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
3290
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
3291
+ const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
3292
+ return [
3293
+ encodeSRGB(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
3294
+ encodeSRGB(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
3295
+ encodeSRGB(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s)
3296
+ ];
3297
+ }
3298
+ function interpolateColor(a, b, t, space = "srgb") {
3299
+ if (space === "jzazbz") {
3300
+ throw new Error("Jzazbz interpolation is not implemented yet");
3301
+ }
3302
+ const mix = (x, y) => x + (y - x) * t;
3303
+ const alpha = mix(a[3], b[3]);
3304
+ if (space === "oklab") {
3305
+ const lhs = toOklab(a), rhs = toOklab(b);
3306
+ const rgb = fromOklab(lhs.map((v, i) => mix(v, rhs[i])));
3307
+ return [rgb[0], rgb[1], rgb[2], alpha];
3308
+ }
3309
+ if (space === "linear-srgb") {
3310
+ return [
3311
+ encodeSRGB(mix(decodeSRGB(a[0]), decodeSRGB(b[0]))),
3312
+ encodeSRGB(mix(decodeSRGB(a[1]), decodeSRGB(b[1]))),
3313
+ encodeSRGB(mix(decodeSRGB(a[2]), decodeSRGB(b[2]))),
3314
+ alpha
3315
+ ];
3316
+ }
3317
+ return [mix(a[0], b[0]), mix(a[1], b[1]), mix(a[2], b[2]), alpha];
3318
+ }
3319
+ function normalize(value, a, b, type) {
3320
+ if (a === b)
3321
+ return 0.5;
3322
+ if (type === "log") {
3323
+ if (a <= 0 || b <= 0 || value <= 0)
3324
+ return NaN;
3325
+ return Math.log(value / a) / Math.log(b / a);
3326
+ }
3327
+ if (type === "sqrt") {
3328
+ if (a < 0 || b < 0 || value < 0)
3329
+ return NaN;
3330
+ return (Math.sqrt(value) - Math.sqrt(a)) / (Math.sqrt(b) - Math.sqrt(a));
3331
+ }
3332
+ if (type === "symlog") {
3333
+ const symlog = (v) => Math.sign(v) * Math.log1p(Math.abs(v));
3334
+ return (symlog(value) - symlog(a)) / (symlog(b) - symlog(a));
3335
+ }
3336
+ return (value - a) / (b - a);
3337
+ }
3338
+ function numericValues(domain) {
3339
+ if (!domain.length || domain.some((v) => typeof v !== "number" || !Number.isFinite(v))) {
3340
+ throw new Error("Numeric scale requires a finite numeric domain");
3341
+ }
3342
+ return domain;
3343
+ }
3344
+ function compileResolvedScale(spec, domain, thresholds) {
3345
+ const colorType = [
3346
+ "sequential",
3347
+ "diverging",
3348
+ "ordinal",
3349
+ "quantize",
3350
+ "quantile",
3351
+ "threshold",
3352
+ "piecewise"
3353
+ ].includes(spec.type);
3354
+ if (colorType && spec.range.type === "numeric")
3355
+ throw new Error("Color scale requires colors");
3356
+ if (!colorType && spec.range.type !== "numeric")
3357
+ throw new Error("Numeric scale requires numeric range");
3358
+ const classes = spec.range.type === "palette" ? spec.range.count : void 0;
3359
+ let palette = colorType ? resolvePalette(spec.range, classes) : void 0;
3360
+ if ((thresholds == null ? void 0 : thresholds.length) && thresholds.length + 1 !== ((palette == null ? void 0 : palette.length) ?? 0))
3361
+ throw new Error("Scale class count must match palette color count");
3362
+ if (spec.type === "quantile" && thresholds) {
3363
+ const original = thresholds;
3364
+ thresholds = original.filter((value, i) => i === 0 || value !== original[i - 1]);
3365
+ palette = palette.filter((_, i) => i === 0 || i === original.length || original[i - 1] !== original[i]);
3366
+ }
3367
+ const encoding = spec.encoding ?? SRGB;
3368
+ const paletteStops = palette && spec.range.type === "palette" && spec.encoding ? palette.map((color) => convertScaleColor(color, SRGB, encoding)) : palette;
3369
+ const space = spec.interpolation ?? "srgb";
3370
+ const workingStops = paletteStops && (space === "linear-srgb" || space === "oklab") ? paletteStops.map((color) => convertScaleColor(color, encoding, SRGB)) : paletteStops;
3371
+ if (spec.type === "ordinal" && domain.length > ((paletteStops == null ? void 0 : paletteStops.length) ?? 0)) {
3372
+ throw new Error("Ordinal palette must have at least one color per category");
3373
+ }
3374
+ const resolvedRange = spec.range.type === "numeric" ? spec.range : { type: "colors", values: paletteStops };
3375
+ const descriptor = {
3376
+ ...spec,
3377
+ domain: [...domain],
3378
+ range: resolvedRange,
3379
+ ...spec.range.type === "palette" ? { palette: spec.range.name } : {},
3380
+ ...thresholds ? { thresholds: [...thresholds] } : {}
3381
+ };
3382
+ const isOrdinal = spec.type === "ordinal";
3383
+ const values = isOrdinal ? domain : numericValues(domain);
3384
+ const numerical = isOrdinal ? [] : numericValues(domain);
3385
+ if (!isOrdinal && numerical.length < 2)
3386
+ throw new Error("Numeric domain requires two endpoints");
3387
+ const pivot = spec.type === "diverging" ? spec.pivot : void 0;
3388
+ if (pivot !== void 0 && !(numerical[0] < pivot && pivot < numerical[numerical.length - 1]))
3389
+ throw new Error("Diverging scale pivot must be between the domain endpoints");
3390
+ const breaks = thresholds ?? [];
3391
+ if (["quantile", "quantize", "threshold"].includes(spec.type) && !thresholds) {
3392
+ throw new Error(`${spec.type} scale requires resolved class breaks`);
3393
+ }
3394
+ const sample = (value) => {
3395
+ if (value === null)
3396
+ return spec.nullColor ?? null;
3397
+ if (isOrdinal) {
3398
+ const index = values.indexOf(value);
3399
+ return index === -1 ? spec.nullColor ?? null : paletteStops[index];
3400
+ }
3401
+ if (typeof value !== "number" || !Number.isFinite(value))
3402
+ return spec.nullColor ?? null;
3403
+ const min = numerical[0], max = numerical[numerical.length - 1];
3404
+ if (value < min && spec.underColor)
3405
+ return spec.underColor;
3406
+ if (value > max && spec.overColor)
3407
+ return spec.overColor;
3408
+ if (spec.type === "quantile" || spec.type === "quantize" || spec.type === "threshold") {
3409
+ const index = breaks.findIndex((boundary) => value < boundary);
3410
+ const colorIndex = index < 0 ? breaks.length : index;
3411
+ return paletteStops[Math.min(colorIndex, paletteStops.length - 1)];
3412
+ }
3413
+ const stopCount = colorType ? paletteStops.length : resolvedRange.values.length;
3414
+ if (numerical.length !== 2 && numerical.length !== stopCount) {
3415
+ throw new Error("Piecewise domain and range stops must have equal lengths");
3416
+ }
3417
+ let segment = 0;
3418
+ let t;
3419
+ if (numerical.length === 2) {
3420
+ t = pivot === void 0 ? normalize(value, min, max, spec.type) : value <= pivot ? normalize(value, min, pivot, spec.type) / 2 : 0.5 + normalize(value, pivot, max, spec.type) / 2;
3421
+ if (spec.clamp ?? colorType)
3422
+ t = clamp01(t);
3423
+ const position = t * (stopCount - 1);
3424
+ segment = Math.min(stopCount - 2, Math.max(0, Math.floor(position)));
3425
+ t = position - segment;
3426
+ } else {
3427
+ while (segment < numerical.length - 2 && value > numerical[segment + 1])
3428
+ segment++;
3429
+ t = normalize(value, numerical[segment], numerical[segment + 1], spec.type);
3430
+ if (spec.clamp ?? colorType)
3431
+ t = clamp01(t);
3432
+ }
3433
+ if (!Number.isFinite(t))
3434
+ return spec.nullColor ?? null;
3435
+ if (colorType) {
3436
+ const color = interpolateColor(workingStops[segment], workingStops[segment + 1], t, space);
3437
+ return workingStops === paletteStops ? color : convertScaleColor(color, SRGB, encoding);
3438
+ }
3439
+ const numbers = resolvedRange.values;
3440
+ return numbers[segment] + (numbers[segment + 1] - numbers[segment]) * t;
3441
+ };
3442
+ return createResolvedScale(descriptor, sample);
3443
+ }
3444
+
3445
+ // dist/scales/arrow-domains.js
3446
+ function arrowScaleValue(value) {
3447
+ if (typeof value !== "bigint")
3448
+ return value;
3449
+ const numeric = Number(value);
3450
+ if (!Number.isSafeInteger(numeric))
3451
+ throw new RangeError("Scale integer exceeds the safe numeric range");
3452
+ return numeric;
3453
+ }
3454
+ function quantileSorted(sorted, probability) {
3455
+ if (!sorted.length || !Number.isFinite(probability) || probability < 0 || probability > 1) {
3456
+ throw new Error("Quantile requires nonempty finite samples and a probability in [0, 1]");
3457
+ }
3458
+ const index = (sorted.length - 1) * probability;
3459
+ const lower = Math.floor(index);
3460
+ const fraction = index - lower;
3461
+ return sorted[lower] + fraction * (sorted[Math.ceil(index)] - sorted[lower]);
3462
+ }
3463
+ function resolveArrowDomains(table, domains) {
3464
+ const columns = /* @__PURE__ */ new Map();
3465
+ const needsSamples = /* @__PURE__ */ new Set();
3466
+ const needsCategories = /* @__PURE__ */ new Set();
3467
+ for (const domain of domains) {
3468
+ if (domain.type === "percentile")
3469
+ needsSamples.add(domain.column);
3470
+ if (domain.type === "categories")
3471
+ needsCategories.add(domain.column);
3472
+ if (domain.type !== "fixed" && !table.getChild(domain.column)) {
3473
+ throw new Error(`Unknown scale domain column: ${domain.column}`);
3474
+ }
3475
+ }
3476
+ for (const domain of domains) {
3477
+ if (domain.type === "fixed" || columns.has(domain.column))
3478
+ continue;
3479
+ const vector = table.getChild(domain.column);
3480
+ const state = {
3481
+ values: [],
3482
+ categories: /* @__PURE__ */ new Set(),
3483
+ min: Infinity,
3484
+ max: -Infinity
3485
+ };
3486
+ const samples = needsSamples.has(domain.column);
3487
+ for (let row = 0; row < vector.length; row++) {
3488
+ const value = arrowScaleValue(vector.get(row));
3489
+ if (value === null || value === void 0)
3490
+ continue;
3491
+ if (typeof value === "string") {
3492
+ if (needsCategories.has(domain.column))
3493
+ state.categories.add(value);
3494
+ continue;
3495
+ }
3496
+ if (typeof value !== "number" || !Number.isFinite(value)) {
3497
+ throw new Error(`Unsupported scale domain value in ${domain.column} at row ${row}`);
3498
+ }
3499
+ if (needsCategories.has(domain.column))
3500
+ state.categories.add(value);
3501
+ if (value < state.min)
3502
+ state.min = value;
3503
+ if (value > state.max)
3504
+ state.max = value;
3505
+ if (samples)
3506
+ state.values.push(value);
3507
+ }
3508
+ if (samples)
3509
+ state.values.sort((a, b) => a - b);
3510
+ columns.set(domain.column, state);
3511
+ }
3512
+ return domains.map((domain) => {
3513
+ if (domain.type === "fixed")
3514
+ return [...domain.values];
3515
+ const data = columns.get(domain.column);
3516
+ if (domain.type === "categories") {
3517
+ const values = [...data.categories];
3518
+ if (domain.order !== "first-seen")
3519
+ values.sort((a, b) => typeof a === "number" && typeof b === "number" ? a - b : a < b ? -1 : a > b ? 1 : 0);
3520
+ if (!values.length)
3521
+ throw new Error(`Empty categorical scale domain: ${domain.column}`);
3522
+ return values;
3523
+ }
3524
+ if (!Number.isFinite(data.min) || !Number.isFinite(data.max)) {
3525
+ throw new Error(`Empty numeric scale domain: ${domain.column}`);
3526
+ }
3527
+ if (domain.type === "percentile") {
3528
+ return [quantileSorted(data.values, domain.lower), quantileSorted(data.values, domain.upper)];
3529
+ }
3530
+ if (domain.type === "symmetric") {
3531
+ const radius = Math.max(Math.abs(data.min - domain.pivot), Math.abs(data.max - domain.pivot));
3532
+ return [domain.pivot - radius, domain.pivot + radius];
3533
+ }
3534
+ if (domain.includeZero)
3535
+ return [Math.min(0, data.min), Math.max(0, data.max)];
3536
+ return [data.min, data.max];
3537
+ });
3538
+ }
3539
+ function resolveArrowQuantiles(table, column, classes) {
3540
+ if (!Number.isSafeInteger(classes) || classes < 2)
3541
+ throw new Error("Quantile classes must be >= 2");
3542
+ const vector = table.getChild(column);
3543
+ if (!vector)
3544
+ throw new Error(`Unknown quantile column: ${column}`);
3545
+ const values = [];
3546
+ for (let row = 0; row < vector.length; row++) {
3547
+ const value = arrowScaleValue(vector.get(row));
3548
+ if (value === null || value === void 0)
3549
+ continue;
3550
+ if (typeof value !== "number" || !Number.isFinite(value)) {
3551
+ throw new Error(`Quantile column ${column} must be finite numeric`);
3552
+ }
3553
+ values.push(value);
3554
+ }
3555
+ values.sort((a, b) => a - b);
3556
+ return Array.from({ length: classes - 1 }, (_, i) => quantileSorted(values, (i + 1) / classes));
3557
+ }
3558
+
3559
+ // dist/scales/quantile-sketch.js
3560
+ var ScaleQuantileSketch = class {
3561
+ constructor(capacity = 256) {
3562
+ this.samples = [];
3563
+ this.parity = 0;
3564
+ this.count = 0;
3565
+ this.min = Infinity;
3566
+ this.max = -Infinity;
3567
+ if (!Number.isSafeInteger(capacity) || capacity < 16 || capacity > 65536) {
3568
+ throw new Error("Quantile sketch capacity must be an integer between 16 and 65536");
3569
+ }
3570
+ this.capacity = capacity;
3571
+ }
3572
+ get length() {
3573
+ return this.count;
3574
+ }
3575
+ get storedSamples() {
3576
+ return this.samples.length;
3577
+ }
3578
+ add(value) {
3579
+ if (!Number.isFinite(value))
3580
+ throw new Error("Quantile sketch requires finite values");
3581
+ this.samples.push({ value, weight: 1 });
3582
+ this.count++;
3583
+ this.min = Math.min(this.min, value);
3584
+ this.max = Math.max(this.max, value);
3585
+ if (this.samples.length >= this.capacity * 2)
3586
+ this.reduce();
3587
+ }
3588
+ merge(other) {
3589
+ if (other === this)
3590
+ throw new Error("Cannot merge a quantile sketch with itself");
3591
+ for (const item of other.samples)
3592
+ this.samples.push({ ...item });
3593
+ this.count += other.count;
3594
+ this.min = Math.min(this.min, other.min);
3595
+ this.max = Math.max(this.max, other.max);
3596
+ this.reduce();
3597
+ }
3598
+ quantile(probability) {
3599
+ if (!Number.isFinite(probability) || probability < 0 || probability > 1) {
3600
+ throw new Error("Quantile probability must be in [0, 1]");
3601
+ }
3602
+ if (!this.count)
3603
+ return null;
3604
+ const sorted = [...this.samples].sort((a, b) => a.value - b.value);
3605
+ if (probability === 0)
3606
+ return this.min;
3607
+ if (probability === 1)
3608
+ return this.max;
3609
+ const index = probability * (this.count - 1);
3610
+ const lowerRank = Math.floor(index);
3611
+ const upperRank = Math.ceil(index);
3612
+ const fraction = index - lowerRank;
3613
+ let cumulative = 0;
3614
+ let lower;
3615
+ for (const sample of sorted) {
3616
+ cumulative += sample.weight;
3617
+ if (lowerRank < cumulative) {
3618
+ lower ?? (lower = sample.value);
3619
+ if (upperRank < cumulative)
3620
+ return lower * (1 - fraction) + sample.value * fraction;
3621
+ }
3622
+ }
3623
+ return this.max;
3624
+ }
3625
+ /** Compact comparable weights first so recent rows do not absorb older heavy samples. */
3626
+ reduce() {
3627
+ while (this.samples.length > this.capacity) {
3628
+ const levels = /* @__PURE__ */ new Map();
3629
+ for (const sample of this.samples) {
3630
+ let level2 = levels.get(sample.weight);
3631
+ if (!level2) {
3632
+ level2 = [];
3633
+ levels.set(sample.weight, level2);
3634
+ }
3635
+ level2.push(sample);
3636
+ }
3637
+ const weights = [...levels.keys()].sort((a, b) => a - b);
3638
+ const weight = weights.find((candidate) => levels.get(candidate).length > 1);
3639
+ if (weight === void 0) {
3640
+ const a = levels.get(weights[0]).pop();
3641
+ const b = levels.get(weights[1]).pop();
3642
+ this.samples = this.samples.filter((item) => item !== a && item !== b);
3643
+ this.samples.push({ value: b.value, weight: a.weight + b.weight });
3644
+ continue;
3645
+ }
3646
+ const level = levels.get(weight).sort((a, b) => a.value - b.value);
3647
+ const offset = this.parity++ % 2;
3648
+ const compacted = [];
3649
+ for (let i = 0; i + 1 < level.length; i += 2) {
3650
+ compacted.push({ value: level[i + offset].value, weight: weight * 2 });
3651
+ }
3652
+ if (level.length % 2)
3653
+ compacted.push(level[level.length - 1]);
3654
+ this.samples = this.samples.filter((sample) => sample.weight !== weight).concat(compacted);
3655
+ }
3656
+ }
3657
+ };
3658
+
3659
+ // dist/scales/streaming-domains.js
3660
+ function createStreamingDomainAccumulator(domains, options = {}) {
3661
+ const columns = /* @__PURE__ */ new Map();
3662
+ const quantileColumns = new Set(options.quantileColumns ?? []);
3663
+ for (const domain of domains) {
3664
+ if (domain.type === "fixed")
3665
+ continue;
3666
+ const previous = columns.get(domain.column);
3667
+ if (previous) {
3668
+ if ((domain.type === "percentile" || quantileColumns.has(domain.column)) && !previous.sketch) {
3669
+ previous.sketch = new ScaleQuantileSketch(options.quantileCapacity);
3670
+ }
3671
+ if (domain.type === "categories")
3672
+ previous.categories ?? (previous.categories = /* @__PURE__ */ new Set());
3673
+ continue;
3674
+ }
3675
+ columns.set(domain.column, {
3676
+ min: Infinity,
3677
+ max: -Infinity,
3678
+ seen: 0,
3679
+ ...domain.type === "categories" ? { categories: /* @__PURE__ */ new Set() } : {},
3680
+ ...domain.type === "percentile" || quantileColumns.has(domain.column) ? { sketch: new ScaleQuantileSketch(options.quantileCapacity) } : {}
3681
+ });
3682
+ }
3683
+ for (const name of quantileColumns) {
3684
+ if (!columns.has(name))
3685
+ columns.set(name, {
3686
+ min: Infinity,
3687
+ max: -Infinity,
3688
+ seen: 0,
3689
+ sketch: new ScaleQuantileSketch(options.quantileCapacity)
3690
+ });
3691
+ }
3692
+ return {
3693
+ update(batch) {
3694
+ var _a2, _b, _c;
3695
+ for (const [name, state] of columns) {
3696
+ const vector = batch.getChild(name);
3697
+ if (!vector)
3698
+ throw new Error(`Missing scale column: ${name}`);
3699
+ for (let row = 0; row < vector.length; row++) {
3700
+ const value = arrowScaleValue(vector.get(row));
3701
+ if (value === null || value === void 0)
3702
+ continue;
3703
+ if (typeof value === "string") {
3704
+ (_a2 = state.categories) == null ? void 0 : _a2.add(value);
3705
+ } else if (typeof value === "number" && Number.isFinite(value)) {
3706
+ (_b = state.categories) == null ? void 0 : _b.add(value);
3707
+ state.seen++;
3708
+ state.min = Math.min(state.min, value);
3709
+ state.max = Math.max(state.max, value);
3710
+ (_c = state.sketch) == null ? void 0 : _c.add(value);
3711
+ } else {
3712
+ throw new Error(`Scale column ${name} has unsupported value at row ${row}`);
3713
+ }
3714
+ }
3715
+ }
3716
+ },
3717
+ result() {
3718
+ return domains.map((domain) => {
3719
+ if (domain.type === "fixed")
3720
+ return [...domain.values];
3721
+ const state = columns.get(domain.column);
3722
+ if (domain.type === "categories") {
3723
+ const labels = [...state.categories];
3724
+ return domain.order === "first-seen" ? labels : labels.sort((a, b) => typeof a === "number" && typeof b === "number" ? a - b : a < b ? -1 : a > b ? 1 : 0);
3725
+ }
3726
+ if (!state.seen)
3727
+ return [];
3728
+ if (domain.type === "percentile") {
3729
+ return [state.sketch.quantile(domain.lower), state.sketch.quantile(domain.upper)];
3730
+ }
3731
+ if (domain.type === "symmetric") {
3732
+ const radius = Math.max(Math.abs(state.min - domain.pivot), Math.abs(state.max - domain.pivot));
3733
+ return [domain.pivot - radius, domain.pivot + radius];
3734
+ }
3735
+ if (domain.includeZero)
3736
+ return [Math.min(state.min, 0), Math.max(state.max, 0)];
3737
+ return [state.min, state.max];
3738
+ });
3739
+ },
3740
+ quantileBreaks(column, classes) {
3741
+ var _a2;
3742
+ if (!Number.isSafeInteger(classes) || classes < 2) {
3743
+ throw new Error("Scale class count must be at least two");
3744
+ }
3745
+ const sketch = (_a2 = columns.get(column)) == null ? void 0 : _a2.sketch;
3746
+ if (!sketch)
3747
+ throw new Error(`Column ${column} has no quantile sketch`);
3748
+ if (!sketch.length)
3749
+ return [];
3750
+ return Array.from({ length: classes - 1 }, (_, i) => sketch.quantile((i + 1) / classes));
3751
+ }
3752
+ };
3753
+ }
3754
+
3755
+ // dist/scales/arrow-scales.js
3756
+ function asColor(value) {
3757
+ if (value === null)
3758
+ return null;
3759
+ if (typeof value === "number")
3760
+ throw new Error("Expected a color-valued scale");
3761
+ return value;
3762
+ }
3763
+ function toVector(rows, spec) {
3764
+ var _a2;
3765
+ const numeric = spec.range.type === "numeric";
3766
+ if (numeric) {
3767
+ return (0, import_apache_arrow7.vectorFromArray)(rows, new import_apache_arrow7.Float64());
3768
+ }
3769
+ const format = ((_a2 = spec.encoding) == null ? void 0 : _a2.format) ?? "rgba8unorm";
3770
+ const type = format === "rgba8unorm" ? new import_apache_arrow7.Uint8() : format === "rgba16unorm" ? new import_apache_arrow7.Uint16() : format === "rgba16float" ? new import_apache_arrow7.Float16() : new import_apache_arrow7.Float32();
3771
+ const factor = format === "rgba8unorm" ? 255 : format === "rgba16unorm" ? 65535 : void 0;
3772
+ const vector = nullTupleVector(new import_apache_arrow7.FixedSizeList(4, new import_apache_arrow7.Field("item", type, false)), rows.length);
3773
+ const channels = vector.getChildAt(0);
3774
+ for (let row = 0; row < rows.length; row++) {
3775
+ const color = asColor(rows[row]);
3776
+ if (!color)
3777
+ continue;
3778
+ for (let component = 0; component < 4; component++) {
3779
+ const channel = color[component];
3780
+ if (!Number.isFinite(channel) || format === "rgba16float" && Math.abs(channel) >= 65520 || format === "rgba32float" && !Number.isFinite(Math.fround(channel)))
3781
+ throw new Error("Scale color cannot be represented in the requested format");
3782
+ channels.set(row * 4 + component, factor === void 0 ? channel : Math.round(Math.max(0, Math.min(1, channel)) * factor));
3783
+ }
3784
+ vector.data[0].setValid(row, true);
3785
+ }
3786
+ return vector;
3787
+ }
3788
+ function compileArrowScale(table, parsed, resolvedDomain) {
3789
+ const domain = resolvedDomain ?? resolveArrowDomains(table, [parsed.scale.domain])[0];
3790
+ let thresholds;
3791
+ const kind = parsed.scale.type;
3792
+ const classCount = parsed.scale.range.type === "palette" ? parsed.scale.range.count : void 0;
3793
+ if (kind === "quantile") {
3794
+ if (!classCount || parsed.scale.domain.type === "fixed") {
3795
+ throw new Error("Quantile scale requires a class count and a source column");
3796
+ }
3797
+ const column = parsed.scale.domain.column;
3798
+ thresholds = resolveArrowQuantiles(table, column, classCount);
3799
+ } else if (kind === "quantize") {
3800
+ if (!classCount || domain.length !== 2 || typeof domain[0] !== "number" || typeof domain[1] !== "number") {
3801
+ throw new Error("Quantize scale requires a numeric extent and a class count");
3802
+ }
3803
+ thresholds = Array.from({ length: classCount - 1 }, (_, i) => domain[0] + (domain[1] - domain[0]) * (i + 1) / classCount);
3804
+ } else if (kind === "threshold") {
3805
+ if (domain.some((value) => typeof value !== "number")) {
3806
+ throw new Error("Thresholds require numeric domain values");
3807
+ }
3808
+ thresholds = domain;
3809
+ }
3810
+ const scale = compileResolvedScale(parsed.scale, domain, thresholds);
3811
+ const compiled = compileArrowExpression(parsed.value, {
3812
+ inputSchema: table.schema
3813
+ });
3814
+ const evaluateVector = (input) => {
3815
+ const result = Array.from({ length: input.length }, (_, i) => {
3816
+ const value = arrowScaleValue(input.get(i));
3817
+ if (value === null || value === void 0)
3818
+ return scale.sample(null);
3819
+ if (typeof value !== "number" && typeof value !== "string") {
3820
+ throw new Error("Scale expression must produce scalar numeric or categorical values");
3821
+ }
3822
+ return scale.sample(value);
3823
+ });
3824
+ return toVector(result, parsed.scale);
3825
+ };
3826
+ return {
3827
+ scale,
3828
+ evaluate: (input) => evaluateVector(compiled.evaluateTable(input)),
3829
+ evaluateBatch: (batch) => evaluateVector(compiled.evaluate(batch))
3830
+ };
3831
+ }
3832
+ function compileArrowScales(table, expressions) {
3833
+ const entries = Object.entries(expressions);
3834
+ const domains = resolveArrowDomains(table, entries.map(([, parsed]) => parsed.scale.domain));
3835
+ return Object.fromEntries(entries.map(([key, parsed], index) => [key, compileArrowScale(table, parsed, domains[index])]));
3836
+ }
3837
+ //# sourceMappingURL=arrow-scales.cjs.map