@johnhenry/mallory-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (760) hide show
  1. package/README.md +60 -2
  2. package/bin/mallory.mjs +51 -0
  3. package/package.json +51 -4
  4. package/src/a2a/client.js +511 -0
  5. package/src/a2a/demo-agent.js +396 -0
  6. package/src/a2a/hub.js +578 -0
  7. package/src/a2a/settings.js +88 -0
  8. package/src/a2a/task.js +358 -0
  9. package/src/acp/client.js +573 -0
  10. package/src/acp/demo-agent.js +332 -0
  11. package/src/acp/hub.js +632 -0
  12. package/src/acp/settings.js +78 -0
  13. package/src/actions/map.js +524 -0
  14. package/src/agent/cloud.js +77 -0
  15. package/src/agent/compact.js +84 -0
  16. package/src/agent/constants.js +39 -0
  17. package/src/agent/diff.js +101 -0
  18. package/src/agent/fork.js +159 -0
  19. package/src/agent/grounding.js +73 -0
  20. package/src/agent/guards.js +129 -0
  21. package/src/agent/local-transport.js +152 -0
  22. package/src/agent/loop.js +479 -0
  23. package/src/agent/park-store.js +77 -0
  24. package/src/agent/park.js +76 -0
  25. package/src/agent/ports.js +28 -0
  26. package/src/agent/providers.js +591 -0
  27. package/src/agent/restart.js +51 -0
  28. package/src/agent/router.js +380 -0
  29. package/src/agent/run.js +861 -0
  30. package/src/agent/tools.js +247 -0
  31. package/src/agent-library/engine.js +43 -0
  32. package/src/ai/bridge.js +155 -0
  33. package/src/ai/policy.js +131 -0
  34. package/src/aimatey/vendor.js +18 -0
  35. package/src/audio/container-duration.js +35 -0
  36. package/src/audio/instruments.js +776 -0
  37. package/src/audio/lanes.js +230 -0
  38. package/src/audio/patch.js +1410 -0
  39. package/src/audio/plan.js +276 -0
  40. package/src/audio/rack.js +1006 -0
  41. package/src/audio/sample-trim.js +293 -0
  42. package/src/audio/soundfont.js +243 -0
  43. package/src/audio/take-store.js +87 -0
  44. package/src/audio/takes.js +129 -0
  45. package/src/audio/wav.js +170 -0
  46. package/src/audio/zzfx.js +333 -0
  47. package/src/autonomy/bundle.js +207 -0
  48. package/src/autonomy/confine.js +61 -0
  49. package/src/autonomy/enforce.js +155 -0
  50. package/src/autonomy/file-kv.js +88 -0
  51. package/src/autonomy/ledger.js +203 -0
  52. package/src/autonomy/pins.js +50 -0
  53. package/src/autonomy/psl/index.js +32 -0
  54. package/src/autonomy/psl/suffixes.json +1 -0
  55. package/src/autonomy/record.js +28 -0
  56. package/src/autonomy/routines.js +107 -0
  57. package/src/autonomy/server.js +175 -0
  58. package/src/autonomy/signer-node.js +167 -0
  59. package/src/autonomy/store.js +43 -0
  60. package/src/autonomy/unattended.js +13 -0
  61. package/src/bytes/bytes.js +378 -0
  62. package/src/calc/syntax.js +125 -0
  63. package/src/calc/tex.js +28 -0
  64. package/src/calendar/vendor.js +2 -0
  65. package/src/clipboard.js +130 -0
  66. package/src/clsh/clsh.js +3417 -0
  67. package/src/codec/capnp.js +1804 -0
  68. package/src/codec/core.js +2043 -0
  69. package/src/codec/vendor/avro.js +136 -0
  70. package/src/codec/vendor/cbor.js +25 -0
  71. package/src/codec/vendor/flatbuffers.js +206 -0
  72. package/src/codec/vendor/msgpack.js +9 -0
  73. package/src/codec/vendor/protobuf.js +53 -0
  74. package/src/delegation/caps.js +60 -0
  75. package/src/delegation/config.js +32 -0
  76. package/src/device/model.js +246 -0
  77. package/src/device/recording.js +198 -0
  78. package/src/device/stream-model.js +151 -0
  79. package/src/documents/documents.js +1224 -0
  80. package/src/effects/catalog.js +63 -0
  81. package/src/effects/extras.js +133 -0
  82. package/src/effects/parse.js +339 -0
  83. package/src/embed/protocol.js +131 -0
  84. package/src/env/env.js +159 -0
  85. package/src/exact/vendor.js +45 -0
  86. package/src/example-meta.js +164 -0
  87. package/src/examples.js +94 -0
  88. package/src/export/canvas-image.js +217 -0
  89. package/src/export/expr-latex-lazy.js +8 -0
  90. package/src/export/formats.js +322 -0
  91. package/src/export/latex.js +183 -0
  92. package/src/export/pane.js +184 -0
  93. package/src/export/value.js +452 -0
  94. package/src/export/zip.js +214 -0
  95. package/src/ext/access.js +58 -0
  96. package/src/ext/btasks.js +225 -0
  97. package/src/ext/client.js +209 -0
  98. package/src/ext/tools.js +69 -0
  99. package/src/ext/view.js +105 -0
  100. package/src/ext/webmcp-tabs.js +299 -0
  101. package/src/files/archive.js +232 -0
  102. package/src/files/files.js +317 -0
  103. package/src/formats/json.js +24 -0
  104. package/src/formats/jupyter.js +188 -0
  105. package/src/formats/markdown.js +254 -0
  106. package/src/formats/n8n.js +276 -0
  107. package/src/formats/node-red.js +363 -0
  108. package/src/formats/registry.js +177 -0
  109. package/src/formats/rivet.js +259 -0
  110. package/src/formats/shared.js +98 -0
  111. package/src/formats/structure.js +182 -0
  112. package/src/formats/yaml.js +127 -0
  113. package/src/frame/frame.js +962 -0
  114. package/src/frame/vendor.js +1484 -0
  115. package/src/gate/audit.js +116 -0
  116. package/src/gate/gate.js +365 -0
  117. package/src/gate/policy.js +295 -0
  118. package/src/gate/scripted.js +110 -0
  119. package/src/gate/seams.js +32 -0
  120. package/src/gate/store.js +66 -0
  121. package/src/geometry/model.js +533 -0
  122. package/src/grant-key.js +149 -0
  123. package/src/graph/model.js +381 -0
  124. package/src/headless/a2a-push.js +123 -0
  125. package/src/headless/channels/config.js +142 -0
  126. package/src/headless/channels/connectors.js +283 -0
  127. package/src/headless/channels/index.js +257 -0
  128. package/src/headless/channels/mail.js +197 -0
  129. package/src/headless/channels/mailnet.js +223 -0
  130. package/src/headless/channels/platforms.js +194 -0
  131. package/src/headless/channels/replay.js +49 -0
  132. package/src/headless/cli.js +1397 -0
  133. package/src/headless/companion-client.js +182 -0
  134. package/src/headless/cost-cli.js +177 -0
  135. package/src/headless/deprecations-cli.js +102 -0
  136. package/src/headless/examples.js +48 -0
  137. package/src/headless/ffmpeg-exec.js +217 -0
  138. package/src/headless/gateways/config.js +213 -0
  139. package/src/headless/gateways/homeassistant.js +159 -0
  140. package/src/headless/gateways/index.js +121 -0
  141. package/src/headless/gateways/matter.js +150 -0
  142. package/src/headless/gateways/mqtt-client.js +177 -0
  143. package/src/headless/gateways/mqtt.js +70 -0
  144. package/src/headless/gateways/netway.js +226 -0
  145. package/src/headless/gateways/serverpod-worker.mjs +16 -0
  146. package/src/headless/gateways/serverpod.js +71 -0
  147. package/src/headless/gateways/util.js +27 -0
  148. package/src/headless/grant-cli.js +208 -0
  149. package/src/headless/guard.js +125 -0
  150. package/src/headless/guards.js +124 -0
  151. package/src/headless/machine-cli.js +853 -0
  152. package/src/headless/mcp-endpoint.js +287 -0
  153. package/src/headless/mcp-roots.js +38 -0
  154. package/src/headless/model-endpoint.js +88 -0
  155. package/src/headless/net.js +151 -0
  156. package/src/headless/node.js +263 -0
  157. package/src/headless/npm-tarball.js +29 -0
  158. package/src/headless/operator-page.js +112 -0
  159. package/src/headless/operator.js +242 -0
  160. package/src/headless/people.js +34 -0
  161. package/src/headless/pkg-cli.js +1103 -0
  162. package/src/headless/pkg-serve.js +138 -0
  163. package/src/headless/process-worker.js +88 -0
  164. package/src/headless/runner-remote.js +477 -0
  165. package/src/headless/sandbox-child.mjs +21 -0
  166. package/src/headless/scheduled.js +557 -0
  167. package/src/headless/serve-stream.js +97 -0
  168. package/src/headless/serve.js +2238 -0
  169. package/src/headless/short-links.js +158 -0
  170. package/src/headless/static-dirs.js +207 -0
  171. package/src/headless/trust-file.js +51 -0
  172. package/src/headless/watch.js +291 -0
  173. package/src/headless/ws-connect.js +65 -0
  174. package/src/headless/ws-connections.js +44 -0
  175. package/src/headless/ws-echo.js +150 -0
  176. package/src/headless/ws-proxy.js +354 -0
  177. package/src/headless/ws-ticket.js +48 -0
  178. package/src/hooks/config.js +50 -0
  179. package/src/hooks/engine.js +189 -0
  180. package/src/input/log.js +613 -0
  181. package/src/input/player.js +217 -0
  182. package/src/input/replay.js +209 -0
  183. package/src/jth/vendor.js +28 -0
  184. package/src/ledger/tx.js +94 -0
  185. package/src/machine/apply.js +193 -0
  186. package/src/machine/diff.js +168 -0
  187. package/src/machine/drive.js +296 -0
  188. package/src/machine/engine.js +478 -0
  189. package/src/machine/files-tool.js +76 -0
  190. package/src/machine/lint.js +139 -0
  191. package/src/machine/llmtm-trace.js +117 -0
  192. package/src/machine/llmtm.js +475 -0
  193. package/src/machine/otel.js +80 -0
  194. package/src/machine/pane-provider.js +51 -0
  195. package/src/machine/propose.js +159 -0
  196. package/src/machine/random.js +52 -0
  197. package/src/machine/risk.js +107 -0
  198. package/src/machine/session.js +1017 -0
  199. package/src/machine/shell-tool.js +45 -0
  200. package/src/machine/tape.js +349 -0
  201. package/src/machine/templates.js +104 -0
  202. package/src/machine/trace.js +664 -0
  203. package/src/machine/view.js +73 -0
  204. package/src/machine/vm-tool.js +47 -0
  205. package/src/machine/watchdog.js +46 -0
  206. package/src/mcp/app-args.js +51 -0
  207. package/src/mcp/app-run.js +56 -0
  208. package/src/mcp/apps.js +468 -0
  209. package/src/mcp/cache.js +232 -0
  210. package/src/mcp/client.js +507 -0
  211. package/src/mcp/demo-app.js +183 -0
  212. package/src/mcp/demo-server.js +602 -0
  213. package/src/mcp/elicitation.js +116 -0
  214. package/src/mcp/hub.js +1326 -0
  215. package/src/mcp/roots.js +139 -0
  216. package/src/mcp/sampling.js +105 -0
  217. package/src/mcp/settings.js +125 -0
  218. package/src/mcp/tape.js +292 -0
  219. package/src/mcp/uri-template.js +156 -0
  220. package/src/mcp/wsh-client.js +164 -0
  221. package/src/media/animated-codec.js +7 -0
  222. package/src/media/animated.js +623 -0
  223. package/src/media/compare-agent.js +70 -0
  224. package/src/media/compare-job.js +63 -0
  225. package/src/media/compare-page.js +296 -0
  226. package/src/media/compare-worker.js +14 -0
  227. package/src/media/compare.js +600 -0
  228. package/src/media/contract.js +62 -0
  229. package/src/media/decode-frame.js +57 -0
  230. package/src/media/decode-pool.js +188 -0
  231. package/src/media/ffmpeg-edit.js +344 -0
  232. package/src/media/ffmpeg-wasm-client.js +121 -0
  233. package/src/media/ffmpeg-wasm-session.js +79 -0
  234. package/src/media/ffmpeg-wasm.js +139 -0
  235. package/src/media/ffmpeg-worker.js +23 -0
  236. package/src/media/ffmpeg.js +903 -0
  237. package/src/media/helpers.js +419 -0
  238. package/src/media/keep.js +108 -0
  239. package/src/media/metadata-worker.js +16 -0
  240. package/src/media/metadata.js +2518 -0
  241. package/src/media/mime.js +102 -0
  242. package/src/media/page-decode.js +74 -0
  243. package/src/media/persist.js +114 -0
  244. package/src/media/png.js +226 -0
  245. package/src/media/sample-input.js +67 -0
  246. package/src/media/store.js +86 -0
  247. package/src/media/wav.js +109 -0
  248. package/src/midi/mappings.js +250 -0
  249. package/src/midi/message.js +125 -0
  250. package/src/model/action-hub.js +143 -0
  251. package/src/model/adapters.js +284 -0
  252. package/src/model/agent-runs.js +12 -0
  253. package/src/model/arrange.js +308 -0
  254. package/src/model/automation-clock.js +494 -0
  255. package/src/model/automation.js +653 -0
  256. package/src/model/batches.js +78 -0
  257. package/src/model/binary-view.js +195 -0
  258. package/src/model/breakpoints.js +392 -0
  259. package/src/model/calc-settings.js +65 -0
  260. package/src/model/calendar.js +254 -0
  261. package/src/model/canvas-id.js +5 -0
  262. package/src/model/canvas.js +5048 -0
  263. package/src/model/channel-names.js +29 -0
  264. package/src/model/channels.js +692 -0
  265. package/src/model/chart-clock.js +631 -0
  266. package/src/model/chart-code.js +69 -0
  267. package/src/model/codecs.js +60 -0
  268. package/src/model/companion-access.js +271 -0
  269. package/src/model/companion-pane.js +50 -0
  270. package/src/model/composite.js +324 -0
  271. package/src/model/context.js +380 -0
  272. package/src/model/controls.js +231 -0
  273. package/src/model/converter-presets.js +368 -0
  274. package/src/model/cost.js +580 -0
  275. package/src/model/curve-transform.js +122 -0
  276. package/src/model/cycles.js +176 -0
  277. package/src/model/debug-log.js +168 -0
  278. package/src/model/decision-clock.js +100 -0
  279. package/src/model/decisions.js +265 -0
  280. package/src/model/desk.js +87 -0
  281. package/src/model/device-hub.js +400 -0
  282. package/src/model/diff.js +445 -0
  283. package/src/model/emit-events.js +179 -0
  284. package/src/model/errors.js +238 -0
  285. package/src/model/event-presets.js +297 -0
  286. package/src/model/events.js +1303 -0
  287. package/src/model/explicit-setters.js +139 -0
  288. package/src/model/field-mapping.js +623 -0
  289. package/src/model/files-pane.js +263 -0
  290. package/src/model/flow-idle.js +89 -0
  291. package/src/model/foreach.js +549 -0
  292. package/src/model/frame-loop.js +71 -0
  293. package/src/model/frame-pressure.js +180 -0
  294. package/src/model/function-scaffold.js +1000 -0
  295. package/src/model/geometry-settings.js +54 -0
  296. package/src/model/goals.js +176 -0
  297. package/src/model/graph-settings.js +76 -0
  298. package/src/model/grid-widget.js +175 -0
  299. package/src/model/groups.js +332 -0
  300. package/src/model/hash.js +21 -0
  301. package/src/model/history.js +259 -0
  302. package/src/model/http-copy.js +88 -0
  303. package/src/model/http-send-companion.js +110 -0
  304. package/src/model/http-send.js +163 -0
  305. package/src/model/http-tap.js +521 -0
  306. package/src/model/http-tools.js +1138 -0
  307. package/src/model/import-lock.js +78 -0
  308. package/src/model/imports.js +258 -0
  309. package/src/model/infer-outputs.js +822 -0
  310. package/src/model/ink-connect.js +150 -0
  311. package/src/model/ink-diff.js +75 -0
  312. package/src/model/ink-gone.js +71 -0
  313. package/src/model/ink-route.js +120 -0
  314. package/src/model/ink-svg.js +206 -0
  315. package/src/model/ink.js +739 -0
  316. package/src/model/input-log-hub.js +456 -0
  317. package/src/model/input-split.js +69 -0
  318. package/src/model/json-schema-host.js +9 -0
  319. package/src/model/json-schema.js +368 -0
  320. package/src/model/jth.js +78 -0
  321. package/src/model/latex-expr.js +528 -0
  322. package/src/model/layout-history.js +120 -0
  323. package/src/model/lazy-map.js +88 -0
  324. package/src/model/ledger-pane.js +101 -0
  325. package/src/model/legacy-viaframe.js +90 -0
  326. package/src/model/lessons.js +448 -0
  327. package/src/model/links.js +981 -0
  328. package/src/model/live.js +411 -0
  329. package/src/model/math-widget.js +53 -0
  330. package/src/model/memory-settings.js +33 -0
  331. package/src/model/midi-controls.js +350 -0
  332. package/src/model/nl-time.js +408 -0
  333. package/src/model/notebook.js +137 -0
  334. package/src/model/pane-view-store.js +15 -0
  335. package/src/model/partial.js +115 -0
  336. package/src/model/pause-clock.js +53 -0
  337. package/src/model/peer-pane.js +32 -0
  338. package/src/model/persist-state.js +290 -0
  339. package/src/model/person-only.js +122 -0
  340. package/src/model/pin.js +209 -0
  341. package/src/model/plot-3d.js +213 -0
  342. package/src/model/plot-series.js +157 -0
  343. package/src/model/plot-settings.js +531 -0
  344. package/src/model/ports.js +312 -0
  345. package/src/model/presentation.js +222 -0
  346. package/src/model/preset-apply.js +316 -0
  347. package/src/model/preset-banks.js +335 -0
  348. package/src/model/preset-morph.js +263 -0
  349. package/src/model/preset-ops.js +205 -0
  350. package/src/model/preset-player.js +283 -0
  351. package/src/model/preset-states.js +172 -0
  352. package/src/model/profile-settings.js +109 -0
  353. package/src/model/promote.js +103 -0
  354. package/src/model/protected.js +10 -0
  355. package/src/model/proxy-log.js +230 -0
  356. package/src/model/proxy.js +367 -0
  357. package/src/model/quantity-widget.js +61 -0
  358. package/src/model/queue-book.js +359 -0
  359. package/src/model/quick-add.js +224 -0
  360. package/src/model/rate-limit.js +313 -0
  361. package/src/model/rate.js +95 -0
  362. package/src/model/recovery.js +216 -0
  363. package/src/model/rename-follow.js +113 -0
  364. package/src/model/repeater.js +1126 -0
  365. package/src/model/retention.js +664 -0
  366. package/src/model/route-edit.js +132 -0
  367. package/src/model/router.js +155 -0
  368. package/src/model/runaway.js +232 -0
  369. package/src/model/runlog.js +1033 -0
  370. package/src/model/runners/a2a.js +2 -0
  371. package/src/model/runners/acp.js +2 -0
  372. package/src/model/runners/actions.js +4 -0
  373. package/src/model/runners/agent.js +4 -0
  374. package/src/model/runners/audio.js +21 -0
  375. package/src/model/runners/automation.js +2 -0
  376. package/src/model/runners/calc.js +23 -0
  377. package/src/model/runners/catch.js +10 -0
  378. package/src/model/runners/codec.js +24 -0
  379. package/src/model/runners/companion-run.js +2 -0
  380. package/src/model/runners/device.js +7 -0
  381. package/src/model/runners/dom.js +13 -0
  382. package/src/model/runners/effects.js +2 -0
  383. package/src/model/runners/embed.js +11 -0
  384. package/src/model/runners/eval.js +2 -0
  385. package/src/model/runners/files.js +19 -0
  386. package/src/model/runners/geometry.js +23 -0
  387. package/src/model/runners/goals.js +18 -0
  388. package/src/model/runners/graph.js +23 -0
  389. package/src/model/runners/html.js +2 -0
  390. package/src/model/runners/http-proxy.js +185 -0
  391. package/src/model/runners/http-send.js +61 -0
  392. package/src/model/runners/http-static.js +83 -0
  393. package/src/model/runners/http-tap.js +26 -0
  394. package/src/model/runners/http.js +40 -0
  395. package/src/model/runners/import.js +2 -0
  396. package/src/model/runners/index.js +74 -0
  397. package/src/model/runners/input.js +14 -0
  398. package/src/model/runners/inputlog.js +7 -0
  399. package/src/model/runners/ledger.js +15 -0
  400. package/src/model/runners/machine.js +4 -0
  401. package/src/model/runners/mcp.js +2 -0
  402. package/src/model/runners/mcpapp.js +2 -0
  403. package/src/model/runners/media.js +18 -0
  404. package/src/model/runners/memory.js +28 -0
  405. package/src/model/runners/mesh-inspect.js +13 -0
  406. package/src/model/runners/peer.js +14 -0
  407. package/src/model/runners/plot.js +22 -0
  408. package/src/model/runners/render.js +14 -0
  409. package/src/model/runners/respond.js +2 -0
  410. package/src/model/runners/sample-soundfont.js +85 -0
  411. package/src/model/runners/sample.js +159 -0
  412. package/src/model/runners/scene.js +8 -0
  413. package/src/model/runners/score.js +24 -0
  414. package/src/model/runners/secret.js +10 -0
  415. package/src/model/runners/select.js +2 -0
  416. package/src/model/runners/shared.js +4 -0
  417. package/src/model/runners/shares.js +15 -0
  418. package/src/model/runners/shell.js +7 -0
  419. package/src/model/runners/skill.js +26 -0
  420. package/src/model/runners/state.js +2 -0
  421. package/src/model/runners/statechart.js +4 -0
  422. package/src/model/runners/subgraph.js +9 -0
  423. package/src/model/runners/tabs.js +25 -0
  424. package/src/model/runners/terminal.js +5 -0
  425. package/src/model/runners/text.js +4 -0
  426. package/src/model/runners/timer.js +7 -0
  427. package/src/model/runners/traffic.js +65 -0
  428. package/src/model/runners/trigger.js +2 -0
  429. package/src/model/runners/verdict.js +29 -0
  430. package/src/model/runners/vm.js +7 -0
  431. package/src/model/runners/wait.js +4 -0
  432. package/src/model/runners/ws-client.js +57 -0
  433. package/src/model/safe-regex.js +719 -0
  434. package/src/model/sample-settings.js +43 -0
  435. package/src/model/sample-source.js +47 -0
  436. package/src/model/saved-mapping.js +153 -0
  437. package/src/model/score-controllers.js +87 -0
  438. package/src/model/score-edit.js +399 -0
  439. package/src/model/score-instruments.js +300 -0
  440. package/src/model/score-library.js +407 -0
  441. package/src/model/score-markup.js +235 -0
  442. package/src/model/score-mix.js +248 -0
  443. package/src/model/score-patterns.js +276 -0
  444. package/src/model/score-selection.js +34 -0
  445. package/src/model/score-time.js +139 -0
  446. package/src/model/score-transforms.js +336 -0
  447. package/src/model/score-transport.js +192 -0
  448. package/src/model/selection.js +351 -0
  449. package/src/model/serial-controls.js +328 -0
  450. package/src/model/shares-pane.js +17 -0
  451. package/src/model/shell-pane.js +106 -0
  452. package/src/model/signature.js +1122 -0
  453. package/src/model/size-hints.js +106 -0
  454. package/src/model/size-ratio.js +12 -0
  455. package/src/model/skill-settings.js +23 -0
  456. package/src/model/snapping.js +466 -0
  457. package/src/model/split.js +375 -0
  458. package/src/model/spring-player.js +222 -0
  459. package/src/model/statecharts.js +1369 -0
  460. package/src/model/states-preset.js +208 -0
  461. package/src/model/static-route.js +100 -0
  462. package/src/model/step-words.js +45 -0
  463. package/src/model/subgraph.js +1042 -0
  464. package/src/model/switch.js +98 -0
  465. package/src/model/tabs-store.js +10 -0
  466. package/src/model/tensor-view.js +146 -0
  467. package/src/model/timer-clock.js +361 -0
  468. package/src/model/timers.js +422 -0
  469. package/src/model/timing.js +212 -0
  470. package/src/model/traffic-agent.js +111 -0
  471. package/src/model/traffic-store.js +20 -0
  472. package/src/model/traffic.js +665 -0
  473. package/src/model/transport.js +364 -0
  474. package/src/model/turns.js +86 -0
  475. package/src/model/types.js +425 -0
  476. package/src/model/value-path.js +138 -0
  477. package/src/model/versions.js +535 -0
  478. package/src/model/view-outputs.js +144 -0
  479. package/src/model/viewport-bookmarks.js +194 -0
  480. package/src/model/virtual-clock.js +85 -0
  481. package/src/model/vm-pane.js +258 -0
  482. package/src/model/wait-clock.js +715 -0
  483. package/src/model/wait-persist.js +248 -0
  484. package/src/model/waits.js +431 -0
  485. package/src/model/watch.js +80 -0
  486. package/src/model/webhook.js +496 -0
  487. package/src/model/when.js +48 -0
  488. package/src/model/widget-values.js +392 -0
  489. package/src/model/window-commands.js +278 -0
  490. package/src/model/windows.js +348 -0
  491. package/src/model/wire-inspect.js +343 -0
  492. package/src/model/wire-ops.js +324 -0
  493. package/src/model/wire-pipeline.js +378 -0
  494. package/src/model/wire-route.js +637 -0
  495. package/src/model/workspaces.js +122 -0
  496. package/src/model/ws-client.js +155 -0
  497. package/src/model/ws-demo.js +31 -0
  498. package/src/model/ws-frames.js +141 -0
  499. package/src/model/ws-hub.js +219 -0
  500. package/src/model/ws-served.js +13 -0
  501. package/src/model/xstate.js +374 -0
  502. package/src/narrative/narrative.js +1557 -0
  503. package/src/network/auth.js +224 -0
  504. package/src/network/csp-frame.js +197 -0
  505. package/src/network/declarative-shadow.js +27 -0
  506. package/src/network/frame-net-shim.js +962 -0
  507. package/src/network/hosts.js +157 -0
  508. package/src/network/policy.js +520 -0
  509. package/src/network/rtc-shim.js +418 -0
  510. package/src/network/secret-gate.js +78 -0
  511. package/src/network/secrets.js +261 -0
  512. package/src/network/sockets.js +287 -0
  513. package/src/network/store.js +186 -0
  514. package/src/network/streams.js +99 -0
  515. package/src/packages/asset-values.js +50 -0
  516. package/src/packages/assets.js +99 -0
  517. package/src/packages/deprecation.js +203 -0
  518. package/src/packages/fetch.js +152 -0
  519. package/src/packages/function-canvas.js +73 -0
  520. package/src/packages/module.js +120 -0
  521. package/src/packages/package.js +474 -0
  522. package/src/packages/published.js +27 -0
  523. package/src/packages/requires.js +83 -0
  524. package/src/packages/signing.js +145 -0
  525. package/src/packages/trust.js +107 -0
  526. package/src/panes/a2a.js +51 -0
  527. package/src/panes/acp.js +60 -0
  528. package/src/panes/actions.js +54 -0
  529. package/src/panes/agent.js +83 -0
  530. package/src/panes/audio.js +103 -0
  531. package/src/panes/automation.js +112 -0
  532. package/src/panes/calc.js +67 -0
  533. package/src/panes/catch.js +52 -0
  534. package/src/panes/codec.js +59 -0
  535. package/src/panes/colors.js +12 -0
  536. package/src/panes/companion.js +54 -0
  537. package/src/panes/decision.js +65 -0
  538. package/src/panes/device.js +56 -0
  539. package/src/panes/dom.js +37 -0
  540. package/src/panes/effects.js +118 -0
  541. package/src/panes/embed.js +30 -0
  542. package/src/panes/eval.js +186 -0
  543. package/src/panes/fields.js +299 -0
  544. package/src/panes/files.js +45 -0
  545. package/src/panes/gate.js +70 -0
  546. package/src/panes/geometry.js +64 -0
  547. package/src/panes/goals.js +75 -0
  548. package/src/panes/graph.js +66 -0
  549. package/src/panes/html.js +54 -0
  550. package/src/panes/http.js +82 -0
  551. package/src/panes/import.js +38 -0
  552. package/src/panes/input.js +124 -0
  553. package/src/panes/inputlog.js +66 -0
  554. package/src/panes/ledger.js +56 -0
  555. package/src/panes/machine.js +138 -0
  556. package/src/panes/mcp.js +85 -0
  557. package/src/panes/mcpapp.js +64 -0
  558. package/src/panes/media.js +38 -0
  559. package/src/panes/memory.js +46 -0
  560. package/src/panes/mesh-inspect.js +49 -0
  561. package/src/panes/note.js +38 -0
  562. package/src/panes/peer.js +44 -0
  563. package/src/panes/plot.js +196 -0
  564. package/src/panes/registry.js +475 -0
  565. package/src/panes/render.js +87 -0
  566. package/src/panes/respond.js +44 -0
  567. package/src/panes/router.js +84 -0
  568. package/src/panes/sample.js +75 -0
  569. package/src/panes/scene.js +55 -0
  570. package/src/panes/score.js +87 -0
  571. package/src/panes/secret.js +38 -0
  572. package/src/panes/select.js +67 -0
  573. package/src/panes/shader.js +166 -0
  574. package/src/panes/shared.js +33 -0
  575. package/src/panes/shares.js +43 -0
  576. package/src/panes/shell.js +47 -0
  577. package/src/panes/skill.js +44 -0
  578. package/src/panes/state.js +91 -0
  579. package/src/panes/statechart.js +63 -0
  580. package/src/panes/story.js +33 -0
  581. package/src/panes/subgraph.js +94 -0
  582. package/src/panes/tabs.js +52 -0
  583. package/src/panes/terminal.js +57 -0
  584. package/src/panes/text.js +36 -0
  585. package/src/panes/timer.js +55 -0
  586. package/src/panes/traffic.js +59 -0
  587. package/src/panes/verdict.js +62 -0
  588. package/src/panes/vm.js +46 -0
  589. package/src/panes/wait.js +61 -0
  590. package/src/panes/watch.js +57 -0
  591. package/src/panes/webhook.js +67 -0
  592. package/src/panes/ws-client.js +67 -0
  593. package/src/persist.js +281 -0
  594. package/src/plot/tex.js +19 -0
  595. package/src/plot/vendor.js +59 -0
  596. package/src/plot/view-vendor.js +5 -0
  597. package/src/privacy/levels.js +108 -0
  598. package/src/protocol/devtools.js +116 -0
  599. package/src/protocol/inspector.js +368 -0
  600. package/src/render/time.js +381 -0
  601. package/src/rooms/mesh-metrics.js +162 -0
  602. package/src/run/companion.js +355 -0
  603. package/src/run/describe.js +114 -0
  604. package/src/run/local-model.js +150 -0
  605. package/src/run/monitor.js +208 -0
  606. package/src/run/publish.js +360 -0
  607. package/src/run/respond-outcome.js +12 -0
  608. package/src/run/run.js +820 -0
  609. package/src/run/runner-pairing.js +243 -0
  610. package/src/run/values.js +122 -0
  611. package/src/runtime/compile.js +122 -0
  612. package/src/runtime/console-tag.js +64 -0
  613. package/src/runtime/frame-signals.js +126 -0
  614. package/src/runtime/iteration-push.js +19 -0
  615. package/src/runtime/keys.js +474 -0
  616. package/src/runtime/midi-input.js +170 -0
  617. package/src/runtime/person-waits.js +140 -0
  618. package/src/runtime/resource-timing.js +56 -0
  619. package/src/runtime/runtime.js +2150 -0
  620. package/src/runtime/sandbox-modules.js +163 -0
  621. package/src/runtime/spring.js +246 -0
  622. package/src/runtime/strict.js +215 -0
  623. package/src/runtime/transfer.js +75 -0
  624. package/src/runtime/tween.js +158 -0
  625. package/src/runtime/wasm-fuel.js +596 -0
  626. package/src/runtime/worker/00-prelude.js +88 -0
  627. package/src/runtime/worker/10-helpers.js +295 -0
  628. package/src/runtime/worker/20-io.js +645 -0
  629. package/src/runtime/worker/30-previews.js +210 -0
  630. package/src/runtime/worker/40-profile-lineage.js +278 -0
  631. package/src/runtime/worker/50-own-worker.js +233 -0
  632. package/src/runtime/worker/60-timers.js +172 -0
  633. package/src/runtime/worker/70-state-keyed.js +193 -0
  634. package/src/runtime/worker/80-each-compile-generators.js +619 -0
  635. package/src/runtime/worker/90-events-operators.js +655 -0
  636. package/src/runtime/worker/95-agents-batches.js +1820 -0
  637. package/src/runtime/worker/96-plot.js +47 -0
  638. package/src/runtime/worker/97-calc.js +28 -0
  639. package/src/runtime/worker/98-geometry.js +24 -0
  640. package/src/runtime/worker/99-graph.js +30 -0
  641. package/src/runtime/worker/99-shell.js +30 -0
  642. package/src/safety/config.js +57 -0
  643. package/src/safety/engine.js +324 -0
  644. package/src/scene/pixi-scene.js +806 -0
  645. package/src/scene/scene-assets.js +241 -0
  646. package/src/scene/scene-edit.js +319 -0
  647. package/src/secret/settings.js +41 -0
  648. package/src/security/multipart.js +257 -0
  649. package/src/security/redact.js +261 -0
  650. package/src/serial/broker.js +473 -0
  651. package/src/serial/config.js +185 -0
  652. package/src/serial/framers.js +389 -0
  653. package/src/serial/packets.js +64 -0
  654. package/src/shader/audio-texture.js +87 -0
  655. package/src/shader/channels.js +496 -0
  656. package/src/shader/common.js +90 -0
  657. package/src/shader/model.js +867 -0
  658. package/src/shader/passes.js +150 -0
  659. package/src/shader/shadertoy.js +198 -0
  660. package/src/shell/hub.js +287 -0
  661. package/src/sim/checkpoints.js +850 -0
  662. package/src/sim/compile.js +37 -0
  663. package/src/sim/fixed.js +377 -0
  664. package/src/sim/headless.js +205 -0
  665. package/src/sim/physics.js +399 -0
  666. package/src/smf-helper/vendor.js +2 -0
  667. package/src/sources/config.js +435 -0
  668. package/src/storage.js +153 -0
  669. package/src/table/table-geo.js +2344 -0
  670. package/src/table/table-lineage.js +808 -0
  671. package/src/table/table-quality.js +355 -0
  672. package/src/table/table-schema.js +392 -0
  673. package/src/table/table-sql.js +1650 -0
  674. package/src/table/table-stats.js +480 -0
  675. package/src/table/table.js +2102 -0
  676. package/src/tensor/tensor.js +1153 -0
  677. package/src/terminal/hub.js +715 -0
  678. package/src/terminal/screen.js +516 -0
  679. package/src/tests/capture.js +88 -0
  680. package/src/tests/compare.js +480 -0
  681. package/src/tests/dataset.js +170 -0
  682. package/src/tests/evaluate.js +286 -0
  683. package/src/tests/from-runs.js +99 -0
  684. package/src/tests/judge.js +134 -0
  685. package/src/tests/matchers.js +263 -0
  686. package/src/tests/matrix-spec.js +87 -0
  687. package/src/tests/matrix.js +397 -0
  688. package/src/tests/metrics.js +369 -0
  689. package/src/tests/no-value.js +42 -0
  690. package/src/tests/pane-check.js +45 -0
  691. package/src/tests/report.js +124 -0
  692. package/src/tests/reporters.js +140 -0
  693. package/src/tests/run.js +155 -0
  694. package/src/tilemap/tilemap.js +1122 -0
  695. package/src/units/units.js +3 -0
  696. package/src/util/bytes-text.js +21 -0
  697. package/src/util/num.js +10 -0
  698. package/src/util/regexp.js +2 -0
  699. package/src/util/text.js +38 -0
  700. package/src/verdict/engine.js +154 -0
  701. package/src/vm/guest-wsh.js +108 -0
  702. package/src/vm/hub.js +457 -0
  703. package/src/vm/image-files.js +4 -0
  704. package/src/vm/image.js +33 -0
  705. package/src/vm/image.lock.json +13 -0
  706. package/src/vm/link.js +266 -0
  707. package/src/vm/mount.js +212 -0
  708. package/src/vm/net.js +85 -0
  709. package/src/vm/pipe-ws.js +187 -0
  710. package/src/vm/v86-loader.js +11 -0
  711. package/src/webmcp/args.js +212 -0
  712. package/src/webmcp/hidden.js +218 -0
  713. package/src/webmcp/text.js +250 -0
  714. package/src/webmcp/tools/bookmark-tools.js +106 -0
  715. package/src/webmcp/tools/breakpoint-tools.js +48 -0
  716. package/src/webmcp/tools/canvases.js +208 -0
  717. package/src/webmcp/tools/context-tools.js +84 -0
  718. package/src/webmcp/tools/core.js +170 -0
  719. package/src/webmcp/tools/devices.js +41 -0
  720. package/src/webmcp/tools/edit.js +357 -0
  721. package/src/webmcp/tools/event-tools.js +145 -0
  722. package/src/webmcp/tools/image-tools.js +173 -0
  723. package/src/webmcp/tools/ink-tools.js +247 -0
  724. package/src/webmcp/tools/input-log-tools.js +163 -0
  725. package/src/webmcp/tools/live.js +166 -0
  726. package/src/webmcp/tools/machine-tools.js +74 -0
  727. package/src/webmcp/tools/media.js +161 -0
  728. package/src/webmcp/tools/midi-tools.js +32 -0
  729. package/src/webmcp/tools/preset-tools.js +184 -0
  730. package/src/webmcp/tools/quick-add-tools.js +95 -0
  731. package/src/webmcp/tools/reshape.js +152 -0
  732. package/src/webmcp/tools/run-tools.js +309 -0
  733. package/src/webmcp/tools/runs.js +101 -0
  734. package/src/webmcp/tools/scaffold-tools.js +161 -0
  735. package/src/webmcp/tools/serial-tools.js +36 -0
  736. package/src/webmcp/tools/shared.js +338 -0
  737. package/src/webmcp/tools/subgraphs.js +360 -0
  738. package/src/webmcp/tools/tests.js +170 -0
  739. package/src/webmcp/tools/traffic-tools.js +70 -0
  740. package/src/webmcp/tools/transport-tools.js +65 -0
  741. package/src/webmcp/tools/version-tools.js +126 -0
  742. package/src/webmcp/tools/versions.js +11 -0
  743. package/src/webmcp/tools/wire-tools.js +90 -0
  744. package/src/webmcp/tools/workspace-tools.js +93 -0
  745. package/src/webmcp/tools.js +1323 -0
  746. package/src/wsh/connect.js +347 -0
  747. package/src/wsh/demo-host.js +361 -0
  748. package/src/wsh/e2e.js +27 -0
  749. package/src/wsh/keys.js +154 -0
  750. package/src/wsh/known-hosts.js +39 -0
  751. package/src/wsh/private-key.js +95 -0
  752. package/src/wsh/reverse.js +34 -0
  753. package/src/wsh/settings.js +118 -0
  754. package/src/wsh/transfer.js +62 -0
  755. package/src/wsh/vendor.js +5 -0
  756. package/src/x402/challenge.js +171 -0
  757. package/src/x402/demo-server.js +127 -0
  758. package/src/x402/pay.js +125 -0
  759. package/src/x402/retry.js +95 -0
  760. package/src/x402/store.js +76 -0
@@ -0,0 +1,2102 @@
1
+ // Local table transformations: the core of the `table` helper pane code
2
+ // gets (the Worker loads this file as the module "mallory:table/core",
3
+ // src/runtime/sources.js; the page, the headless runner and the tests import it
4
+ // too). Self-contained and pure: no imports, no DOM, no network, no storage.
5
+ //
6
+ // REPRESENTATION (one decision, shared by every table feature)
7
+ //
8
+ // A table is an array of plain row objects, `[{ id: 1, name: "a" }, …]`:
9
+ // what an eval pane returns, what the table and plot views and the CSV/TSV
10
+ // export already take, and what survives a structured clone or JSON.
11
+ //
12
+ // - A cell is `undefined` (the key is absent: "no such field in this row"),
13
+ // `null` ("known to be empty") or any value, `""` included. The three stay
14
+ // apart through every operation, CSV included (see parseCsv/formatCsv).
15
+ // - A column's order is first appearance across the rows. A table with no rows
16
+ // has no columns, so an operation takes a declared `schema` when columns
17
+ // must exist without rows.
18
+ // - A schema (`inferSchema`, or declared) is `{ columns: [{ name, type,
19
+ // nullable, missing }], rows }`. Types are "string", "number", "boolean",
20
+ // "date"/"datetime" (an ISO 8601 string; declared, or inferred with `dates: true`), "json" (objects/arrays),
21
+ // "null" (only null seen), "mixed" (several of those) and "any" (declared,
22
+ // unchecked). Text is never silently read as a number or a date: that is
23
+ // `convert`, which reports each cell it can't read.
24
+ //
25
+ // RESULT (what every operation returns, so panes, tests and later features
26
+ // can rely on one shape)
27
+ //
28
+ // { rows, schema, errors, notes, rejected?, origin?, …extra tables }
29
+ // - rows: the output table. schema: its schema.
30
+ // - errors: row-specific problems, `{ row, column?, value?, code, message,
31
+ // op }`; `row` is the position in that operation's input (`side` says
32
+ // "left"/"right" for a join). Nothing is dropped without an entry here.
33
+ // - notes: table-wide observations as text (a mixed-type join key, a
34
+ // duplicated key, a CSV header that was renamed).
35
+ // - rejected: with `onError: "route"`, the input rows that failed, unchanged,
36
+ // taken out of `rows` (a row that fails is never silently lost).
37
+ // - origin: with `trace: true`, one entry per output row, `{ <input>: [row
38
+ // positions] }` (input "rows", "left"/"right" for a join, a table's name
39
+ // for SQL). At most `maxLinks` positions (default 64) are kept per input;
40
+ // an entry that had more says so under the reserved key `$`:
41
+ // `{ rows: [...], $: { truncated: { rows: 12 } } }`, and `$: { unknown: true }`
42
+ // marks a row whose ancestry code declined to say (see table-lineage.js).
43
+ // - exclusions: with `trace: true`, why input rows are not in `rows`:
44
+ // `[{ input, kind, reason, code?, rule?, rows: [positions], count }]`
45
+ // (kind "filtered", "rejected", "review", "dropped", "unmatched").
46
+ // - Other named tables (`excluded`, `matched`, `leftOnly`, `rightOnly`): any
47
+ // further array of rows on the result is a table output; a pane publishes
48
+ // each as a named output.
49
+ //
50
+ // POLICIES are options named for the thing they decide, never implicit:
51
+ // `onError` ("null" default: keep the row, cell null, error reported; "keep":
52
+ // keep the original cell; "route": move the row to `rejected`; "fail": throw),
53
+ // `locale`/`nulls`/`numeric` for sorting, `nulls`/`types`/`duplicates` for join
54
+ // keys, `empty` for CSV, `nullKeys` for grouping.
55
+ //
56
+ // BUDGETS: `limits: { maxRows, maxCells, maxBytes, maxMs }` and `signal` (an
57
+ // AbortSignal) on every operation; exceeding one throws a TableError (code
58
+ // "limit" or "aborted") that says which and how to raise it.
59
+ //
60
+ // CANCELLATION (the one primitive; everything that must be able to
61
+ // stop or yield builds on it). A synchronous operation is a loop that nothing
62
+ // else can interrupt, so an AbortSignal can't fire while it runs and only the
63
+ // pane timeout (which restarts the Worker) can stop it. The async variant
64
+ // yields to the event loop between slices of work, so an abort (a newer run of
65
+ // the pane, the pane deleted: the pane-scope `signal`) lands within a slice.
66
+ //
67
+ // await table.async.filter(rows, { where: "x > 1", signal }) every operation: table.async.<name>
68
+ // await table.runAsync("filter", rows, options) by name
69
+ // await table.async.sql(query, tables, options) plugins add theirs (sql, profile, …)
70
+ // a signal that aborts stops the operation: it rejects with TableError code "aborted"
71
+ //
72
+ // options (besides the shared ones): sliceMs (default 10: how long a slice
73
+ // runs before it yields). `limits.maxMs` counts wall time, yielded time too.
74
+ // A sync call (table.filter(...)) never yields: it is the same code, driven to
75
+ // the end, and gives the same result as the async call.
76
+ //
77
+ // For a feature author (an operation, a plugin): write the operation as a
78
+ // generator, `defineOp("name", function* (input, options, ctx) { … })`, and put
79
+ // `if (ctx.tick()) yield;` first in each loop that can be long. ctx.tick()
80
+ // checks the signal and the budgets (every 128 calls in an async run, 1024 in a
81
+ // sync one) and is true only in an async run whose slice is used up; so the
82
+ // `yield` is where an async run pauses and a sync run never stops. A helper
83
+ // that loops is a generator too, called as `yield* helper(…)`. `sortYielding`
84
+ // is the yielding sort. A plain (non-generator) operation still works in both
85
+ // modes; it just can't be interrupted. A function that isn't a defineOp
86
+ // operation gets the same two entry points from `callable(name, fn)`.
87
+ //
88
+ // EXTENDING (src/table/README is docs/guide/data.md's "Table transformations"):
89
+ // - an operation: `defineOp(name, fn, { inputs })`; fn(input, options, ctx)
90
+ // returns rows or a partial Result. It shows up as `table[name]`.
91
+ // - an aggregate (group, pivot, SQL): `aggregates.set(name, { init, step, done })`.
92
+ // - a scalar function (SQL and expression strings): `functions.set(name, fn)`.
93
+ // - a plugin module (the SQL engine is one): `export function install(table)`.
94
+
95
+ // ── errors, budgets ─────────────────────────────────────────────────────────
96
+
97
+ export class TableError extends Error {
98
+ constructor(code, message, detail) {
99
+ super(message);
100
+ this.name = "TableError";
101
+ this.code = code;
102
+ if (detail !== undefined) this.detail = detail;
103
+ }
104
+ }
105
+
106
+ export const DEFAULT_LIMITS = Object.freeze({ maxRows: 1_000_000, maxCells: 10_000_000, maxBytes: 64 * 1024 * 1024, maxMs: 0 });
107
+ /** How long an async run works before it yields to the event loop (`sliceMs`). */
108
+ export const DEFAULT_SLICE_MS = 10;
109
+
110
+ const isRow = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
111
+ const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
112
+
113
+ // ── lineage bounds ───────────────────────────────────────────────────
114
+
115
+ /** The reserved key of an origin entry that carries metadata (`truncated`, `unknown`) instead of positions. */
116
+ export const LINEAGE_META = "$";
117
+ export const DEFAULT_MAX_LINKS = 64;
118
+ export const MAX_LINKS = 10_000;
119
+ const MAX_EXCLUDED = 1000; // positions listed per exclusion reason
120
+ const MAX_REASONS = 50; // distinct exclusion reasons listed
121
+
122
+ function linkLimit(value) {
123
+ if (value === undefined) return DEFAULT_MAX_LINKS;
124
+ if (!Number.isInteger(value) || value < 1 || value > MAX_LINKS) throw new TableError("bad-option", `maxLinks should be a whole number from 1 to ${MAX_LINKS} (ancestors kept per output row), not ${JSON.stringify(value)}.`);
125
+ return value;
126
+ }
127
+
128
+ /** An origin entry with at most `max` positions per input; what was left out is counted under `$.truncated`. Entries within the cap are returned as they are. */
129
+ export function capOrigin(entry, max = DEFAULT_MAX_LINKS) {
130
+ if (!entry || typeof entry !== "object") return entry;
131
+ let out = entry;
132
+ for (const key of Object.keys(entry)) {
133
+ const list = entry[key];
134
+ if (key === LINEAGE_META || !Array.isArray(list) || list.length <= max) continue;
135
+ if (out === entry) out = { ...entry, [LINEAGE_META]: { ...entry[LINEAGE_META], truncated: { ...entry[LINEAGE_META]?.truncated } } };
136
+ out[key] = list.slice(0, max);
137
+ out[LINEAGE_META].truncated[key] = (out[LINEAGE_META].truncated[key] ?? 0) + list.length - max;
138
+ }
139
+ return out;
140
+ }
141
+
142
+ /** One origin entry for several: the positions of each input without repeats, in first-seen order, capped. `unknown` if any part was. */
143
+ export function mergeOrigin(entries, max = DEFAULT_MAX_LINKS) {
144
+ const sets = new Map();
145
+ const truncated = {};
146
+ let unknown = false;
147
+ for (const e of entries) {
148
+ if (!e) continue;
149
+ for (const key of Object.keys(e)) {
150
+ if (key === LINEAGE_META) {
151
+ if (e[key].unknown) unknown = true;
152
+ for (const [k, n] of Object.entries(e[key].truncated ?? {})) truncated[k] = (truncated[k] ?? 0) + n;
153
+ } else {
154
+ let set = sets.get(key);
155
+ if (!set) sets.set(key, (set = new Set()));
156
+ for (const p of e[key]) set.add(p);
157
+ }
158
+ }
159
+ }
160
+ const out = {};
161
+ for (const [key, set] of sets) out[key] = [...set];
162
+ if (unknown || Object.keys(truncated).length) out[LINEAGE_META] = { ...(unknown ? { unknown: true } : {}), ...(Object.keys(truncated).length ? { truncated } : {}) };
163
+ return capOrigin(out, max);
164
+ }
165
+
166
+ /** The run context of one operation: budgets, abort, error and note collection, tracing. */
167
+ function makeContext(op, options = {}, yielding = false) {
168
+ const limits = { ...DEFAULT_LIMITS, ...(options.limits ?? {}) };
169
+ const started = Date.now();
170
+ const errors = [];
171
+ const notes = [];
172
+ const sliceMs = Number.isFinite(options.sliceMs) && options.sliceMs >= 0 ? options.sliceMs : DEFAULT_SLICE_MS;
173
+ const mask = yielding ? 127 : 1023;
174
+ let sliceStart = started;
175
+ let ticks = 0;
176
+ const ctx = {
177
+ op,
178
+ options,
179
+ limits,
180
+ errors,
181
+ notes,
182
+ trace: Boolean(options.trace),
183
+ maxLinks: linkLimit(options.maxLinks),
184
+ excluded: new Map(),
185
+ policy: options.onError ?? "null",
186
+ rejected: new Set(),
187
+ /** True in an async run (table.async.*): `tick()` can be true, and the driver yields to the event loop at each `yield`. */
188
+ yielding,
189
+ /** Throw if the signal aborted (TableError "aborted") or the time budget is used up. */
190
+ check() {
191
+ if (options.signal?.aborted) throw new TableError("aborted", `${op}: stopped (the run was cancelled).`);
192
+ if (limits.maxMs && Date.now() - started > limits.maxMs) throw new TableError("limit", `${op}: stopped after ${limits.maxMs} ms (limits.maxMs).`);
193
+ },
194
+ /**
195
+ * Call in loops, as `if (ctx.tick()) yield;` in a generator (anywhere else, ignore the result).
196
+ * Every 128 (async) or 1024 (sync) calls: checks the signal and the time budget; true when
197
+ * this is an async run and its slice (`sliceMs`) is used up.
198
+ */
199
+ tick() {
200
+ if ((++ticks & mask) !== 0) return false;
201
+ ctx.check();
202
+ return yielding && Date.now() - sliceStart >= sliceMs;
203
+ },
204
+ /** The driver calls this when a run resumes after a yield: a new slice starts. */
205
+ resumed() {
206
+ sliceStart = Date.now();
207
+ },
208
+ note(text) {
209
+ if (!notes.includes(text)) notes.push(text);
210
+ },
211
+ /** Record a row-specific problem. Throws under onError "fail". */
212
+ error(entry) {
213
+ const e = { op, ...entry };
214
+ if (ctx.policy === "fail") throw new TableError(e.code ?? "error", `${op}: row ${e.row}${e.column !== undefined ? `, column "${e.column}"` : ""}: ${e.message}`, e);
215
+ errors.push(e);
216
+ if (ctx.policy === "route" && e.row !== undefined) ctx.rejected.add(`${e.side ?? ""}:${e.row}`);
217
+ return e;
218
+ },
219
+ /** With `trace`: input row `position` is not in the result, and why. Grouped by reason and bounded, so it never grows with the table. */
220
+ exclude(why, position) {
221
+ if (!ctx.trace) return;
222
+ const input = why.input ?? "rows";
223
+ let key = [input, why.kind, why.code ?? "", why.rule ?? "", why.reason].join("\u0001");
224
+ // A reason that names the row (an error message with a value in it) would make a group per row: past MAX_REASONS groups the rest share one.
225
+ if (!ctx.excluded.has(key) && ctx.excluded.size >= MAX_REASONS) {
226
+ why = { input, kind: why.kind, reason: "other reasons (more distinct reasons than are listed)" };
227
+ key = [input, why.kind, "", "", why.reason].join("\u0001");
228
+ }
229
+ let g = ctx.excluded.get(key);
230
+ if (!g) ctx.excluded.set(key, (g = { input, kind: why.kind, reason: why.reason, ...(why.code ? { code: why.code } : {}), ...(why.rule ? { rule: why.rule } : {}), rows: [], count: 0 }));
231
+ g.count++;
232
+ if (g.rows.length < MAX_EXCLUDED) g.rows.push(position);
233
+ },
234
+ checkRows(count, what = "rows") {
235
+ if (count > limits.maxRows) throw new TableError("limit", `${op}: ${what} has ${count} rows, over limits.maxRows (${limits.maxRows}). Raise limits.maxRows, or filter first.`);
236
+ },
237
+ checkCells(rows, columns, what = "the result") {
238
+ if (rows * columns > limits.maxCells) throw new TableError("limit", `${op}: ${what} would hold ${rows * columns} cells (${rows} rows x ${columns} columns), over limits.maxCells (${limits.maxCells}).`);
239
+ },
240
+ };
241
+ return ctx;
242
+ }
243
+
244
+ /** A rough size of rows in bytes (JSON length of a sample, scaled): for the maxBytes budget. */
245
+ export function estimateBytes(rows, sample = 50) {
246
+ if (!rows.length) return 0;
247
+ const step = Math.max(1, Math.floor(rows.length / sample));
248
+ let total = 0;
249
+ let n = 0;
250
+ for (let i = 0; i < rows.length && n < sample; i += step, n++) {
251
+ try {
252
+ total += JSON.stringify(rows[i])?.length ?? 0;
253
+ } catch {
254
+ total += 64;
255
+ }
256
+ }
257
+ return Math.round((total / n) * rows.length);
258
+ }
259
+
260
+ export function checkInput(ctx, rows, what = "the input") {
261
+ if (!Array.isArray(rows)) throw new TableError("bad-input", `${ctx.op}: ${what} isn't a table (an array of row objects).`);
262
+ ctx.checkRows(rows.length, what);
263
+ if (rows.length && ctx.limits.maxBytes && estimateBytes(rows) > ctx.limits.maxBytes) throw new TableError("limit", `${ctx.op}: ${what} is about ${estimateBytes(rows)} bytes, over limits.maxBytes (${ctx.limits.maxBytes}).`);
264
+ for (let i = 0; i < rows.length; i++) {
265
+ ctx.tick();
266
+ if (!isRow(rows[i])) throw new TableError("bad-input", `${ctx.op}: row ${i} of ${what} isn't an object (${Array.isArray(rows[i]) ? "an array" : rows[i] === null ? "null" : typeof rows[i]}). Rows are plain objects; use table.fromArrays(columns, rows) for arrays.`);
267
+ }
268
+ }
269
+
270
+ // ── values ──────────────────────────────────────────────────────────────────
271
+
272
+ /** "null" (null and undefined), "number", "string", "boolean", "json" (objects and arrays), or another typeof. */
273
+ export function typeOfCell(v) {
274
+ if (v === null || v === undefined) return "null";
275
+ const t = typeof v;
276
+ return t === "object" ? "json" : t;
277
+ }
278
+
279
+ const TYPE_RANK = { number: 0, bigint: 0, string: 1, boolean: 2, json: 3 };
280
+
281
+ /** Does this look like a date-time (ISO 8601 date, or date and time with an offset)? */
282
+ const ISO = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
283
+
284
+ /** Read an ISO 8601 date or date-time: `{ ms, offset, time }` (offset: the text names a UTC offset or Z; time: it has a time of day), or null. UTC when it has no offset. */
285
+ function readIso(text) {
286
+ const m = ISO.exec(String(text).trim());
287
+ if (!m) return null;
288
+ const [, y, mo, d, h, mi = "0", s = "0", frac = "0", zone] = m;
289
+ const ms = Date.UTC(+y, +mo - 1, +d, +(h ?? 0), +mi, +s, Math.round(+`0.${frac}` * 1000));
290
+ const probe = new Date(ms);
291
+ if (probe.getUTCFullYear() !== +y || probe.getUTCMonth() !== +mo - 1 || probe.getUTCDate() !== +d) return null; // 2024-02-31
292
+ if (+(h ?? 0) > 23 || +mi > 59 || +s > 59) return null;
293
+ const time = h !== undefined;
294
+ if (zone && zone !== "Z") {
295
+ const sign = zone[0] === "-" ? -1 : 1;
296
+ const digits = zone.slice(1).replace(":", "");
297
+ return { ms: ms - sign * (+digits.slice(0, 2) * 60 + +digits.slice(2)) * 60000, offset: true, time };
298
+ }
299
+ return { ms, offset: Boolean(zone), time };
300
+ }
301
+
302
+ /** Parse an ISO 8601 date or date-time to epoch ms (UTC when it has no offset), or NaN. */
303
+ export function parseIso(text) {
304
+ return readIso(text)?.ms ?? NaN;
305
+ }
306
+
307
+ /**
308
+ * Does this text read as an ISO 8601 date ("date": 2024-03-09) or date-time
309
+ * ("datetime": it has a time)? Null otherwise. The one rule `inferSchema`'s
310
+ * `dates` option, `profile` and the schema snapshot share, and the one
311
+ * `convert` and `validate` read dates by, so they agree on what a date is.
312
+ */
313
+ export function isoKind(text) {
314
+ if (typeof text !== "string" || Number.isNaN(parseIso(text))) return null;
315
+ return /^\s*\d{4}-\d{2}-\d{2}\s*$/.test(text) ? "date" : "datetime";
316
+ }
317
+
318
+ // ── dates that aren't ISO 8601 ─────────────────────────────────
319
+ //
320
+ // One rule for every place that has to decide what a date column is: `convert`'s
321
+ // `from`, the schema snapshot, `inferSchema`'s `dateHints` and `profile`. Text and
322
+ // numbers are never silently typed as dates: `dateHint` only SAYS a column looks
323
+ // like one (and how to read it), and `convert` does the reading.
324
+ //
325
+ // from: "iso" (default) 2024-03-09, 2024-03-09T14:30:00Z
326
+ // "epoch-s" | "epoch-ms" a number of seconds / milliseconds since 1970
327
+ // "mdy" | "dmy" | "ymd" numeric parts with / . - (03/09/2024, 9.3.2024, 2024/03/09),
328
+ // a four-digit year, an optional time (14:30, 2:30 pm)
329
+ // "text" a month name: 9 Mar 2024, March 9, 2024 (any of mdy/dmy/ymd accept these too)
330
+ // timeZone: an IANA zone (America/Los_Angeles) the text without an offset is read in (default UTC)
331
+
332
+ /** How many values of a column a date hint reads (callers that sample pass at most this many). */
333
+ export const DATE_HINT_SAMPLE = 200;
334
+ export const DATE_FROM = ["iso", "epoch-s", "epoch-ms", "mdy", "dmy", "ymd", "text"];
335
+ const MONTH_INDEX = Object.fromEntries(["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"].map((m, i) => [m, i]));
336
+ const MONTH_WORD = "(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\\.?";
337
+ const TIME_TAIL = "(?:[ T,]+(\\d{1,2}):(\\d{2})(?::(\\d{2}))?\\s*([ap]\\.?m\\.?)?)?";
338
+ const LOOSE_NUMERIC = new RegExp(`^(\\d{1,4})([/.-])(\\d{1,2})\\2(\\d{1,4})${TIME_TAIL}$`, "i");
339
+ const LOOSE_DMY_TEXT = new RegExp(`^(\\d{1,2})(?:st|nd|rd|th)?[ -]${MONTH_WORD}[ ,-]+(\\d{4})${TIME_TAIL}$`, "i");
340
+ const LOOSE_MDY_TEXT = new RegExp(`^${MONTH_WORD}[ -](\\d{1,2})(?:st|nd|rd|th)?,?[ -]+(\\d{4})${TIME_TAIL}$`, "i");
341
+
342
+ /** Read date text that isn't ISO: `{ ms, time, named }` or null. `order`: "mdy", "dmy" or "ymd" for the numeric forms; month-name forms need none. */
343
+ function readLoose(text, order) {
344
+ const t = String(text).trim();
345
+ let y;
346
+ let mo;
347
+ let d;
348
+ let tail;
349
+ let named = false;
350
+ let m = LOOSE_NUMERIC.exec(t);
351
+ if (m) {
352
+ const [, a, , b, c] = m;
353
+ tail = m.slice(5);
354
+ const parts = order === "mdy" ? { mo: a, d: b, y: c } : order === "dmy" ? { mo: b, d: a, y: c } : order === "ymd" ? { y: a, mo: b, d: c } : null;
355
+ if (!parts) return null;
356
+ if (parts.y.length !== 4 || parts.d.length > 2 || parts.mo.length > 2) return null; // a two-digit year is ambiguous: never guessed
357
+ ({ y, mo, d } = parts);
358
+ mo = +mo - 1;
359
+ } else if ((m = LOOSE_DMY_TEXT.exec(t))) {
360
+ named = true;
361
+ [, d, , y] = m;
362
+ mo = MONTH_INDEX[m[2].toLowerCase()];
363
+ tail = m.slice(4);
364
+ } else if ((m = LOOSE_MDY_TEXT.exec(t))) {
365
+ named = true;
366
+ [, , d, y] = m;
367
+ mo = MONTH_INDEX[m[1].toLowerCase()];
368
+ tail = m.slice(4);
369
+ } else return null;
370
+ const [h, mi = "0", s = "0", ampm] = tail;
371
+ const time = h !== undefined;
372
+ let hour = +(h ?? 0);
373
+ if (ampm) {
374
+ if (hour < 1 || hour > 12) return null;
375
+ hour = (hour % 12) + (/^p/i.test(ampm) ? 12 : 0);
376
+ }
377
+ if (hour > 23 || +mi > 59 || +s > 59) return null;
378
+ const ms = Date.UTC(+y, mo, +d, hour, +mi, +s);
379
+ const probe = new Date(ms);
380
+ if (probe.getUTCFullYear() !== +y || probe.getUTCMonth() !== mo || probe.getUTCDate() !== +d) return null;
381
+ return { ms, time, named };
382
+ }
383
+
384
+ /** Offset (ms) of IANA zone `zone` from UTC at instant `utcMs`; throws a RangeError for an unknown zone. */
385
+ function zoneOffset(zone, utcMs) {
386
+ const f = new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });
387
+ const p = Object.fromEntries(f.formatToParts(new Date(utcMs)).map((x) => [x.type, x.value]));
388
+ return Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +p.second) - Math.floor(utcMs / 1000) * 1000;
389
+ }
390
+
391
+ /** The instant whose wall-clock time in `zone` is `wallMs` (read as if UTC). Around a clock change the usual single-correction rule applies. */
392
+ export function wallToUtc(wallMs, zone) {
393
+ const first = wallMs - zoneOffset(zone, wallMs);
394
+ return wallMs - zoneOffset(zone, first);
395
+ }
396
+
397
+ /** Is `zone` a time zone name Intl knows? */
398
+ export function knownZone(zone) {
399
+ try {
400
+ new Intl.DateTimeFormat("en-US", { timeZone: zone });
401
+ return true;
402
+ } catch {
403
+ return false;
404
+ }
405
+ }
406
+
407
+ const EPOCH_S = [946684800, 4102444800]; // 2000-01-01 to 2100-01-01
408
+ const NAMED_COLUMN = /(date|time|stamp|created|updated|modified|(^|[_ -])(at|on|ts|when)($|[_ -])|(At|On)$)/;
409
+
410
+ /**
411
+ * Does a column's sample of values look like dates that aren't typed as dates? `values`: the non-null
412
+ * cells (a bounded sample, from anywhere in the table). Returns null, or
413
+ * `{ type: "date" | "datetime", from, confidence, of, ambiguous? }`: `from` is what `convert` should read
414
+ * the column with ("epoch-s", "epoch-ms", "mdy", "dmy", "ymd" or "text"); when day-first and month-first
415
+ * both fit every value there is no `from`, only `ambiguous: ["mdy", "dmy"]` (say which, never guess).
416
+ * Every value has to fit. Numbers are hints only: ten-digit ids also fall in the epoch-s range, so
417
+ * confidence is "high" for text, "medium" for numbers when `name` looks like a date column, else "low".
418
+ * Values that are all ISO 8601 return null (they are already typed by `inferSchema({ dates: true })`).
419
+ */
420
+ export function dateHint(values, { name = "" } = {}) {
421
+ const n = values.length;
422
+ if (!n) return null;
423
+ if (values.every((v) => typeof v === "number" || typeof v === "bigint")) {
424
+ const nums = values.map(Number);
425
+ if (!nums.every(Number.isFinite)) return null;
426
+ const named = NAMED_COLUMN.test(name);
427
+ const confidence = named ? "medium" : "low";
428
+ if (nums.every((x) => x >= EPOCH_S[0] && x < EPOCH_S[1])) return { type: "datetime", from: "epoch-s", confidence, of: n };
429
+ if (nums.every((x) => Number.isInteger(x) && x >= EPOCH_S[0] * 1000 && x < EPOCH_S[1] * 1000)) return { type: "datetime", from: "epoch-ms", confidence, of: n };
430
+ return null;
431
+ }
432
+ if (!values.every((v) => typeof v === "string")) return null;
433
+ if (values.every((v) => isoKind(v))) return null;
434
+ const orders = ["mdy", "dmy", "ymd"];
435
+ const fits = Object.fromEntries(orders.map((o) => [o, true]));
436
+ let time = false;
437
+ let allNamed = true;
438
+ for (const v of values) {
439
+ const iso = readIso(v);
440
+ if (iso) {
441
+ time ||= iso.time;
442
+ continue; // a mixed column: ISO next to the other spelling
443
+ }
444
+ let any = false;
445
+ let named = false;
446
+ for (const o of orders) {
447
+ const r = readLoose(v, o);
448
+ if (r) {
449
+ any = true;
450
+ named ||= r.named;
451
+ time ||= r.time;
452
+ } else fits[o] = false;
453
+ }
454
+ if (!any) return null;
455
+ if (!named) allNamed = false;
456
+ }
457
+ const type = time ? "datetime" : "date";
458
+ if (allNamed && orders.some((o) => fits[o])) return { type, from: "text", confidence: "high", of: n };
459
+ const ok = orders.filter((o) => fits[o]);
460
+ if (ok.length === 1) return { type, from: ok[0], confidence: "high", of: n };
461
+ if (ok.length > 1) return { type, ambiguous: ok, confidence: "high", of: n };
462
+ return null;
463
+ }
464
+
465
+ /** A key for equality and grouping that keeps types apart: 1 and "1" differ, null and undefined are the same "z". */
466
+ export function keyPart(v, { loose = false, ignoreCase = false } = {}) {
467
+ if (v === null || v === undefined) return "z";
468
+ if (loose) {
469
+ const s = typeof v === "object" ? JSON.stringify(v) : String(v).trim();
470
+ return `l${ignoreCase ? s.toLowerCase() : s}`;
471
+ }
472
+ switch (typeof v) {
473
+ case "number":
474
+ return Object.is(v, -0) ? "n0" : `n${v}`;
475
+ case "string":
476
+ return `s${ignoreCase ? v.toLowerCase() : v}`;
477
+ case "boolean":
478
+ return v ? "bt" : "bf";
479
+ case "bigint":
480
+ return `n${v}`;
481
+ default:
482
+ return `j${JSON.stringify(v)}`;
483
+ }
484
+ }
485
+ const keyOf = (values, opts) => values.map((v) => keyPart(v, opts)).join("\u0001");
486
+
487
+ // ── schema ──────────────────────────────────────────────────────────────────
488
+
489
+ const DECLARED_TYPES = new Set(["string", "number", "integer", "boolean", "date", "datetime", "json", "quantity", "null", "mixed", "any"]);
490
+
491
+ /** Declared schema in any of its spellings (`{ a: "number" }`, `[ "a", { name, type } ]`, `{ columns: [...] }`) as `{ columns: [{ name, type }] }`. */
492
+ export function normalizeSchema(declared) {
493
+ if (declared === undefined || declared === null) return undefined;
494
+ const list = Array.isArray(declared) ? declared : Array.isArray(declared.columns) ? declared.columns : Object.entries(declared).map(([name, type]) => ({ name, type }));
495
+ const seen = new Set();
496
+ const columns = list.map((c) => {
497
+ const col = typeof c === "string" ? { name: c, type: "any" } : { ...c, type: c.type ?? "any" };
498
+ if (typeof col.name !== "string" || !col.name) throw new TableError("bad-schema", "A schema column needs a name.");
499
+ if (!DECLARED_TYPES.has(col.type)) throw new TableError("bad-schema", `Column "${col.name}": unknown type "${col.type}" (use ${[...DECLARED_TYPES].join(", ")}).`);
500
+ if (seen.has(col.name)) throw new TableError("bad-schema", `The schema names column "${col.name}" twice.`);
501
+ seen.add(col.name);
502
+ return col;
503
+ });
504
+ return { columns };
505
+ }
506
+
507
+ /**
508
+ * The schema of rows: `{ columns: [{ name, type, nullable, missing }], rows }`.
509
+ * `missing` counts rows without the key (undefined), `nullable` says a null or
510
+ * a missing cell was seen. With `declared`, its columns come first (with
511
+ * their declared type, still counting nulls and missing from the data) and
512
+ * data-only columns follow. `sample` limits how many rows are read (default all).
513
+ * With `dates: true`, text that is an ISO 8601 date or date-time counts as type
514
+ * "date" / "datetime" (off by default: text is otherwise never read as a date).
515
+ * With `dateHints: true`, a column of numbers or text that looks like dates in another
516
+ * spelling (epoch seconds or milliseconds, 03/09/2024, 9 Mar 2024) keeps its type and
517
+ * gets `dateHint: { type, from, confidence, of }` (see `dateHint`): what to give `convert`.
518
+ */
519
+ export function inferSchema(rows, options) {
520
+ return driveSync(inferSchemaYielding(rows, options));
521
+ }
522
+
523
+ /**
524
+ * `inferSchema` as a generator, for an operation's last step: with the run's `ctx` it calls
525
+ * `ctx.tick()` per row, so an async run yields and sees its signal and budgets while a big result is
526
+ * read. Without `ctx` it never yields (that is what `inferSchema` drives).
527
+ */
528
+ export function* inferSchemaYielding(rows, { declared, sample = Infinity, dates = false, dateHints = false } = {}, ctx) {
529
+ const decl = normalizeSchema(declared);
530
+ const order = [];
531
+ const info = new Map();
532
+ const touch = (name, type) => {
533
+ let c = info.get(name);
534
+ if (!c) {
535
+ c = { name, types: new Set(), nulls: 0, present: 0, hinted: dateHints ? [] : null };
536
+ info.set(name, c);
537
+ order.push(name);
538
+ }
539
+ return c;
540
+ };
541
+ for (const c of decl?.columns ?? []) touch(c.name);
542
+ const n = Math.min(rows.length, sample);
543
+ for (let i = 0; i < n; i++) {
544
+ if (ctx?.tick()) yield;
545
+ const row = rows[i];
546
+ for (const k of Object.keys(row)) {
547
+ const c = touch(k);
548
+ let t = typeOfCell(row[k]);
549
+ if (dates && t === "string") t = isoKind(row[k]) ?? t;
550
+ c.present++;
551
+ if (t === "null") c.nulls++;
552
+ else {
553
+ c.types.add(t);
554
+ if (c.hinted && c.hinted.length < DATE_HINT_SAMPLE && row[k] !== "") c.hinted.push(row[k]);
555
+ }
556
+ }
557
+ }
558
+ const declaredBy = new Map((decl?.columns ?? []).map((c) => [c.name, c]));
559
+ const columns = order.map((name) => {
560
+ const c = info.get(name);
561
+ const d = declaredBy.get(name);
562
+ const types = [...c.types].map((t) => (t === "bigint" ? "number" : t));
563
+ const uniq = [...new Set(types)];
564
+ if (uniq.length === 2 && uniq.includes("date") && uniq.includes("datetime")) uniq.splice(0, 2, "datetime"); // a date is a date-time without a time
565
+ const inferred = uniq.length === 0 ? "null" : uniq.length === 1 ? uniq[0] : "mixed";
566
+ const missing = n - c.present;
567
+ const hint = c.hinted && (inferred === "number" || inferred === "string") ? dateHint(c.hinted, { name }) : null;
568
+ return { name, type: d && d.type !== "any" ? d.type : inferred, nullable: c.nulls > 0 || missing > 0 || (d?.nullable ?? false), missing, ...(d && d.type !== "any" ? { declared: true } : {}), ...(hint ? { dateHint: hint } : {}) };
569
+ });
570
+ return { columns, rows: rows.length };
571
+ }
572
+
573
+ const schemaNames = (schema) => schema.columns.map((c) => c.name);
574
+
575
+ // ── patterns a person or an agent wrote ─────────────────────────────────────
576
+ // A column pattern or a split pattern is text from the canvas, so it never reaches RegExp (which backtracks: `(a+)+$` freezes the page). The
577
+ // linear-time matcher of src/model/safe-regex.js is handed in by the `safe-regex` plugin (src/table/index.js, the sandbox's `mallory:table/safe-regex`),
578
+ // which installs first: this module cannot import it (a sandbox module imports nothing).
579
+ let safeRegex = null;
580
+ /** Called by the safe-regex plugin's install: the matcher this module uses for patterns. */
581
+ export function bindSafeRegex(lib) {
582
+ safeRegex = lib;
583
+ }
584
+ /** A matcher for `source` with `flags`, or a TableError saying why not (a pattern outside the supported subset is refused here, with the matcher's reason). */
585
+ function safePattern(source, flags, what, wording = "isn't a regular expression") {
586
+ if (!safeRegex) throw new TableError("bad-option", `${what} can't be checked: no safe pattern matcher is installed`);
587
+ const f = safeRegex.flagOptions(flags);
588
+ if (f.error) throw new TableError("bad-option", `${what} ${JSON.stringify(source)}: ${f.error}`);
589
+ const c = safeRegex.compileSafeRegex(String(source), f.options);
590
+ if (!c.ok) throw new TableError("bad-option", `${what} ${JSON.stringify(source)} ${wording} this helper can run safely: ${c.error}`);
591
+ return c;
592
+ }
593
+
594
+ /**
595
+ * Resolve a column selector against a schema to column names, in schema order
596
+ * (or the order named, for a list). A selector is a name, a list of names, "*",
597
+ * `{ type: "number" }`, `{ match: "^pre" }` (regex source), or `{ except: sel }`.
598
+ * An unknown name throws a TableError that lists the columns that exist.
599
+ */
600
+ export function resolveColumns(selector, schema, what = "column") {
601
+ const names = schemaNames(schema);
602
+ const known = new Set(names);
603
+ const pick = (sel) => {
604
+ if (sel === "*" || sel === undefined) return names;
605
+ if (typeof sel === "string") return [sel];
606
+ if (Array.isArray(sel)) return sel.flatMap((s) => (typeof s === "string" ? [s] : pick(s)));
607
+ if (sel && typeof sel === "object") {
608
+ if ("except" in sel) {
609
+ const out = new Set(pick(sel.except));
610
+ return names.filter((n) => !out.has(n));
611
+ }
612
+ if ("type" in sel) return schema.columns.filter((c) => c.type === sel.type).map((c) => c.name);
613
+ if ("match" in sel) {
614
+ const re = safePattern(sel.match, sel.flags, "The column pattern");
615
+ // A column name the pattern can't be tested on (a name over the matcher's length, or a pattern too costly) is not guessed at: the selector is refused.
616
+ const budget = { left: safeRegex.SAFE_REGEX_PASS_STEPS };
617
+ return names.filter((n) => {
618
+ const answer = re.check(n, budget);
619
+ if (answer === "match") return true;
620
+ if (answer === "none") return false;
621
+ throw new TableError("bad-option", `The column pattern ${JSON.stringify(sel.match)} couldn't be tested on the column ${JSON.stringify(n.length > 40 ? `${n.slice(0, 40)}…` : n)} (${answer}), so no columns were chosen`);
622
+ });
623
+ }
624
+ }
625
+ throw new TableError("bad-option", `Can't read ${JSON.stringify(sel)} as a ${what} selector (a name, a list of names, "*", { type }, { match } or { except }).`);
626
+ };
627
+ const out = pick(selector);
628
+ for (const n of out) {
629
+ if (!known.has(n)) throw new TableError("unknown-column", `No ${what} "${n}"${suggest(n, names)}. Columns: ${names.length ? names.map((x) => JSON.stringify(x)).join(", ") : "(none: the table has no rows and no declared schema)"}.`, { column: n, columns: names });
630
+ }
631
+ return [...new Set(out)];
632
+ }
633
+
634
+ function suggest(name, names) {
635
+ const lower = String(name).toLowerCase();
636
+ const near = names.find((n) => n.toLowerCase() === lower || n.toLowerCase().replace(/[_\s-]/g, "") === lower.replace(/[_\s-]/g, ""));
637
+ return near ? ` (did you mean "${near}"?)` : "";
638
+ }
639
+
640
+ // ── comparing ───────────────────────────────────────────────────────────────
641
+
642
+ const collators = new Map();
643
+ function collatorFor(locale, { numeric = false, sensitivity = "variant", caseFirst } = {}) {
644
+ const key = `${locale}|${numeric}|${sensitivity}|${caseFirst ?? ""}`;
645
+ let c = collators.get(key);
646
+ if (!c) {
647
+ try {
648
+ c = new Intl.Collator(locale === "codepoint" ? undefined : locale, { numeric, sensitivity, ...(caseFirst ? { caseFirst } : {}) });
649
+ } catch (error) {
650
+ throw new TableError("bad-option", `Unknown locale ${JSON.stringify(locale)}: ${error.message}`);
651
+ }
652
+ collators.set(key, c);
653
+ }
654
+ return c;
655
+ }
656
+
657
+ /** Compare two non-null cells. Same type: natural order (strings by the locale's collation, or by code point with locale "codepoint"). Different types: by type rank number < string < boolean < json. */
658
+ export function compareCells(a, b, { locale = "en", numeric = false, sensitivity = "variant", caseFirst } = {}) {
659
+ const ta = typeOfCell(a);
660
+ const tb = typeOfCell(b);
661
+ const ra = TYPE_RANK[ta] ?? 9;
662
+ const rb = TYPE_RANK[tb] ?? 9;
663
+ if (ra !== rb) return ra - rb;
664
+ if (ta === "string") {
665
+ if (locale === "codepoint") return a < b ? -1 : a > b ? 1 : 0;
666
+ return collatorFor(locale, { numeric, sensitivity, caseFirst }).compare(a, b);
667
+ }
668
+ if (ta === "number" || ta === "bigint") return a < b ? -1 : a > b ? 1 : 0;
669
+ if (ta === "boolean") return Number(a) - Number(b);
670
+ const sa = JSON.stringify(a);
671
+ const sb = JSON.stringify(b);
672
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
673
+ }
674
+
675
+ // ── op registry ─────────────────────────────────────────────────────────────
676
+
677
+ export const aggregates = new Map();
678
+ export const functions = new Map();
679
+ export const ops = new Map();
680
+ const hooks = { compileExpr: null, sqlVersion: null, units: null, unitsCheck: null };
681
+
682
+ /**
683
+ * Compile an expression string (the SQL engine's expression grammar) to
684
+ * `(row, index) => value`. Throws "engine-unavailable" when the SQL plugin
685
+ * isn't installed.
686
+ */
687
+ export function compileExpr(text, options) {
688
+ if (!hooks.compileExpr) throw new TableError("engine-unavailable", "Expression strings need the table SQL engine (mallory:table/sql), which isn't loaded in this runtime. Pass a function instead, or run where the engine is available.");
689
+ return hooks.compileExpr(text, options);
690
+ }
691
+
692
+ /** Used by plugins (the SQL engine) to provide compileExpr. */
693
+ export function setExpressionEngine(compile, version) {
694
+ hooks.compileExpr = compile;
695
+ hooks.sqlVersion = version;
696
+ }
697
+ export const hasExpressionEngine = () => Boolean(hooks.compileExpr);
698
+
699
+ /**
700
+ * Used by the quantities module (src/units/units.js `installTable`) to provide the quantity column: `read(cell, spec)`
701
+ * returns `{ value }` or `{ error }`, and `check(spec)` says why a column's settings can't be used ("" when they can). Without it a column of type "quantity" says the module isn't loaded.
702
+ */
703
+ export function setUnitsEngine(read, check) {
704
+ hooks.units = read;
705
+ hooks.unitsCheck = check;
706
+ }
707
+ export const hasUnitsEngine = () => Boolean(hooks.units);
708
+
709
+ const toFn = (what, expr, ctx, columns) => {
710
+ if (typeof expr === "function") return expr;
711
+ if (typeof expr === "string") return compileExpr(expr, { params: ctx.options.params, columns });
712
+ throw new TableError("bad-option", `${ctx.op}: ${what} should be an expression string or a function.`);
713
+ };
714
+
715
+ /** The error text of a thrown value. */
716
+ const messageOf = (e) => (e && e.message ? e.message : String(e));
717
+
718
+ function* finish(ctx, partial, inputRowsList, declared) {
719
+ const result = Array.isArray(partial) ? { rows: partial } : { ...partial };
720
+ const rows = result.rows;
721
+ ctx.checkRows(rows.length, "the result");
722
+ result.schema = result.schema ?? (yield* inferSchemaYielding(rows, { declared: declared ?? ctx.options.outputSchema }, ctx));
723
+ result.errors = ctx.errors;
724
+ result.notes = ctx.notes;
725
+ // Lineage is opt-in: without `trace` nothing of it is on the result; with it, every entry is capped.
726
+ if (ctx.trace) {
727
+ if (result.origin) result.origin = result.origin.map((e) => capOrigin(e, ctx.maxLinks));
728
+ if (ctx.excluded.size && !result.exclusions) result.exclusions = [...ctx.excluded.values()];
729
+ } else {
730
+ delete result.origin;
731
+ delete result.exclusions;
732
+ }
733
+ for (const k of Object.keys(result)) if (result[k] === undefined) delete result[k];
734
+ return result;
735
+ }
736
+
737
+ const isGenerator = (v) => Object.prototype.toString.call(v) === "[object Generator]";
738
+
739
+ /** Run a generator to its end without ever pausing (a sync call): its `yield`s are no-ops. */
740
+ function driveSync(gen) {
741
+ let step = gen.next();
742
+ while (!step.done) step = gen.next();
743
+ return step.value;
744
+ }
745
+
746
+ /** Let the event loop run (messages, timers, an abort): a macrotask, not a microtask. */
747
+ function yieldNow() {
748
+ if (typeof MessageChannel === "function") {
749
+ return new Promise((resolve) => {
750
+ const { port1, port2 } = new MessageChannel();
751
+ port1.onmessage = () => {
752
+ port1.close();
753
+ resolve();
754
+ };
755
+ port2.postMessage(null);
756
+ });
757
+ }
758
+ return new Promise((resolve) => setTimeout(resolve, 0));
759
+ }
760
+
761
+ /** Run a generator, yielding to the event loop at each of its `yield`s and checking the signal and budgets when it resumes. */
762
+ async function driveAsync(gen, ctx) {
763
+ try {
764
+ ctx.check();
765
+ let step = gen.next();
766
+ while (!step.done) {
767
+ await yieldNow();
768
+ ctx.resumed();
769
+ ctx.check();
770
+ step = gen.next();
771
+ }
772
+ return step.value;
773
+ } finally {
774
+ gen.return?.(); // an abort (or an error) leaves the generator's finally blocks to run
775
+ }
776
+ }
777
+
778
+ /** Every `callable`'s async entry, by name: exported as `table.async` (a plugin's `defineOp` adds to it). */
779
+ export const asyncOps = {};
780
+ export { asyncOps as async };
781
+
782
+ /**
783
+ * The two entry points of one operation. `fn(input, options, ctx)` is a plain
784
+ * function or a generator function (see CANCELLATION above) that returns what
785
+ * `finish` takes: `{ sync(input, options), async(input, options) }`, the second
786
+ * resolving to the same result and rejecting with TableError "aborted" when
787
+ * `options.signal` aborts. Registers `asyncOps[name]` (unless `register: false`: a plugin's own entry points). The operations of
788
+ * defineOp go through here; so do parseCsv and formatCsv.
789
+ */
790
+ export function callable(name, fn, { prepare = (ctx, input) => checkInput(ctx, input), done = (ctx, result) => finish(ctx, result), register = true } = {}) {
791
+ function* body(input, options, ctx) {
792
+ prepare(ctx, input);
793
+ let result = fn(input, options, ctx);
794
+ if (isGenerator(result)) result = yield* result;
795
+ const finished = done(ctx, result);
796
+ return isGenerator(finished) ? yield* finished : finished; // the default `done` (finish) yields while it infers the schema
797
+ }
798
+ const sync = (input, options = {}) => {
799
+ const ctx = makeContext(name, options ?? {});
800
+ ctx.check(); // an aborted signal never starts a call, however small (an async call checks first too)
801
+ return driveSync(body(input, options ?? {}, ctx));
802
+ };
803
+ const asynchronous = (input, options = {}) => {
804
+ let ctx;
805
+ try {
806
+ ctx = makeContext(name, options ?? {}, true);
807
+ } catch (error) {
808
+ return Promise.reject(error);
809
+ }
810
+ return driveAsync(body(input, options ?? {}, ctx), ctx);
811
+ };
812
+ if (register) asyncOps[name] = asynchronous;
813
+ return { sync, async: asynchronous };
814
+ }
815
+
816
+ /**
817
+ * Define an operation: `table[name](input, options)` and `table.run(name, input, options)`
818
+ * call `fn(input, options, ctx)`, which returns rows or a partial result
819
+ * (`{ rows, schema?, rejected?, origin?, <other tables> }`); the wrapper adds
820
+ * `schema`, `errors` and `notes` and applies the budgets and options every
821
+ * operation shares. `inputs`: "rows" (default), or ["left", "right"]. `fn` may be
822
+ * a generator function (cancellable and yielding in `table.async[name]`, see CANCELLATION).
823
+ */
824
+ export function defineOp(name, fn, { inputs = "rows", doc } = {}) {
825
+ const prepare = (ctx, input) => {
826
+ if (Array.isArray(inputs)) {
827
+ for (const side of inputs) checkInput(ctx, input?.[side], side);
828
+ } else if (inputs === "rows") checkInput(ctx, input, "the input");
829
+ // inputs: "none": the operation checks its own (the SQL engine takes a query and named tables).
830
+ };
831
+ const { sync, async } = callable(name, fn, { prepare });
832
+ ops.set(name, { name, run: sync, runAsync: async, inputs, doc });
833
+ return Object.assign(sync, { async });
834
+ }
835
+
836
+ /** Run an operation by name (`table.run("filter", rows, { where: "x > 1" })`). */
837
+ export function run(name, input, options) {
838
+ return opNamed(name).run(input, options);
839
+ }
840
+
841
+ /** `table.runAsync(name, input, options)`: `run`, yielding to the event loop and cancellable by `options.signal`. */
842
+ export function runAsync(name, input, options) {
843
+ try {
844
+ return opNamed(name).runAsync(input, options);
845
+ } catch (error) {
846
+ return Promise.reject(error);
847
+ }
848
+ }
849
+
850
+ /** Where each operation takes its options, when it isn't the second argument: `table.sql(query, tables, options)`, `table.run(name, input, options)`. */
851
+ const OPTIONS_AT = { sql: 2, run: 2, runAsync: 2 };
852
+ const LINEAGE_OPTIONS_AT = { extend: 2, declare: 3, trace: 2, fate: 3, inspect: 1 };
853
+
854
+ /**
855
+ * `table` bound to a run's AbortSignal: a copy of the assembled table `t`
856
+ * (core and plugins) in which every operation, sync or `.async`, and `run` and
857
+ * `runAsync`, gets `signal` in its options unless the call names its own
858
+ * (`signal: null` opts out). Pane code gets this, with the pane-scope `signal` of
859
+ * the run, so a superseded or deleted pane's long table work stops without the
860
+ * code passing the signal by hand. Frozen, like the table it copies.
861
+ */
862
+ export function bindSignal(t, signal) {
863
+ const bind = (at, fn) => {
864
+ if (typeof fn !== "function") return fn;
865
+ return (...args) => {
866
+ const given = args[at];
867
+ if (given === undefined || given === null) {
868
+ while (args.length < at) args.push(undefined);
869
+ args[at] = { signal };
870
+ } else if (typeof given === "object" && given.signal === undefined) args[at] = { ...given, signal };
871
+ return fn(...args);
872
+ };
873
+ };
874
+ const names = new Set([...ops.keys(), ...Object.keys(t.async ?? {}), "run", "runAsync"]);
875
+ const asynchronous = {};
876
+ for (const name of Object.keys(t.async ?? {})) asynchronous[name] = bind(OPTIONS_AT[name] ?? 1, t.async[name]);
877
+ const bound = { ...t, async: Object.freeze(asynchronous) };
878
+ if (t.asyncOps === t.async) bound.asyncOps = bound.async;
879
+ for (const name of names) {
880
+ if (typeof t[name] !== "function") continue;
881
+ const fn = bind(OPTIONS_AT[name] ?? 1, t[name]);
882
+ bound[name] = asynchronous[name] ? Object.assign(fn, { async: asynchronous[name] }) : fn;
883
+ }
884
+ // The lineage plugin's entry points take their options after their other arguments (table-lineage.js).
885
+ if (t.lineage?.async) {
886
+ const group = (source) => Object.fromEntries(Object.entries(LINEAGE_OPTIONS_AT).map(([name, at]) => [name, bind(at, source[name])]));
887
+ bound.lineage = Object.freeze({ ...t.lineage, ...group(t.lineage), async: Object.freeze(group(t.lineage.async)) });
888
+ }
889
+ return Object.freeze(bound);
890
+ }
891
+
892
+ function opNamed(name) {
893
+ const op = ops.get(name);
894
+ if (!op) throw new TableError("unknown-op", `No table operation "${name}". Operations: ${[...ops.keys()].join(", ")}.`);
895
+ return op;
896
+ }
897
+
898
+ /**
899
+ * Sort `items` in place with `compare`, stably, and return them. In a sync run
900
+ * this is Array#sort; in an async run it is a merge sort that yields between
901
+ * merge steps (`yield* sortYielding(ctx, items, compare)`), so a long sort can
902
+ * be cancelled. Same order either way when `compare` is consistent. `compare`
903
+ * itself never calls `ctx.tick()` (sortYielding does).
904
+ */
905
+ export function* sortYielding(ctx, items, compare) {
906
+ if (!ctx.yielding) {
907
+ // The comparator is where a sync sort can check its budgets (it can't yield).
908
+ return items.sort((a, b) => {
909
+ ctx.tick();
910
+ return compare(a, b);
911
+ });
912
+ }
913
+ const n = items.length;
914
+ let from = items;
915
+ let to = new Array(n);
916
+ for (let width = 1; width < n; width *= 2) {
917
+ for (let lo = 0; lo < n; lo += 2 * width) {
918
+ const mid = Math.min(lo + width, n);
919
+ const hi = Math.min(lo + 2 * width, n);
920
+ let i = lo;
921
+ let j = mid;
922
+ let k = lo;
923
+ while (i < mid && j < hi) {
924
+ if (ctx.tick()) yield;
925
+ to[k++] = compare(from[j], from[i]) < 0 ? from[j++] : from[i++];
926
+ }
927
+ while (i < mid) to[k++] = from[i++];
928
+ while (j < hi) to[k++] = from[j++];
929
+ }
930
+ [from, to] = [to, from];
931
+ }
932
+ if (from !== items) for (let i = 0; i < n; i++) items[i] = from[i];
933
+ return items;
934
+ }
935
+
936
+ /** Split off the rows `ctx.rejected` marks (onError "route"); returns `[kept, rejected, keptOrigin]`. */
937
+ function routeRejected(ctx, input, output, origin, side = "") {
938
+ if (!ctx.rejected.size) return [output, [], origin];
939
+ const keep = [];
940
+ const keepOrigin = [];
941
+ const rejected = [];
942
+ const seen = new Set();
943
+ for (let i = 0; i < output.length; i++) {
944
+ const from = origin ? origin[i] : undefined;
945
+ const idxs = from ? from.rows ?? [] : [];
946
+ if (from && idxs.some((j) => ctx.rejected.has(`${side}:${j}`))) {
947
+ for (const j of idxs) {
948
+ if (!ctx.rejected.has(`${side}:${j}`) || seen.has(j)) continue;
949
+ seen.add(j);
950
+ rejected.push(input[j]);
951
+ if (ctx.trace) {
952
+ const why = ctx.errors.find((e) => e.row === j && (e.side ?? "") === side);
953
+ ctx.exclude({ input: side || "rows", kind: "rejected", code: why?.code, reason: why?.message ?? "the row failed and onError is \"route\"" }, j);
954
+ }
955
+ }
956
+ } else {
957
+ keep.push(output[i]);
958
+ if (origin) keepOrigin.push(from);
959
+ }
960
+ }
961
+ return [keep, rejected, origin ? keepOrigin : undefined];
962
+ }
963
+
964
+ // ── CSV ─────────────────────────────────────────────────────────────────────
965
+
966
+ /**
967
+ * Parse CSV/TSV text (RFC 4180: quoted fields, "" for a quote, line breaks in
968
+ * quotes, a BOM skipped) to a table.
969
+ *
970
+ * - `empty`: what an unquoted empty field is: "null" (default), "string" ("")
971
+ * or "undefined" (the key is left out). A quoted `""` is always the empty
972
+ * string, so the three stay apart; a row shorter than the header leaves its
973
+ * missing cells undefined (reported as a note).
974
+ * - `infer: true` reads unquoted numbers and true/false as numbers/booleans;
975
+ * everything else, and every quoted field, stays text. Default off.
976
+ * - `header`: true (default) uses the first record; false names columns
977
+ * "column_1"…; or a list of names.
978
+ * - `delimiter`: "," (default), "\t", ";" …
979
+ * - A record with more fields than the header is an error entry (`extra-fields`),
980
+ * its extra fields dropped; duplicate or blank header names are made unique
981
+ * and noted. An unclosed quote throws.
982
+ */
983
+ function* parseCsvRun(text, options, ctx) {
984
+ const { delimiter = ",", empty = "null", infer = false, header = true, skipEmpty = true } = options;
985
+ if (typeof text !== "string") throw new TableError("bad-input", "parseCsv: the input isn't text.");
986
+ if (delimiter.length !== 1) throw new TableError("bad-option", "parseCsv: the delimiter is one character.");
987
+ if (!["null", "string", "undefined"].includes(empty)) throw new TableError("bad-option", 'parseCsv: empty is "null", "string" or "undefined".');
988
+ if (ctx.limits.maxBytes && text.length > ctx.limits.maxBytes) throw new TableError("limit", `parseCsv: the text is ${text.length} characters, over limits.maxBytes (${ctx.limits.maxBytes}).`);
989
+ const s = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
990
+ const records = []; // each: array of { v: string, q: boolean }
991
+ let rec = [];
992
+ let field = "";
993
+ let quoted = false;
994
+ let inQuotes = false;
995
+ let any = false;
996
+ const endField = () => {
997
+ rec.push({ v: field, q: quoted });
998
+ field = "";
999
+ quoted = false;
1000
+ any = true;
1001
+ };
1002
+ const endRecord = () => {
1003
+ endField();
1004
+ if (!(rec.length === 1 && rec[0].v === "" && !rec[0].q && skipEmpty)) {
1005
+ records.push(rec);
1006
+ ctx.checkRows(records.length, "the CSV");
1007
+ }
1008
+ rec = [];
1009
+ any = false;
1010
+ };
1011
+ for (let i = 0; i < s.length; i++) {
1012
+ if (ctx.tick()) yield;
1013
+ const c = s[i];
1014
+ if (inQuotes) {
1015
+ if (c === '"') {
1016
+ if (s[i + 1] === '"') (field += '"', i++);
1017
+ else inQuotes = false;
1018
+ } else field += c;
1019
+ } else if (c === '"' && field === "" && !quoted) {
1020
+ inQuotes = true;
1021
+ quoted = true;
1022
+ any = true;
1023
+ } else if (c === delimiter) endField();
1024
+ else if (c === "\n" || c === "\r") {
1025
+ if (c === "\r" && s[i + 1] === "\n") i++;
1026
+ endRecord();
1027
+ } else field += c;
1028
+ }
1029
+ if (inQuotes) throw new TableError("csv-quote", "parseCsv: a quoted field is never closed (the text ends inside a quote).");
1030
+ if (any || field !== "" || rec.length) endRecord();
1031
+
1032
+ let names;
1033
+ let body = records;
1034
+ if (Array.isArray(header)) names = header.map(String);
1035
+ else if (header === false) names = null;
1036
+ else {
1037
+ names = (records[0] ?? []).map((f) => f.v);
1038
+ body = records.slice(1);
1039
+ }
1040
+ const width = Math.max(names?.length ?? 0, ...body.map((r) => r.length), 0);
1041
+ if (!names) names = Array.from({ length: width }, (_, i) => `column_${i + 1}`);
1042
+ const used = new Set();
1043
+ const cols = names.map((n, i) => {
1044
+ let name = n === "" ? `column_${i + 1}` : n;
1045
+ if (name !== n) ctx.note(`Header ${i + 1} was blank: named "${name}".`);
1046
+ let k = 2;
1047
+ const base = name;
1048
+ while (used.has(name)) name = `${base}_${k++}`;
1049
+ if (name !== base) ctx.note(`Header "${base}" appears more than once: the later one is "${name}".`);
1050
+ used.add(name);
1051
+ return name;
1052
+ });
1053
+ const read = (f) => {
1054
+ if (f.q) return f.v;
1055
+ if (f.v === "") return empty === "null" ? null : empty === "string" ? "" : undefined;
1056
+ if (!infer) return f.v;
1057
+ if (f.v === "true") return true;
1058
+ if (f.v === "false") return false;
1059
+ // Numbers only when they read back unchanged enough to trust: no leading zeros ("007" is an id), nothing past safe integers.
1060
+ if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(f.v)) {
1061
+ const n = Number(f.v);
1062
+ if (Number.isFinite(n) && (Number.isSafeInteger(n) || /[.eE]/.test(f.v))) return n;
1063
+ }
1064
+ return f.v;
1065
+ };
1066
+ let short = 0;
1067
+ const rows = [];
1068
+ for (let ri = 0; ri < body.length; ri++) {
1069
+ if (ctx.tick()) yield;
1070
+ const r = body[ri];
1071
+ const row = {};
1072
+ for (let i = 0; i < Math.min(r.length, cols.length); i++) {
1073
+ const v = read(r[i]);
1074
+ if (v !== undefined) row[cols[i]] = v;
1075
+ }
1076
+ if (r.length < cols.length) short++;
1077
+ if (r.length > cols.length) ctx.error({ row: ri, code: "extra-fields", message: `${r.length} fields but ${cols.length} columns; the extra ${r.length - cols.length} were ignored`, value: r.slice(cols.length).map((f) => f.v) });
1078
+ rows.push(row);
1079
+ }
1080
+ if (short) ctx.note(`${short} row${short === 1 ? " is" : "s are"} shorter than the header: the missing cells are left out (undefined).`);
1081
+ const schema = inferSchema(rows, { declared: cols.map((name) => ({ name, type: "any" })) });
1082
+ const result = { rows, schema, errors: ctx.errors, notes: ctx.notes };
1083
+ if (ctx.policy === "route" && ctx.rejected.size) {
1084
+ const bad = new Set([...ctx.rejected].map((k) => Number(k.slice(1))));
1085
+ result.rejected = rows.filter((_, i) => bad.has(i));
1086
+ result.rows = rows.filter((_, i) => !bad.has(i));
1087
+ }
1088
+ return result;
1089
+ }
1090
+
1091
+ const parseCsvCall = callable("parseCsv", parseCsvRun, { prepare: () => {}, done: (_ctx, result) => result });
1092
+ export const parseCsv = (text, options = {}) => parseCsvCall.sync(text, options);
1093
+
1094
+ const csvText = (v) => {
1095
+ if (v === null || v === undefined) return "";
1096
+ if (typeof v === "string") return v;
1097
+ if (typeof v === "number") return Object.is(v, -0) ? "0" : String(v);
1098
+ if (typeof v === "boolean" || typeof v === "bigint") return String(v);
1099
+ try {
1100
+ return JSON.stringify(v);
1101
+ } catch {
1102
+ return String(v);
1103
+ }
1104
+ };
1105
+
1106
+ /**
1107
+ * A table as CSV text (CRLF line ends by default). null and undefined are
1108
+ * written as an empty unquoted field and the empty string as `""`, so parseCsv
1109
+ * (with the default `empty: "null"`) reads null and "" back; an undefined cell
1110
+ * comes back as null (CSV has no third state besides a short row). Fields are
1111
+ * quoted when they hold a quote, the delimiter or a line break, or begin or end
1112
+ * with a space. Options: `columns` (default all, in schema order), `header`
1113
+ * (true), `delimiter` (","), `newline` ("\r\n"), `quoteEmpty` (true: write ""
1114
+ * for the empty string).
1115
+ */
1116
+ function* formatCsvRun(rows, options, ctx) {
1117
+ const { delimiter = ",", newline = "\r\n", header = true, quoteEmpty = true } = options;
1118
+ const columns = options.columns ?? schemaNames(inferSchema(rows, { declared: options.schema }));
1119
+ const quote = (v) => {
1120
+ if (v === "" && quoteEmpty) return '""';
1121
+ const t = csvText(v);
1122
+ return t.includes('"') || t.includes("\n") || t.includes("\r") || t.includes(delimiter) || /^\s|\s$/.test(t) ? `"${t.replaceAll('"', '""')}"` : t;
1123
+ };
1124
+ const lines = header ? [columns.map((c) => quote(String(c))).join(delimiter)] : [];
1125
+ for (const row of rows) {
1126
+ if (ctx.tick()) yield;
1127
+ lines.push(columns.map((c) => quote(row[c])).join(delimiter));
1128
+ }
1129
+ return lines.join(newline) + (lines.length ? newline : "");
1130
+ }
1131
+
1132
+ const formatCsvCall = callable("formatCsv", formatCsvRun, { done: (_ctx, text) => text });
1133
+ export const formatCsv = (rows, options = {}) => formatCsvCall.sync(rows, options);
1134
+
1135
+ /** Rows from a list of column names and arrays of cells (`[["a","b"],[1,2]]` shape: `fromArrays(["a","b"], [[1,2]])`). A short array leaves the rest of the cells undefined. */
1136
+ export function fromArrays(columns, arrays) {
1137
+ if (!Array.isArray(columns) || !Array.isArray(arrays)) throw new TableError("bad-input", "fromArrays(columns, rows): both are arrays.");
1138
+ return arrays.map((a) => {
1139
+ const row = {};
1140
+ columns.forEach((c, i) => {
1141
+ if (i < a.length) row[c] = a[i];
1142
+ });
1143
+ return row;
1144
+ });
1145
+ }
1146
+
1147
+ // ── select, rename, drop ────────────────────────────────────────────────────
1148
+
1149
+ const schemaFor = (rows, ctx) => inferSchema(rows, { declared: ctx.options.schema });
1150
+
1151
+ const UNKNOWN_POLICIES = ["keep", "drop", "error"];
1152
+
1153
+ /**
1154
+ * The unknown-column policy of select and rename. "Unknown" is a column
1155
+ * of the data that the operation's contract doesn't name: the declared
1156
+ * `schema` when it is given, else the columns the operation itself names.
1157
+ * `keep` carries it through, `drop` leaves it out (with a note), `error`
1158
+ * throws a TableError that lists them. Returns the policy, validated.
1159
+ */
1160
+ function unknownPolicy(op, value, fallback) {
1161
+ const policy = value ?? fallback;
1162
+ if (!UNKNOWN_POLICIES.includes(policy)) throw new TableError("bad-option", `${op}: unknown: ${JSON.stringify(value)} isn't a policy (use ${UNKNOWN_POLICIES.map((p) => JSON.stringify(p)).join(", ")}).`);
1163
+ return policy;
1164
+ }
1165
+
1166
+ function refuseUnknown(op, unknown, contract) {
1167
+ throw new TableError("unknown-column", `${op}: ${unknown.length === 1 ? "column" : "columns"} ${unknown.map((n) => JSON.stringify(n)).join(", ")} ${unknown.length === 1 ? "isn't" : "aren't"} ${contract ? "in the declared schema" : "named by this operation"} (unknown: "error"). Name ${unknown.length === 1 ? "it" : "them"}, or set unknown to "keep" or "drop".`, { columns: unknown });
1168
+ }
1169
+
1170
+ defineOp("select", function* (rows, o, ctx) {
1171
+ const schema = schemaFor(rows, ctx);
1172
+ const contract = normalizeSchema(ctx.options.schema);
1173
+ const policy = unknownPolicy("select", o.unknown, contract ? "keep" : "drop");
1174
+ let names = resolveColumns(o.columns ?? "*", schema);
1175
+ const rename = o.rename ?? {};
1176
+ for (const from of Object.keys(rename)) resolveColumns(from, schema);
1177
+ // Unknown: columns the data has that the contract (or, without one, the selection) doesn't name.
1178
+ const known = new Set(contract ? contract.columns.map((c) => c.name) : names);
1179
+ const unknown = schemaNames(schema).filter((n) => !known.has(n));
1180
+ if (unknown.length) {
1181
+ if (policy === "error") refuseUnknown("select", unknown, Boolean(contract));
1182
+ if (contract) {
1183
+ if (policy === "drop") {
1184
+ names = names.filter((n) => known.has(n));
1185
+ ctx.note(`select: dropped ${unknown.length === 1 ? "column" : "columns"} ${unknown.map((n) => JSON.stringify(n)).join(", ")} (not in the declared schema).`);
1186
+ }
1187
+ } else if (policy === "keep") {
1188
+ names = [...names, ...unknown];
1189
+ ctx.note(`select: kept ${unknown.length === 1 ? "column" : "columns"} ${unknown.map((n) => JSON.stringify(n)).join(", ")} after the selected ones (unknown: "keep").`);
1190
+ }
1191
+ }
1192
+ const out = [];
1193
+ const origin = ctx.trace ? [] : undefined;
1194
+ const target = (n) => rename[n] ?? n;
1195
+ const targets = names.map(target);
1196
+ if (new Set(targets).size !== targets.length) throw new TableError("bad-option", `select: two columns would be named the same (${targets.filter((t, i) => targets.indexOf(t) !== i).map((t) => JSON.stringify(t)).join(", ")}).`);
1197
+ for (let i = 0; i < rows.length; i++) {
1198
+ if (ctx.tick()) yield;
1199
+ const row = {};
1200
+ for (const n of names) if (has(rows[i], n)) row[target(n)] = rows[i][n];
1201
+ out.push(row);
1202
+ if (origin) origin.push({ rows: [i] });
1203
+ }
1204
+ const declared = names.map((n, i) => ({ name: targets[i], type: schema.columns.find((c) => c.name === n).type }));
1205
+ return { rows: out, origin, schema: inferSchema(out, { declared }) };
1206
+ });
1207
+
1208
+ defineOp("rename", function* (rows, o, ctx) {
1209
+ const nested = o.columns ?? o.map;
1210
+ const map = nested ?? o;
1211
+ const schema = schemaFor(rows, ctx);
1212
+ const contract = normalizeSchema(ctx.options.schema);
1213
+ // The policy is an option only beside a nested map: in the flat form every key is a column.
1214
+ const policy = unknownPolicy("rename", nested ? o.unknown : undefined, "keep");
1215
+ const pairs = Object.entries(map).filter(([k]) => !["trace", "onError", "schema", "limits", "signal", "params"].includes(k));
1216
+ for (const [from] of pairs) resolveColumns(from, schema);
1217
+ const known = new Set(contract ? contract.columns.map((c) => c.name) : pairs.map(([k]) => k));
1218
+ const unknown = schemaNames(schema).filter((n) => !known.has(n));
1219
+ let kept = schemaNames(schema);
1220
+ if (unknown.length && policy === "error") refuseUnknown("rename", unknown, Boolean(contract));
1221
+ if (unknown.length && policy === "drop") {
1222
+ kept = kept.filter((n) => known.has(n));
1223
+ ctx.note(`rename: dropped ${unknown.length === 1 ? "column" : "columns"} ${unknown.map((n) => JSON.stringify(n)).join(", ")} (${contract ? "not in the declared schema" : "not renamed"}).`);
1224
+ }
1225
+ const names = kept.map((n) => map[n] ?? n);
1226
+ if (new Set(names).size !== names.length) throw new TableError("bad-option", `rename: the result would have two columns named ${names.filter((t, i) => names.indexOf(t) !== i).map((t) => JSON.stringify(t)).join(", ")}.`);
1227
+ const keepSet = new Set(kept);
1228
+ const out = [];
1229
+ for (const r of rows) {
1230
+ if (ctx.tick()) yield;
1231
+ const row = {};
1232
+ for (const k of Object.keys(r)) if (keepSet.has(k)) row[map[k] ?? k] = r[k];
1233
+ out.push(row);
1234
+ }
1235
+ return { rows: out, origin: ctx.trace ? rows.map((_, i) => ({ rows: [i] })) : undefined, schema: inferSchema(out, { declared: schema.columns.filter((c) => keepSet.has(c.name)).map((c) => ({ name: map[c.name] ?? c.name, type: c.type })) }) };
1236
+ });
1237
+
1238
+ // ── derive, filter ──────────────────────────────────────────────────────────
1239
+
1240
+ /** Apply the error policy to a per-row evaluation failure; returns true if the row was routed away. */
1241
+ function rowFailed(ctx, i, column, error, value) {
1242
+ ctx.error({ row: i, ...(column !== undefined ? { column } : {}), code: error?.code ?? "expression", message: messageOf(error), ...(value !== undefined ? { value } : {}) });
1243
+ }
1244
+
1245
+ defineOp("derive", function* (rows, o, ctx) {
1246
+ const defs = Object.entries(o.columns ?? {});
1247
+ if (!defs.length) throw new TableError("bad-option", 'derive: columns: { name: "expression" | (row, index) => value } is empty.');
1248
+ const known = schemaNames(schemaFor(rows, ctx));
1249
+ const fns = defs.map(([name, expr]) => {
1250
+ const fn = toFn(`columns.${name}`, expr, ctx, known);
1251
+ known.push(name); // a later column may use an earlier one
1252
+ return [name, fn];
1253
+ });
1254
+ const out = [];
1255
+ const origin = [];
1256
+ for (let i = 0; i < rows.length; i++) {
1257
+ if (ctx.tick()) yield;
1258
+ const row = { ...rows[i] };
1259
+ for (const [name, fn] of fns) {
1260
+ try {
1261
+ row[name] = fn(row, i);
1262
+ if (row[name] === undefined) row[name] = null;
1263
+ } catch (error) {
1264
+ rowFailed(ctx, i, name, error);
1265
+ if (ctx.policy !== "keep") row[name] = null;
1266
+ }
1267
+ }
1268
+ out.push(row);
1269
+ if (origin) origin.push({ rows: [i] });
1270
+ }
1271
+ const [kept, rejected, keptOrigin] = routeRejected(ctx, rows, out, origin);
1272
+ return { rows: kept, origin: ctx.trace ? keptOrigin : undefined, ...(rejected.length ? { rejected } : {}) };
1273
+ });
1274
+
1275
+ defineOp("filter", function* (rows, o, ctx) {
1276
+ const test = toFn("where", o.where, ctx, schemaNames(schemaFor(rows, ctx)));
1277
+ const keep = [];
1278
+ const excluded = [];
1279
+ const rejected = [];
1280
+ const keepIdx = [];
1281
+ const excludedIdx = [];
1282
+ for (let i = 0; i < rows.length; i++) {
1283
+ if (ctx.tick()) yield;
1284
+ let pass;
1285
+ try {
1286
+ const v = test(rows[i], i);
1287
+ pass = v === true || (typeof v !== "boolean" && v !== null && v !== undefined && Boolean(v) && o.truthy === true);
1288
+ if (v !== null && v !== undefined && typeof v !== "boolean" && o.truthy !== true) throw new TableError("type-mismatch", `the condition gave ${typeOfCell(v)} ${JSON.stringify(v)}, not true/false/null (set truthy: true to accept any value)`);
1289
+ } catch (error) {
1290
+ rowFailed(ctx, i, undefined, error);
1291
+ if (ctx.policy === "route") {
1292
+ rejected.push(rows[i]);
1293
+ ctx.exclude({ kind: "rejected", code: error?.code ?? "expression", reason: messageOf(error) }, i);
1294
+ } else {
1295
+ excluded.push(rows[i]);
1296
+ excludedIdx.push(i);
1297
+ ctx.exclude({ kind: "filtered", code: error?.code ?? "expression", reason: `the condition could not be evaluated: ${messageOf(error)}` }, i);
1298
+ }
1299
+ continue;
1300
+ }
1301
+ if (pass) {
1302
+ keep.push(rows[i]);
1303
+ keepIdx.push(i);
1304
+ } else {
1305
+ excluded.push(rows[i]);
1306
+ excludedIdx.push(i);
1307
+ ctx.exclude({ kind: "filtered", reason: "the condition was not true" }, i);
1308
+ }
1309
+ }
1310
+ const out = o.invert ? excludedIdx : keepIdx;
1311
+ return { rows: o.invert ? excluded : keep, excluded: o.invert ? keep : excluded, ...(rejected.length ? { rejected } : {}), origin: ctx.trace ? out.map((i) => ({ rows: [i] })) : undefined, schema: o.invert ? undefined : inferSchema(keep, { declared: schemaFor(rows, ctx) }) };
1312
+ });
1313
+
1314
+ // ── sort ────────────────────────────────────────────────────────────────────
1315
+
1316
+ /** `["name", "-price", { column, dir, nulls, locale, numeric }]` as sort keys. */
1317
+ function sortKeys(by, o) {
1318
+ const list = Array.isArray(by) ? by : [by];
1319
+ return list.map((k) => {
1320
+ const key = typeof k === "string" ? { column: k.replace(/^[-+]/, ""), dir: k.startsWith("-") ? "desc" : "asc" } : { dir: "asc", ...k };
1321
+ if (typeof key.column !== "string") throw new TableError("bad-option", "sort: each key names a column.");
1322
+ if (!["asc", "desc"].includes(key.dir)) throw new TableError("bad-option", `sort: dir is "asc" or "desc", not ${JSON.stringify(key.dir)}.`);
1323
+ return { nulls: o.nulls ?? "last", locale: o.locale ?? "en", numeric: o.numeric ?? false, sensitivity: o.sensitivity ?? "variant", ...key };
1324
+ });
1325
+ }
1326
+
1327
+ defineOp("sort", function* (rows, o, ctx) {
1328
+ const schema = schemaFor(rows, ctx);
1329
+ const keys = sortKeys(o.by, o);
1330
+ for (const k of keys) {
1331
+ resolveColumns(k.column, schema);
1332
+ if (!["first", "last"].includes(k.nulls)) throw new TableError("bad-option", `sort: nulls is "first" or "last", not ${JSON.stringify(k.nulls)}.`);
1333
+ const col = schema.columns.find((c) => c.name === k.column);
1334
+ if (col.type === "mixed") ctx.note(`Column "${k.column}" holds mixed types: numbers sort before text, text before booleans.`);
1335
+ }
1336
+ const idx = rows.map((_, i) => i);
1337
+ yield* sortYielding(ctx, idx, (x, y) => {
1338
+ for (const k of keys) {
1339
+ const a = rows[x][k.column];
1340
+ const b = rows[y][k.column];
1341
+ const an = a === null || a === undefined;
1342
+ const bn = b === null || b === undefined;
1343
+ if (an || bn) {
1344
+ if (an && bn) continue;
1345
+ return (an ? 1 : -1) * (k.nulls === "last" ? 1 : -1);
1346
+ }
1347
+ const c = compareCells(a, b, k);
1348
+ if (c) return k.dir === "desc" ? -c : c;
1349
+ }
1350
+ return x - y; // stable
1351
+ });
1352
+ return { rows: idx.map((i) => rows[i]), origin: ctx.trace ? idx.map((i) => ({ rows: [i] })) : undefined, schema };
1353
+ });
1354
+
1355
+ // ── convert ─────────────────────────────────────────────────────────────────
1356
+
1357
+ const BOOLS = new Map([["true", true], ["false", false], ["yes", true], ["no", false], ["y", true], ["n", false], ["t", true], ["f", false], ["1", true], ["0", false], ["on", true], ["off", false]]);
1358
+
1359
+ /** Read one cell as `type`; returns `{ value }` or `{ error }`. Null/undefined cells are not touched. */
1360
+ export function convertCell(v, spec) {
1361
+ const { type } = spec;
1362
+ switch (type) {
1363
+ case "string":
1364
+ return { value: typeof v === "string" ? v : typeof v === "object" ? JSON.stringify(v) : String(v) };
1365
+ case "number":
1366
+ case "integer": {
1367
+ let n;
1368
+ if (typeof v === "number") n = v;
1369
+ else if (typeof v === "boolean") return { error: `a boolean isn't a number` };
1370
+ else if (typeof v === "string") {
1371
+ let t = v.trim();
1372
+ if (t === "") return spec.empty === "error" ? { error: "empty text isn't a number" } : { value: null };
1373
+ const group = spec.group ?? (spec.decimal === "," ? "." : ",");
1374
+ const decimal = spec.decimal ?? ".";
1375
+ if (spec.currency !== false) t = t.replace(/^[$€£¥]\s?|\s?[$€£¥]$/g, "");
1376
+ let neg = false;
1377
+ if (/^\(.*\)$/.test(t)) (neg = true, (t = t.slice(1, -1)));
1378
+ if (group) t = t.split(group).join("");
1379
+ if (decimal !== ".") t = t.replace(decimal, ".");
1380
+ if (t.endsWith("%")) return { error: `"${v}" is a percentage; strip the % or divide by 100 first` };
1381
+ if (!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(t)) return { error: `"${v}" isn't a number` };
1382
+ n = Number(t);
1383
+ if (neg) n = -n;
1384
+ } else return { error: `${typeOfCell(v)} isn't a number` };
1385
+ if (!Number.isFinite(n)) return { error: `${v} isn't a finite number` };
1386
+ if (type === "integer" && !Number.isInteger(n)) return spec.round ? { value: Math.round(n) } : { error: `${n} isn't a whole number (set round: true to round)` };
1387
+ return { value: n };
1388
+ }
1389
+ case "boolean": {
1390
+ if (typeof v === "boolean") return { value: v };
1391
+ if (typeof v === "number") return v === 0 || v === 1 ? { value: v === 1 } : { error: `${v} isn't 0 or 1` };
1392
+ const b = BOOLS.get(String(v).trim().toLowerCase());
1393
+ return b === undefined ? { error: `"${v}" isn't a yes/no value (true/false, yes/no, y/n, 1/0, on/off)` } : { value: b };
1394
+ }
1395
+ case "date":
1396
+ case "datetime": {
1397
+ let ms;
1398
+ let wall = false; // the text names a time of day but no offset: a time zone (spec.timeZone) applies
1399
+ const from = spec.from ?? "iso";
1400
+ if (from === "epoch-ms" || from === "epoch-s") {
1401
+ const n = typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN;
1402
+ if (!Number.isFinite(n)) return { error: `"${v}" isn't a number of ${from === "epoch-s" ? "seconds" : "milliseconds"} since 1970` };
1403
+ ms = from === "epoch-s" ? n * 1000 : n;
1404
+ } else if (typeof v === "string") {
1405
+ if (from === "iso") {
1406
+ const r = readIso(v);
1407
+ if (!r) return { error: `"${v}" isn't an ISO 8601 date (like 2024-03-09 or 2024-03-09T14:30:00Z)` };
1408
+ (ms = r.ms), (wall = r.time && !r.offset);
1409
+ } else {
1410
+ const r = readLoose(v, from === "text" ? "none" : from);
1411
+ if (!r || (from === "text" && !r.named)) return { error: `"${v}" isn't a ${from === "text" ? "date with a month name (like 9 Mar 2024 or March 9, 2024)" : `${from} date (like ${from === "mdy" ? "03/09/2024" : from === "dmy" ? "09/03/2024" : "2024/03/09"})`}` };
1412
+ (ms = r.ms), (wall = r.time);
1413
+ }
1414
+ } else return { error: `${typeOfCell(v)} isn't a date` };
1415
+ if (wall && spec.timeZone) ms = wallToUtc(ms, spec.timeZone);
1416
+ const d = new Date(ms);
1417
+ if (Number.isNaN(d.getTime())) return { error: `${v} is out of the range of dates` };
1418
+ return { value: type === "date" ? d.toISOString().slice(0, 10) : d.toISOString() };
1419
+ }
1420
+ case "quantity": {
1421
+ // { value, unit }: a number with a unit (src/units/units.js). unit: convert to it; from: the unit of a bare number; dimension: what it must measure.
1422
+ if (!hooks.units) return { error: "quantity columns need the units module (mallory:units), which isn't loaded in this runtime" };
1423
+ return hooks.units(v, { unit: spec.unit, from: spec.from, dimension: spec.dimension, hint: "set unit (or from) for this column" });
1424
+ }
1425
+ case "json": {
1426
+ if (typeof v !== "string") return { value: v };
1427
+ try {
1428
+ return { value: JSON.parse(v) };
1429
+ } catch (error) {
1430
+ return { error: `"${v.length > 40 ? `${v.slice(0, 39)}…` : v}" isn't JSON (${error.message})` };
1431
+ }
1432
+ }
1433
+ default:
1434
+ return { error: `unknown type "${type}"` };
1435
+ }
1436
+ }
1437
+
1438
+ /** Throw a TableError when a quantity spec's `unit`, `from` or `dimension` isn't one the units module reads (a mistake in the call, said once, not an error on every cell). */
1439
+ export function checkQuantitySpec(op, s) {
1440
+ if (s.type !== "quantity") return;
1441
+ if (!hooks.units) throw new TableError("engine-unavailable", `${op}: quantity columns need the units module (mallory:units), which isn't loaded in this runtime.`);
1442
+ for (const key of ["unit", "from", "dimension"]) if (s[key] !== undefined && typeof s[key] !== "string") throw new TableError("bad-option", `${op}: ${key} for "${s.name}" is text (a unit like "kg"${key === "dimension" ? " or a dimension like \"mass\"" : ""}).`);
1443
+ const problem = hooks.unitsCheck ? hooks.unitsCheck({ unit: s.unit, from: s.from, dimension: s.dimension }) : "";
1444
+ if (problem) throw new TableError("bad-option", `${op}: "${s.name}": ${problem}.`);
1445
+ }
1446
+
1447
+ /** Throw a TableError when a date spec's `from` or `timeZone` isn't one this table API reads. */
1448
+ export function checkDateSpec(op, s) {
1449
+ if (s.from !== undefined && !DATE_FROM.includes(s.from)) throw new TableError("bad-option", `${op}: unknown from ${JSON.stringify(s.from)} for "${s.name}" (use ${DATE_FROM.map((f) => JSON.stringify(f)).join(", ")}).`);
1450
+ if (s.timeZone !== undefined && (typeof s.timeZone !== "string" || !knownZone(s.timeZone))) throw new TableError("bad-option", `${op}: timeZone ${JSON.stringify(s.timeZone)} for "${s.name}" isn't a time zone name (like "America/Los_Angeles").`);
1451
+ }
1452
+
1453
+ /**
1454
+ * Convert columns to types, reporting each cell that can't be read.
1455
+ * `columns: { price: "number", when: { type: "datetime", from: "epoch-ms" }, qty: { type: "integer", round: true } }`.
1456
+ * Number options: `decimal` ("." or ","), `group` (thousands separator), `empty: "error"`.
1457
+ * Date options (date, datetime): `from` ("iso" default, "epoch-s", "epoch-ms", "mdy", "dmy", "ymd", "text": see DATES THAT AREN'T ISO), `timeZone` (an IANA zone that text with a time but no offset is read in; UTC by default). Output is always ISO 8601 in UTC.
1458
+ * A cell that fails follows `onError`: null with an error entry (default), kept as it was ("keep"), or its row moved to `rejected` ("route").
1459
+ */
1460
+ defineOp("convert", function* (rows, o, ctx) {
1461
+ const schema = schemaFor(rows, ctx);
1462
+ const specs = Object.entries(o.columns ?? {}).map(([name, s]) => ({ name, ...(typeof s === "string" ? { type: s } : s) }));
1463
+ if (!specs.length) throw new TableError("bad-option", 'convert: columns: { name: "number" | "integer" | "boolean" | "date" | "datetime" | "string" | "json" } is empty.');
1464
+ for (const s of specs) {
1465
+ resolveColumns(s.name, schema);
1466
+ if (!["string", "number", "integer", "boolean", "date", "datetime", "json", "quantity"].includes(s.type)) throw new TableError("bad-option", `convert: unknown type ${JSON.stringify(s.type)} for "${s.name}".`);
1467
+ if (s.type === "quantity") checkQuantitySpec("convert", s);
1468
+ else checkDateSpec("convert", s); // `from` is a date spelling here, a unit for a quantity
1469
+ }
1470
+ const out = [];
1471
+ const origin = [];
1472
+ for (let i = 0; i < rows.length; i++) {
1473
+ if (ctx.tick()) yield;
1474
+ const row = { ...rows[i] };
1475
+ for (const s of specs) {
1476
+ const v = row[s.name];
1477
+ if (v === null || v === undefined) continue;
1478
+ const r = convertCell(v, s);
1479
+ if (r.error) {
1480
+ ctx.error({ row: i, column: s.name, value: v, code: "conversion", message: r.error });
1481
+ if (ctx.policy !== "keep") row[s.name] = null;
1482
+ } else row[s.name] = r.value;
1483
+ }
1484
+ out.push(row);
1485
+ if (origin) origin.push({ rows: [i] });
1486
+ }
1487
+ const [kept, rejected, keptOrigin] = routeRejected(ctx, rows, out, origin);
1488
+ const declared = schema.columns.map((c) => ({ name: c.name, type: specs.find((s) => s.name === c.name)?.type === "integer" ? "number" : specs.find((s) => s.name === c.name)?.type ?? c.type }));
1489
+ return { rows: kept, origin: ctx.trace ? keptOrigin : undefined, schema: inferSchema(kept, { declared }), ...(rejected.length ? { rejected } : {}) };
1490
+ });
1491
+
1492
+ // ── split and explode ───────────────────────────────────────────────────────
1493
+
1494
+ /**
1495
+ * A splitter from `{ by: "," | {regex} | /re/ | {lengths:[2,3]} }` to `text => parts`. A `{ regex }` runs on the safe matcher; for text it cannot split
1496
+ * (too long, or too costly) the function returns null and `cut.reason` says why, so the op can mark that cell instead of guessing.
1497
+ */
1498
+ function splitter(by, ctx) {
1499
+ if (typeof by === "string") {
1500
+ if (by === "") throw new TableError("bad-option", `${ctx.op}: the separator is empty.`);
1501
+ return (t) => t.split(by);
1502
+ }
1503
+ if (by instanceof RegExp) return (t) => t.split(by);
1504
+ if (by && typeof by === "object" && "regex" in by) {
1505
+ const re = safePattern(by.regex, by.flags, `${ctx.op}:`);
1506
+ const budget = { left: safeRegex.SAFE_REGEX_PASS_STEPS };
1507
+ const cut = (t) => {
1508
+ const r = re.split(t, { budget });
1509
+ if (r.answer !== "done") {
1510
+ cut.reason = `the separator pattern couldn't be tested on this text (${r.answer})`;
1511
+ return null;
1512
+ }
1513
+ return r.parts;
1514
+ };
1515
+ return cut;
1516
+ }
1517
+ if (by && typeof by === "object" && Array.isArray(by.lengths)) {
1518
+ const lengths = by.lengths;
1519
+ if (!lengths.every((n) => Number.isInteger(n) && n > 0)) throw new TableError("bad-option", `${ctx.op}: lengths are positive whole numbers.`);
1520
+ return (t) => {
1521
+ const parts = [];
1522
+ let at = 0;
1523
+ for (const n of lengths) {
1524
+ parts.push(t.slice(at, at + n));
1525
+ at += n;
1526
+ }
1527
+ if (at < t.length) parts.push(t.slice(at));
1528
+ return parts;
1529
+ };
1530
+ }
1531
+ throw new TableError("bad-option", `${ctx.op}: "by" is a separator string, a RegExp, { regex, flags } or { lengths: [n, …] }.`);
1532
+ }
1533
+
1534
+ /**
1535
+ * Split a text column into several columns. `column`, `by` (a separator,
1536
+ * { regex }, { lengths }), `into` (names, or a number: column_1…), `trim`
1537
+ * (true), `empty` ("null" default: an empty part is null; "keep": ""),
1538
+ * `extra` ("error" default: a row with more parts than names gets an error
1539
+ * entry and the extras dropped; "last": the rest joins the last column with the
1540
+ * separator; "drop"), `remove` (true: drop the source column). A row with fewer
1541
+ * parts gets null for the rest.
1542
+ */
1543
+ defineOp("split", function* (rows, o, ctx) {
1544
+ const schema = schemaFor(rows, ctx);
1545
+ const [col] = resolveColumns(o.column, schema);
1546
+ const into = typeof o.into === "number" ? Array.from({ length: o.into }, (_, i) => `${col}_${i + 1}`) : o.into;
1547
+ if (!Array.isArray(into) || !into.length) throw new TableError("bad-option", "split: into is a list of column names or a number of columns.");
1548
+ const others = new Set(schemaNames(schema).filter((n) => n !== col || o.remove === false));
1549
+ for (const n of into) if (others.has(n)) throw new TableError("bad-option", `split: column "${n}" already exists.`);
1550
+ const cut = splitter(o.by, ctx);
1551
+ const trim = o.trim !== false;
1552
+ const extra = o.extra ?? "error";
1553
+ const emptyKeep = o.empty === "keep";
1554
+ const sep = typeof o.by === "string" ? o.by : ",";
1555
+ const out = [];
1556
+ const origin = [];
1557
+ for (let i = 0; i < rows.length; i++) {
1558
+ if (ctx.tick()) yield;
1559
+ const row = {};
1560
+ const v = rows[i][col];
1561
+ for (const k of Object.keys(rows[i])) if (k !== col || o.remove === false) row[k] = rows[i][k];
1562
+ if (v === null || v === undefined) for (const n of into) row[n] = null;
1563
+ else if (typeof v !== "string") {
1564
+ ctx.error({ row: i, column: col, value: v, code: "split-type", message: `${typeOfCell(v)} can't be split (only text)` });
1565
+ for (const n of into) row[n] = null;
1566
+ if (ctx.policy === "keep") row[col] = v;
1567
+ } else {
1568
+ let parts = cut(v);
1569
+ if (parts === null) {
1570
+ ctx.error({ row: i, column: col, value: v, code: "split-unsure", message: `not split: ${cut.reason}` });
1571
+ for (const n of into) row[n] = null;
1572
+ if (ctx.policy === "keep") row[col] = v;
1573
+ out.push(row);
1574
+ if (origin) origin.push({ rows: [i] });
1575
+ continue;
1576
+ }
1577
+ if (parts.length > into.length) {
1578
+ if (extra === "last") parts = [...parts.slice(0, into.length - 1), parts.slice(into.length - 1).join(sep)];
1579
+ else if (extra === "error") ctx.error({ row: i, column: col, value: v, code: "split-extra", message: `${parts.length} parts but ${into.length} columns; ${parts.length - into.length} ignored` });
1580
+ else if (extra !== "drop") throw new TableError("bad-option", 'split: extra is "error", "last" or "drop".');
1581
+ }
1582
+ into.forEach((n, j) => {
1583
+ let p = parts[j];
1584
+ if (p === undefined) return void (row[n] = null);
1585
+ if (trim) p = p.trim();
1586
+ row[n] = p === "" && !emptyKeep ? null : p;
1587
+ });
1588
+ }
1589
+ out.push(row);
1590
+ if (origin) origin.push({ rows: [i] });
1591
+ }
1592
+ const [kept, rejected, keptOrigin] = routeRejected(ctx, rows, out, origin);
1593
+ return { rows: kept, origin: ctx.trace ? keptOrigin : undefined, ...(rejected.length ? { rejected } : {}) };
1594
+ });
1595
+
1596
+ /**
1597
+ * One row per element of an array column, or per part of a text column
1598
+ * (`by`, as split). `into` names the column that holds the element (default:
1599
+ * the same column). `empty`: an empty list or null/undefined cell gives "keep"
1600
+ * (default: one row, the cell null) or "drop" (no rows). `index` names a
1601
+ * column for the element's position. Every other column repeats.
1602
+ */
1603
+ defineOp("explode", function* (rows, o, ctx) {
1604
+ const schema = schemaFor(rows, ctx);
1605
+ const [col] = resolveColumns(o.column, schema);
1606
+ const into = o.into ?? col;
1607
+ const cut = o.by === undefined ? null : splitter(o.by, ctx);
1608
+ const trim = o.trim !== false;
1609
+ const out = [];
1610
+ const origin = [];
1611
+ const emit = (i, value, position) => {
1612
+ ctx.checkRows(out.length + 1, "the result");
1613
+ const row = { ...rows[i] };
1614
+ row[into] = value;
1615
+ if (o.index) row[o.index] = position;
1616
+ out.push(row);
1617
+ if (origin) origin.push({ rows: [i] });
1618
+ };
1619
+ for (let i = 0; i < rows.length; i++) {
1620
+ if (ctx.tick()) yield;
1621
+ const v = rows[i][col];
1622
+ let items;
1623
+ if (Array.isArray(v)) items = v;
1624
+ else if (typeof v === "string" && cut) {
1625
+ const parts = cut(v);
1626
+ if (parts === null) {
1627
+ ctx.error({ row: i, column: col, value: v, code: "explode-unsure", message: `not split: ${cut.reason}` });
1628
+ if (ctx.policy !== "route") emit(i, ctx.policy === "keep" ? v : null, 0);
1629
+ continue;
1630
+ }
1631
+ items = parts.map((p) => (trim ? p.trim() : p)).filter((p) => (o.keepEmptyParts ? true : p !== ""));
1632
+ }
1633
+ else if (v === null || v === undefined) items = [];
1634
+ else {
1635
+ ctx.error({ row: i, column: col, value: v, code: "explode-type", message: `${typeOfCell(v)} can't be exploded (${cut ? "text or a list" : "a list; give `by` to split text"})` });
1636
+ if (ctx.policy !== "route") emit(i, ctx.policy === "keep" ? v : null, 0);
1637
+ continue;
1638
+ }
1639
+ if (!items.length) {
1640
+ if (o.empty !== "drop") emit(i, null, 0);
1641
+ else ctx.exclude({ kind: "dropped", reason: "nothing to explode (an empty list or no value) and empty is \"drop\"" }, i);
1642
+ continue;
1643
+ }
1644
+ items.forEach((it, p) => emit(i, it, p));
1645
+ }
1646
+ const [kept, rejected, keptOrigin] = routeRejected(ctx, rows, out, origin);
1647
+ return { rows: kept, origin: ctx.trace ? keptOrigin : undefined, ...(rejected.length ? { rejected } : {}) };
1648
+ });
1649
+
1650
+ // ── aggregates, group ───────────────────────────────────────────────────────
1651
+
1652
+ const numeric = (v) => typeof v === "number" || typeof v === "bigint";
1653
+
1654
+ function defineAggregate(name, spec) {
1655
+ aggregates.set(name, spec);
1656
+ }
1657
+ // Each aggregate: init() -> state; step(state, value, ctx) -> void (value is never undefined: a missing cell is null; `ctx.row` is the input position); done(state) -> value.
1658
+ // `nulls: true` means step sees null cells too (count(*)).
1659
+ defineAggregate("count", { init: () => ({ n: 0 }), step: (s, v, c) => void (s.n += c.star || (v !== null && v !== undefined) ? 1 : 0), done: (s) => s.n, nulls: true });
1660
+ defineAggregate("count_distinct", { init: () => ({ seen: new Set() }), step: (s, v) => void (v !== null && v !== undefined && s.seen.add(keyPart(v))), done: (s) => s.seen.size, nulls: true });
1661
+ defineAggregate("sum", {
1662
+ init: () => ({ n: 0, any: false }),
1663
+ step(s, v, c) {
1664
+ if (v === null || v === undefined) return;
1665
+ if (!numeric(v)) return c.bad(`sum needs numbers, not ${typeOfCell(v)} ${JSON.stringify(v)}`);
1666
+ s.n += Number(v);
1667
+ s.any = true;
1668
+ },
1669
+ done: (s) => (s.any ? s.n : null),
1670
+ nulls: true,
1671
+ });
1672
+ defineAggregate("avg", {
1673
+ init: () => ({ n: 0, c: 0 }),
1674
+ step(s, v, c) {
1675
+ if (v === null || v === undefined) return;
1676
+ if (!numeric(v)) return c.bad(`avg needs numbers, not ${typeOfCell(v)} ${JSON.stringify(v)}`);
1677
+ s.n += Number(v);
1678
+ s.c++;
1679
+ },
1680
+ done: (s) => (s.c ? s.n / s.c : null),
1681
+ nulls: true,
1682
+ });
1683
+ const extreme = (sign) => ({
1684
+ init: () => ({ v: null, any: false }),
1685
+ step(s, v, c) {
1686
+ if (v === null || v === undefined) return;
1687
+ if (s.any && typeOfCell(s.v) !== typeOfCell(v)) return c.bad(`mixed types (${typeOfCell(s.v)} and ${typeOfCell(v)}) can't be compared`);
1688
+ if (!s.any || compareCells(v, s.v, c.compare) * sign > 0) (s.v = v, (s.any = true));
1689
+ },
1690
+ done: (s) => (s.any ? s.v : null),
1691
+ nulls: true,
1692
+ });
1693
+ defineAggregate("min", extreme(-1));
1694
+ defineAggregate("max", extreme(1));
1695
+ defineAggregate("first", { init: () => ({ v: null, set: false }), step: (s, v) => void (!s.set && ((s.v = v), (s.set = true))), done: (s) => s.v, nulls: true });
1696
+ defineAggregate("last", { init: () => ({ v: null }), step: (s, v) => void (s.v = v), done: (s) => s.v, nulls: true });
1697
+ defineAggregate("list", { init: () => ({ a: [] }), step: (s, v) => void (v !== null && v !== undefined && s.a.push(v)), done: (s) => s.a, nulls: true });
1698
+ defineAggregate("median", {
1699
+ init: () => ({ a: [] }),
1700
+ step(s, v, c) {
1701
+ if (v === null || v === undefined) return;
1702
+ if (!numeric(v)) return c.bad(`median needs numbers, not ${typeOfCell(v)} ${JSON.stringify(v)}`);
1703
+ s.a.push(Number(v));
1704
+ },
1705
+ done: (s) => {
1706
+ if (!s.a.length) return null;
1707
+ const a = [...s.a].sort((x, y) => x - y);
1708
+ const m = a.length >> 1;
1709
+ return a.length % 2 ? a[m] : (a[m - 1] + a[m]) / 2;
1710
+ },
1711
+ nulls: true,
1712
+ });
1713
+
1714
+ /** `"sum(price)"`, `"count(*)"`, `"count_distinct(id)"` or `{ fn, column }` as `{ fn, column }`. */
1715
+ function aggregateSpec(spec, outName, ctx) {
1716
+ let fn;
1717
+ let column;
1718
+ if (typeof spec === "string") {
1719
+ const m = /^\s*([A-Za-z_]\w*)\s*\(\s*(\*|"[^"]+"|[^()]*?)\s*\)\s*$/.exec(spec);
1720
+ if (!m) throw new TableError("bad-option", `${ctx.op}: can't read the aggregate ${JSON.stringify(spec)} for "${outName}" (like "sum(price)" or "count(*)").`);
1721
+ fn = m[1].toLowerCase();
1722
+ column = m[2].replace(/^"|"$/g, "");
1723
+ } else if (spec && typeof spec === "object") {
1724
+ fn = String(spec.fn ?? "").toLowerCase();
1725
+ column = spec.column ?? "*";
1726
+ } else throw new TableError("bad-option", `${ctx.op}: the aggregate for "${outName}" is "fn(column)" or { fn, column }.`);
1727
+ if (fn === "count" && /^distinct\s+/i.test(column)) (fn = "count_distinct", (column = column.replace(/^distinct\s+/i, "")));
1728
+ if (!aggregates.has(fn)) throw new TableError("bad-option", `${ctx.op}: unknown aggregate "${fn}" for "${outName}". Aggregates: ${[...aggregates.keys()].join(", ")}.`);
1729
+ return { fn, column, impl: aggregates.get(fn) };
1730
+ }
1731
+
1732
+ /** Run a set of aggregate specs over groups of rows. Returns the rows of the aggregate values per group. */
1733
+ function* aggregateGroup(ctx, rows, members, specs, compare) {
1734
+ const states = specs.map((s) => s.impl.init());
1735
+ for (const i of members) {
1736
+ if (ctx.tick()) yield;
1737
+ specs.forEach((s, k) => {
1738
+ const star = s.column === "*";
1739
+ const v = star ? 1 : rows[i][s.column] ?? null;
1740
+ const cx = { star, row: i, compare, bad: (message) => ctx.error({ row: i, column: s.column, value: rows[i][s.column], code: "aggregate-type", message: `${s.fn}(${s.column}): ${message}; the cell was ignored` }) };
1741
+ if (!s.impl.nulls && (v === null || v === undefined)) return;
1742
+ s.impl.step(states[k], v, cx);
1743
+ });
1744
+ }
1745
+ return specs.map((s, k) => s.impl.done(states[k]));
1746
+ }
1747
+
1748
+ /**
1749
+ * Group rows. `by`: columns (empty or absent: one group of everything);
1750
+ * `aggregates: { total: "sum(price)", n: "count(*)", who: { fn: "list", column: "name" } }`.
1751
+ * Groups come out in order of first appearance. A group key is compared by
1752
+ * value and type (1 and "1" are different groups; null and a missing cell are
1753
+ * one group); `nullKeys: "drop"` leaves rows with a null key out (reported
1754
+ * as a note) instead of grouping them. A cell an aggregate can't use (`sum` of
1755
+ * text) is skipped with an error entry. Output: the `by` columns, then the aggregates.
1756
+ */
1757
+ defineOp("group", function* (rows, o, ctx) {
1758
+ const schema = schemaFor(rows, ctx);
1759
+ const by = o.by === undefined || (Array.isArray(o.by) && !o.by.length) ? [] : resolveColumns(o.by, schema, "group column");
1760
+ const specs = Object.entries(o.aggregates ?? { count: "count(*)" }).map(([name, s]) => ({ name, ...aggregateSpec(s, name, ctx) }));
1761
+ for (const s of specs) if (s.column !== "*") resolveColumns(s.column, schema);
1762
+ for (const s of specs) if (by.includes(s.name)) throw new TableError("bad-option", `group: the aggregate "${s.name}" has the name of a group column.`);
1763
+ const groups = new Map();
1764
+ let nullDropped = 0;
1765
+ for (let i = 0; i < rows.length; i++) {
1766
+ if (ctx.tick()) yield;
1767
+ const values = by.map((c) => rows[i][c]);
1768
+ if (o.nullKeys === "drop" && values.some((v) => v === null || v === undefined)) {
1769
+ ctx.exclude({ kind: "dropped", reason: "a group key is null and nullKeys is \"drop\"" }, i);
1770
+ nullDropped++;
1771
+ continue;
1772
+ }
1773
+ const k = keyOf(values);
1774
+ let g = groups.get(k);
1775
+ if (!g) groups.set(k, (g = { values, members: [] }));
1776
+ g.members.push(i);
1777
+ }
1778
+ if (!by.length && !groups.size) groups.set("", { values: [], members: [] });
1779
+ if (nullDropped) ctx.note(`${nullDropped} row${nullDropped === 1 ? " has" : "s have"} a null group key and ${nullDropped === 1 ? "was" : "were"} left out (nullKeys: "drop").`);
1780
+ for (const c of by) {
1781
+ const col = schema.columns.find((x) => x.name === c);
1782
+ if (col.type === "mixed") ctx.note(`Group column "${c}" holds mixed types: 1 and "1" are different groups.`);
1783
+ }
1784
+ const out = [];
1785
+ const origin = [];
1786
+ for (const g of groups.values()) {
1787
+ const row = {};
1788
+ by.forEach((c, k) => {
1789
+ row[c] = g.values[k] === undefined ? null : g.values[k];
1790
+ });
1791
+ const vals = yield* aggregateGroup(ctx, rows, g.members, specs, o);
1792
+ specs.forEach((s, k) => (row[s.name] = vals[k]));
1793
+ out.push(row);
1794
+ if (origin) origin.push({ rows: g.members });
1795
+ }
1796
+ const [kept, rejected, keptOrigin] = routeRejected(ctx, rows, out, origin);
1797
+ return { rows: kept, origin: ctx.trace ? keptOrigin : undefined, ...(rejected.length ? { rejected } : {}) };
1798
+ });
1799
+
1800
+ // ── pivot, unpivot ──────────────────────────────────────────────────────────
1801
+
1802
+ /**
1803
+ * Long to wide. `index`: the columns that identify a row; `column`: the column
1804
+ * whose values become new columns; `values`: the cell column; `agg`
1805
+ * (default "first") combines cells that share an index and column (any
1806
+ * aggregate: "sum", "count", "list"); `columns`: an explicit list of the new
1807
+ * column values (others are reported and left out), else the distinct values
1808
+ * in order of appearance (`sort: true` sorts them); `fill`: a cell with no data
1809
+ * (null by default); `nullLabel`: the name for a null pivot value ("null").
1810
+ */
1811
+ defineOp("pivot", function* (rows, o, ctx) {
1812
+ const schema = schemaFor(rows, ctx);
1813
+ const index = resolveColumns(o.index ?? [], schema, "index column");
1814
+ const [pivotCol] = resolveColumns(o.column, schema, "pivot column");
1815
+ const [valueCol] = resolveColumns(o.values, schema, "values column");
1816
+ const impl = aggregates.get(o.agg ?? "first");
1817
+ if (!impl) throw new TableError("bad-option", `pivot: unknown aggregate "${o.agg}". Aggregates: ${[...aggregates.keys()].join(", ")}.`);
1818
+ const spec = { fn: o.agg ?? "first", column: valueCol, impl };
1819
+ const label = (v) => (v === null || v === undefined ? o.nullLabel ?? "null" : String(v));
1820
+ const explicit = o.columns ? o.columns.map(String) : null;
1821
+ const colOrder = [];
1822
+ const colSeen = new Set();
1823
+ const rowsByKey = new Map();
1824
+ const skipped = new Set();
1825
+ for (let i = 0; i < rows.length; i++) {
1826
+ if (ctx.tick()) yield;
1827
+ const r = rows[i];
1828
+ const c = label(r[pivotCol]);
1829
+ if (explicit && !explicit.includes(c)) {
1830
+ ctx.exclude({ kind: "dropped", reason: "its pivot value is not in `columns`" }, i);
1831
+ skipped.add(c);
1832
+ continue;
1833
+ }
1834
+ if (!colSeen.has(c)) (colSeen.add(c), colOrder.push(c));
1835
+ const k = keyOf(index.map((n) => r[n]));
1836
+ let g = rowsByKey.get(k);
1837
+ if (!g) rowsByKey.set(k, (g = { values: index.map((n) => r[n]), cells: new Map() }));
1838
+ let cell = g.cells.get(c);
1839
+ if (!cell) g.cells.set(c, (cell = []));
1840
+ cell.push(i);
1841
+ }
1842
+ let names = explicit ?? (o.sort ? [...colOrder].sort((a, b) => compareCells(a, b, { numeric: true, locale: o.locale ?? "en" })) : colOrder);
1843
+ if (skipped.size) ctx.note(`Pivot values not in \`columns\` were left out: ${[...skipped].map((x) => JSON.stringify(x)).join(", ")}.`);
1844
+ for (const n of names) if (index.includes(n)) throw new TableError("bad-option", `pivot: the pivot value "${n}" would make a column with the name of an index column. Use \`prefix\` to tell them apart.`);
1845
+ const prefix = o.prefix ?? "";
1846
+ const out = [];
1847
+ const origin = [];
1848
+ for (const g of rowsByKey.values()) {
1849
+ const row = {};
1850
+ index.forEach((n, k) => (row[n] = g.values[k] === undefined ? null : g.values[k]));
1851
+ for (const n of names) {
1852
+ const members = g.cells.get(n);
1853
+ row[prefix + n] = members ? (yield* aggregateGroup(ctx, rows, members, [spec], o))[0] : o.fill ?? null;
1854
+ }
1855
+ out.push(row);
1856
+ if (origin) origin.push({ rows: [...g.cells.values()].flat() });
1857
+ }
1858
+ const [kept, rejected, keptOrigin] = routeRejected(ctx, rows, out, origin);
1859
+ return { rows: kept, origin: ctx.trace ? keptOrigin : undefined, ...(rejected.length ? { rejected } : {}), schema: inferSchema(kept, { declared: [...index, ...names.map((n) => prefix + n)].map((name) => ({ name, type: "any" })) }) };
1860
+ });
1861
+
1862
+ /**
1863
+ * Wide to long. `columns`: the columns to turn into rows (selector; default
1864
+ * every column not in `keep`); `keep`: columns that repeat; `name`/`value`: the
1865
+ * new column names ("key"/"value"); `dropNulls`: leave out null cells (default false).
1866
+ */
1867
+ defineOp("unpivot", function* (rows, o, ctx) {
1868
+ const schema = schemaFor(rows, ctx);
1869
+ const keep = resolveColumns(o.keep ?? [], schema, "kept column");
1870
+ const cols = o.columns === undefined ? schemaNames(schema).filter((n) => !keep.includes(n)) : resolveColumns(o.columns, schema);
1871
+ const clash = cols.filter((c) => keep.includes(c));
1872
+ if (clash.length) throw new TableError("bad-option", `unpivot: ${clash.map((c) => JSON.stringify(c)).join(", ")} is both kept and unpivoted.`);
1873
+ const nameCol = o.name ?? "key";
1874
+ const valueCol = o.value ?? "value";
1875
+ if (keep.includes(nameCol) || keep.includes(valueCol) || nameCol === valueCol) throw new TableError("bad-option", `unpivot: the new columns "${nameCol}" and "${valueCol}" must differ from each other and from the kept columns.`);
1876
+ const out = [];
1877
+ const origin = [];
1878
+ for (let i = 0; i < rows.length; i++) {
1879
+ if (ctx.tick()) yield;
1880
+ for (const c of cols) {
1881
+ const v = rows[i][c];
1882
+ if (o.dropNulls && (v === null || v === undefined)) continue;
1883
+ ctx.checkRows(out.length + 1, "the result");
1884
+ const row = {};
1885
+ for (const k of keep) if (has(rows[i], k)) row[k] = rows[i][k];
1886
+ row[nameCol] = c;
1887
+ row[valueCol] = v === undefined ? null : v;
1888
+ out.push(row);
1889
+ if (origin) origin.push({ rows: [i] });
1890
+ }
1891
+ }
1892
+ return { rows: out, origin: ctx.trace ? origin : undefined, schema: inferSchema(out, { declared: [...keep, nameCol, valueCol] }) };
1893
+ });
1894
+
1895
+ // ── join ────────────────────────────────────────────────────────────────────
1896
+
1897
+ /** `on`: "id", ["a","b"], or [{ left: "a", right: "b" }] as pairs. */
1898
+ function joinKeys(on, ls, rs) {
1899
+ const list = Array.isArray(on) ? on : [on];
1900
+ if (!list.length || list.some((k) => k === undefined)) throw new TableError("bad-option", 'join: `on` names the key column(s): "id", ["a", "b"] or [{ left, right }].');
1901
+ return list.map((k) => {
1902
+ const pair = typeof k === "string" ? { left: k, right: k } : { left: k.left, right: k.right ?? k.left };
1903
+ resolveColumns(pair.left, ls, "left key column");
1904
+ resolveColumns(pair.right, rs, "right key column");
1905
+ return pair;
1906
+ });
1907
+ }
1908
+
1909
+ /**
1910
+ * Join two tables: `join({ left, right }, { on, mode })`.
1911
+ *
1912
+ * - `on`: key column(s), composite allowed: "id", ["region", "year"], or
1913
+ * [{ left: "customer", right: "id" }].
1914
+ * - `mode`: "inner" (default), "left", "right" or "full".
1915
+ * - Key policies, all explicit: `nulls` ("never", default: a null or missing
1916
+ * key never matches, as in SQL; "match": null equals null); `types`
1917
+ * ("strict", default: 1 and "1" are different keys; "loose": compare as
1918
+ * trimmed text); `ignoreCase` (false); `duplicates` (how right-side rows that
1919
+ * share a key combine: "all", default, every pairing; "first"; "last";
1920
+ * "error" throws on the first repeated key). A mixed-type key column or a
1921
+ * repeated key is also noted.
1922
+ * - Columns: the left columns, then the right ones that aren't a key with
1923
+ * the same name; a name in both gets `suffix` ([left, right], default ["",
1924
+ * "_right"]). `select: { left: [...], right: [...] }` keeps only those
1925
+ * (keys stay). Unmatched cells are null.
1926
+ * - Outputs: `rows` (per `mode`), and always `matched`, `leftOnly` and
1927
+ * `rightOnly` (the original rows of each side that found no partner; with
1928
+ * `nulls: "never"`, null-key rows are here).
1929
+ */
1930
+ defineOp(
1931
+ "join",
1932
+ function* ({ left, right }, o, ctx) {
1933
+ const ls = inferSchema(left, { declared: o.leftSchema });
1934
+ const rs = inferSchema(right, { declared: o.rightSchema });
1935
+ const mode = o.mode ?? "inner";
1936
+ if (!["inner", "left", "right", "full"].includes(mode)) throw new TableError("bad-option", `join: mode is "inner", "left", "right" or "full", not ${JSON.stringify(mode)}.`);
1937
+ const nulls = o.nulls ?? "never";
1938
+ const types = o.types ?? "strict";
1939
+ const dup = o.duplicates ?? "all";
1940
+ if (!["never", "match"].includes(nulls)) throw new TableError("bad-option", 'join: nulls is "never" or "match".');
1941
+ if (!["strict", "loose"].includes(types)) throw new TableError("bad-option", 'join: types is "strict" or "loose".');
1942
+ if (!["all", "first", "last", "error"].includes(dup)) throw new TableError("bad-option", 'join: duplicates is "all", "first", "last" or "error".');
1943
+ const keys = joinKeys(o.on, ls, rs);
1944
+ const kopts = { loose: types === "loose", ignoreCase: Boolean(o.ignoreCase) };
1945
+ for (const k of keys) {
1946
+ const lt = ls.columns.find((c) => c.name === k.left).type;
1947
+ const rt = rs.columns.find((c) => c.name === k.right).type;
1948
+ const set = (c, t) => (t === "mixed" ? "mixed types" : t);
1949
+ if (lt !== rt && lt !== "null" && rt !== "null" && lt !== "any" && rt !== "any") ctx.note(`Key "${k.left}" is ${set(0, lt)} on the left but "${k.right}" is ${set(0, rt)} on the right${types === "strict" ? ": they never match (types: \"strict\"). Convert one side, or set types: \"loose\"" : ": compared as text (types: \"loose\")"}.`);
1950
+ else if (lt === "mixed" || rt === "mixed") ctx.note(`Key column "${lt === "mixed" ? k.left : k.right}" holds mixed types${types === "strict" ? ": a number and its text never match (types: \"strict\")" : ""}.`);
1951
+ }
1952
+ const isNullKey = (row, side) => keys.some((k) => row[k[side]] === null || row[k[side]] === undefined);
1953
+ const keyFor = (row, side) => keyOf(keys.map((k) => row[k[side]]), kopts);
1954
+ // Index the right side.
1955
+ const index = new Map();
1956
+ const rightDupKeys = new Set();
1957
+ for (let j = 0; j < right.length; j++) {
1958
+ if (ctx.tick()) yield;
1959
+ const r = right[j];
1960
+ if (nulls === "never" && isNullKey(r, "right")) continue;
1961
+ const k = keyFor(r, "right");
1962
+ const list = index.get(k);
1963
+ if (!list) index.set(k, [j]);
1964
+ else {
1965
+ if (dup === "error") throw new TableError("duplicate-key", `join: the right table has the key ${JSON.stringify(keys.map((kk) => r[kk.right]))} more than once (rows ${list[0]} and ${j}); duplicates is "error". Use duplicates: "all", "first" or "last", or group the right table first.`);
1966
+ rightDupKeys.add(k);
1967
+ if (dup === "all") list.push(j);
1968
+ else if (dup === "last") list[0] = j;
1969
+ }
1970
+ }
1971
+ if (rightDupKeys.size) ctx.note(`${rightDupKeys.size} key${rightDupKeys.size === 1 ? " is" : "s are"} repeated in the right table (duplicates: "${dup}")${dup === "all" ? ": matching left rows are repeated once per partner" : dup === "first" ? ": only the first partner is used" : ": only the last partner is used"}.`);
1972
+ // Output columns.
1973
+ const sameKeys = new Set(keys.filter((k) => k.left === k.right).map((k) => k.left));
1974
+ const lcols = o.select?.left ? resolveColumns([...new Set([...keys.map((k) => k.left), ...o.select.left])], ls) : schemaNames(ls);
1975
+ const rcolsAll = o.select?.right ? resolveColumns([...new Set([...keys.map((k) => k.right), ...o.select.right])], rs) : schemaNames(rs);
1976
+ const rcols = rcolsAll.filter((c) => !sameKeys.has(c));
1977
+ const [lsuf, rsuf] = o.suffix ?? ["", "_right"];
1978
+ const lset = new Set(lcols);
1979
+ const rset = new Set(rcols);
1980
+ const lname = (c) => (rset.has(c) && !sameKeys.has(c) ? c + lsuf : c);
1981
+ const rname = (c) => (lset.has(c) ? c + rsuf : c);
1982
+ const outNames = [...lcols.map(lname), ...rcols.map(rname)];
1983
+ if (new Set(outNames).size !== outNames.length) throw new TableError("bad-option", `join: the result would have a duplicate column name (${outNames.filter((n, i) => outNames.indexOf(n) !== i).map((n) => JSON.stringify(n)).join(", ")}). Change \`suffix\`.`);
1984
+ const combine = (l, r) => {
1985
+ const row = {};
1986
+ for (const c of lcols) if (l === null ? sameKeys.has(c) && r && has(r, c) : has(l, c)) row[lname(c)] = l === null ? r[c] : l[c];
1987
+ else if (l === null) row[lname(c)] = null;
1988
+ for (const c of rcols) row[rname(c)] = r === null ? null : has(r, c) ? r[c] : null;
1989
+ return row;
1990
+ };
1991
+ // Probe.
1992
+ const matched = [];
1993
+ const matchedOrigin = ctx.trace ? [] : undefined;
1994
+ const leftOnly = [];
1995
+ const leftOnlyIdx = [];
1996
+ const rightUsed = new Uint8Array(right.length);
1997
+ const pairs = []; // [i, j]
1998
+ for (let i = 0; i < left.length; i++) {
1999
+ if (ctx.tick()) yield;
2000
+ const l = left[i];
2001
+ const list = nulls === "never" && isNullKey(l, "left") ? undefined : index.get(keyFor(l, "left"));
2002
+ if (!list) {
2003
+ leftOnly.push(l);
2004
+ leftOnlyIdx.push(i);
2005
+ continue;
2006
+ }
2007
+ for (const j of list) {
2008
+ if (ctx.tick()) yield;
2009
+ ctx.checkRows(matched.length + 1, "the matched rows");
2010
+ rightUsed[j] = 1;
2011
+ matched.push(combine(l, right[j]));
2012
+ pairs.push([i, j]);
2013
+ if (matchedOrigin) matchedOrigin.push({ left: [i], right: [j] });
2014
+ }
2015
+ }
2016
+ const rightOnly = [];
2017
+ const rightOnlyIdx = [];
2018
+ right.forEach((r, j) => {
2019
+ if (!rightUsed[j]) {
2020
+ rightOnly.push(r);
2021
+ rightOnlyIdx.push(j);
2022
+ }
2023
+ });
2024
+ if (ctx.trace) {
2025
+ if (mode === "inner" || mode === "right") for (const i of leftOnlyIdx) ctx.exclude({ input: "left", kind: "unmatched", reason: nulls === "never" && isNullKey(left[i], "left") ? `its key is null (nulls: "never") and mode is "${mode}"` : `no row on the right has its key and mode is "${mode}"` }, i);
2026
+ if (mode === "inner" || mode === "left") for (const j of rightOnlyIdx) ctx.exclude({ input: "right", kind: "unmatched", reason: nulls === "never" && isNullKey(right[j], "right") ? `its key is null (nulls: "never") and mode is "${mode}"` : `no row on the left has its key and mode is "${mode}"` }, j);
2027
+ }
2028
+ ctx.checkCells(matched.length + leftOnly.length + rightOnly.length, outNames.length);
2029
+ let rows = matched;
2030
+ let origin = matchedOrigin;
2031
+ if (mode === "left" || mode === "full") {
2032
+ // Keep the left table's order: interleave unmatched left rows at their place.
2033
+ const merged = [];
2034
+ const mo = ctx.trace ? [] : undefined;
2035
+ let p = 0;
2036
+ let u = 0;
2037
+ for (let i = 0; i < left.length; i++) {
2038
+ if (ctx.tick()) yield;
2039
+ if (u < leftOnlyIdx.length && leftOnlyIdx[u] === i) {
2040
+ merged.push(combine(left[i], null));
2041
+ mo?.push({ left: [i], right: [] });
2042
+ u++;
2043
+ } else {
2044
+ while (p < pairs.length && pairs[p][0] === i) (merged.push(matched[p]), mo?.push(matchedOrigin[p]), p++);
2045
+ }
2046
+ }
2047
+ rows = merged;
2048
+ origin = mo;
2049
+ } else if (mode === "right") {
2050
+ const byRight = pairs.map((_, k) => k).sort((a, b) => pairs[a][1] - pairs[b][1] || a - b);
2051
+ const merged = [];
2052
+ const mo = ctx.trace ? [] : undefined;
2053
+ const unmatchedAt = new Map(rightOnlyIdx.map((j) => [j, true]));
2054
+ let k = 0;
2055
+ for (let j = 0; j < right.length; j++) {
2056
+ if (ctx.tick()) yield;
2057
+ if (unmatchedAt.has(j)) {
2058
+ merged.push(combine(null, right[j]));
2059
+ mo?.push({ left: [], right: [j] });
2060
+ } else {
2061
+ while (k < byRight.length && pairs[byRight[k]][1] === j) (merged.push(matched[byRight[k]]), mo?.push(matchedOrigin[byRight[k]]), k++);
2062
+ }
2063
+ }
2064
+ rows = merged;
2065
+ origin = mo;
2066
+ }
2067
+ if (mode === "full") {
2068
+ for (const j of rightOnlyIdx) {
2069
+ if (ctx.tick()) yield;
2070
+ rows.push(combine(null, right[j]));
2071
+ origin?.push({ left: [], right: [j] });
2072
+ }
2073
+ }
2074
+ const declared = [...lcols.map((c) => ({ name: lname(c), type: ls.columns.find((x) => x.name === c).type })), ...rcols.map((c) => ({ name: rname(c), type: rs.columns.find((x) => x.name === c).type }))];
2075
+ return { rows, origin, schema: inferSchema(rows, { declared }), matched, leftOnly, rightOnly };
2076
+ },
2077
+ { inputs: ["left", "right"] },
2078
+ );
2079
+
2080
+ /** All operations as functions on `table`: `table.filter(rows, opts)`. */
2081
+ export const select = ops.get("select").run;
2082
+ export const rename = ops.get("rename").run;
2083
+ export const derive = ops.get("derive").run;
2084
+ export const filter = ops.get("filter").run;
2085
+ export const sort = ops.get("sort").run;
2086
+ export const convert = ops.get("convert").run;
2087
+ export const split = ops.get("split").run;
2088
+ export const explode = ops.get("explode").run;
2089
+ export const group = ops.get("group").run;
2090
+ export const pivot = ops.get("pivot").run;
2091
+ export const unpivot = ops.get("unpivot").run;
2092
+ export const join = ops.get("join").run;
2093
+
2094
+ /**
2095
+ * The version of this table API, for packages that need a minimum (`table.version`; a package's
2096
+ * `requires: { helpers: { table: 2 } }`, src/packages/requires.js, which keeps the same number).
2097
+ * 2: `table.async` and `table.runAsync` (CANCELLATION above), the pane-scope `signal`.
2098
+ * 3: dates that aren't ISO 8601 (`convert`'s `from` formats and `timeZone`, `dateHint`, `inferSchema`'s `dateHints`), `profile`'s pane settings.
2099
+ * 4: `profile.starter`, the validation rules proposed from a profile's problems.
2100
+ * 5: quantity columns (`convert`'s type "quantity", a declared "quantity" type, `validate`'s `type: "quantity"`), via the units module.
2101
+ */
2102
+ export const version = 5;