@orangecharts/wrun-chart-host 0.4.0 → 0.5.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 (322) hide show
  1. package/README.md +15 -4
  2. package/dist/constants/exchange-names.leaf.d.ts +8 -0
  3. package/dist/constants/exchange-names.leaf.js +101 -0
  4. package/dist/constants/kscript-data-interval-restrictions.constants.d.ts +15 -0
  5. package/dist/constants/kscript-data-interval-restrictions.constants.js +40 -0
  6. package/dist/constants/opra-compliance.constants.d.ts +19 -0
  7. package/dist/constants/opra-compliance.constants.js +19 -0
  8. package/dist/constants/replay-ladder.leaf.d.ts +30 -0
  9. package/dist/constants/replay-ladder.leaf.js +99 -0
  10. package/dist/constants/scriptEditor/cme-official-scripts.constants.d.ts +168 -0
  11. package/dist/constants/scriptEditor/cme-official-scripts.constants.js +398 -0
  12. package/dist/constants/scriptEditor/converted-script-id.leaf.d.ts +8 -0
  13. package/dist/constants/scriptEditor/converted-script-id.leaf.js +10 -0
  14. package/dist/constants/scriptEditor/execution.constants.d.ts +4 -0
  15. package/dist/constants/scriptEditor/execution.constants.js +14 -0
  16. package/dist/constants/wrun-prefix-safe.constants.d.ts +23 -0
  17. package/dist/constants/wrun-prefix-safe.constants.js +26 -0
  18. package/dist/host-env.d.ts +313 -18
  19. package/dist/host-env.js +15 -0
  20. package/dist/host-ports.types.d.ts +853 -16
  21. package/dist/index.d.ts +139 -2
  22. package/dist/index.js +139 -2
  23. package/dist/instances/script-engine-worker-ohlcv-transfer.d.ts +31 -0
  24. package/dist/instances/script-engine-worker-ohlcv-transfer.js +164 -0
  25. package/dist/interfaces/market-event.interface.d.ts +231 -0
  26. package/dist/interfaces/market-event.interface.js +15 -0
  27. package/dist/interfaces/opra-realtime.interface.d.ts +70 -134
  28. package/dist/interfaces/opra-realtime.interface.js +34 -59
  29. package/dist/interfaces/replay.interface.d.ts +285 -0
  30. package/dist/interfaces/replay.interface.js +1 -0
  31. package/dist/kscript-data/controls/live-ohlcv-merge.util.d.ts +1 -0
  32. package/dist/kscript-data/controls/live-ohlcv-merge.util.js +93 -0
  33. package/dist/kscript-data/controls/live-trades-merge.util.d.ts +5 -1
  34. package/dist/kscript-data/controls/live-trades-merge.util.js +2 -2
  35. package/dist/market-data/billing.interface.d.ts +219 -0
  36. package/dist/market-data/billing.interface.js +58 -0
  37. package/dist/market-data/venue-governed.util.d.ts +2 -0
  38. package/dist/market-data/venue-governed.util.js +10 -0
  39. package/dist/market-data/venue.d.ts +122 -0
  40. package/dist/market-data/venue.js +1 -0
  41. package/dist/market-data/venues/index.d.ts +97 -0
  42. package/dist/market-data/venues/index.js +33 -0
  43. package/dist/market-data/venues/opra.contract.copy.json +35 -0
  44. package/dist/market-data/venues/opra.d.ts +70 -0
  45. package/dist/market-data/venues/opra.js +74 -0
  46. package/dist/replay/replayIndicatorRows.d.ts +31 -0
  47. package/dist/replay/replayIndicatorRows.js +117 -0
  48. package/dist/replay/replayLadder.d.ts +85 -0
  49. package/dist/replay/replayLadder.js +388 -0
  50. package/dist/utility/auth/server-clock.util.d.ts +81 -0
  51. package/dist/utility/auth/server-clock.util.js +238 -0
  52. package/dist/utility/chart/builtin-identity.util.d.ts +18 -0
  53. package/dist/utility/chart/builtin-identity.util.js +51 -0
  54. package/dist/utility/chart/cache-alignment.util.d.ts +454 -0
  55. package/dist/utility/chart/cache-alignment.util.js +926 -0
  56. package/dist/utility/chart/chart-data-fetch-generation.util.d.ts +15 -0
  57. package/dist/utility/chart/chart-data-fetch-generation.util.js +22 -0
  58. package/dist/utility/chart/chart-mount-epoch.util.d.ts +5 -0
  59. package/dist/utility/chart/chart-mount-epoch.util.js +29 -0
  60. package/dist/utility/chart/chart-time-domain.util.d.ts +12 -0
  61. package/dist/utility/chart/chart-time-domain.util.js +23 -0
  62. package/dist/utility/chart/color-customization.leaf.d.ts +10 -0
  63. package/dist/utility/chart/color-customization.leaf.js +16 -0
  64. package/dist/utility/chart/footprint-tick-grid.util.d.ts +106 -0
  65. package/dist/utility/chart/footprint-tick-grid.util.js +167 -0
  66. package/dist/utility/chart/gesture-timing.leaf.d.ts +29 -0
  67. package/dist/utility/chart/gesture-timing.leaf.js +29 -0
  68. package/dist/utility/chart/governed-contract-coin.util.d.ts +22 -0
  69. package/dist/utility/chart/governed-contract-coin.util.js +39 -0
  70. package/dist/utility/chart/host-bar-placement.util.d.ts +107 -0
  71. package/dist/utility/chart/host-bar-placement.util.js +447 -0
  72. package/dist/utility/chart/index-host-tier.util.d.ts +31 -0
  73. package/dist/utility/chart/index-host-tier.util.js +118 -0
  74. package/dist/utility/chart/index-mode-admission.util.d.ts +34 -0
  75. package/dist/utility/chart/index-mode-admission.util.js +67 -0
  76. package/dist/utility/chart/indicator-error-message.util.d.ts +35 -0
  77. package/dist/utility/chart/indicator-error-message.util.js +44 -0
  78. package/dist/utility/chart/kscript-apply-fingerprint.util.d.ts +65 -0
  79. package/dist/utility/chart/kscript-apply-fingerprint.util.js +357 -0
  80. package/dist/utility/chart/kscript-chart-flush.leaf.d.ts +22 -0
  81. package/dist/utility/chart/kscript-chart-flush.leaf.js +13 -0
  82. package/dist/utility/chart/kscript-data-interval-restriction.leaf.d.ts +6 -0
  83. package/dist/utility/chart/kscript-data-interval-restriction.leaf.js +27 -0
  84. package/dist/utility/chart/kscript-integration-decision.leaf.d.ts +89 -0
  85. package/dist/utility/chart/kscript-integration-decision.leaf.js +80 -0
  86. package/dist/utility/chart/kscript-live-coalesce.util.d.ts +76 -0
  87. package/dist/utility/chart/kscript-live-coalesce.util.js +156 -0
  88. package/dist/utility/chart/kscript-live-rest-pace.util.d.ts +34 -0
  89. package/dist/utility/chart/kscript-live-rest-pace.util.js +134 -0
  90. package/dist/utility/chart/kscript-live-source-identity.util.d.ts +98 -0
  91. package/dist/utility/chart/kscript-live-source-identity.util.js +121 -0
  92. package/dist/utility/chart/kscript-mounted-plot-set.leaf.d.ts +48 -0
  93. package/dist/utility/chart/kscript-mounted-plot-set.leaf.js +145 -0
  94. package/dist/utility/chart/kscript-perf-tracker.util.d.ts +243 -0
  95. package/dist/utility/chart/kscript-perf-tracker.util.js +522 -0
  96. package/dist/utility/chart/kscript-run-interval-projection.util.d.ts +43 -0
  97. package/dist/utility/chart/kscript-run-interval-projection.util.js +471 -0
  98. package/dist/utility/chart/kscript-run-result-equality.util.d.ts +38 -0
  99. package/dist/utility/chart/kscript-run-result-equality.util.js +89 -0
  100. package/dist/utility/chart/kscript-settings-revision.leaf.d.ts +2 -0
  101. package/dist/utility/chart/kscript-settings-revision.leaf.js +12 -0
  102. package/dist/utility/chart/kscript-source-degrade.leaf.d.ts +63 -0
  103. package/dist/utility/chart/kscript-source-degrade.leaf.js +68 -0
  104. package/dist/utility/chart/kscript-source-retention.util.d.ts +134 -0
  105. package/dist/utility/chart/kscript-source-retention.util.js +218 -0
  106. package/dist/utility/chart/kscript-standin-identity.leaf.d.ts +57 -0
  107. package/dist/utility/chart/kscript-standin-identity.leaf.js +61 -0
  108. package/dist/utility/chart/kscript-titancharts-preparation.util.d.ts +15 -0
  109. package/dist/utility/chart/kscript-titancharts-preparation.util.js +376 -0
  110. package/dist/utility/chart/kscript-titancharts-render-keys.constants.d.ts +9 -0
  111. package/dist/utility/chart/kscript-titancharts-render-keys.constants.js +130 -0
  112. package/dist/utility/chart/kscript-venue-policy.util.d.ts +217 -0
  113. package/dist/utility/chart/kscript-venue-policy.util.js +324 -0
  114. package/dist/utility/chart/live-cadence.util.d.ts +38 -0
  115. package/dist/utility/chart/live-cadence.util.js +37 -0
  116. package/dist/utility/chart/live-feed-series-match.leaf.d.ts +13 -0
  117. package/dist/utility/chart/live-feed-series-match.leaf.js +21 -0
  118. package/dist/utility/chart/local-engine-self-heal-backoff.util.d.ts +46 -0
  119. package/dist/utility/chart/local-engine-self-heal-backoff.util.js +46 -0
  120. package/dist/utility/chart/local-engine-uninit.leaf.d.ts +21 -0
  121. package/dist/utility/chart/local-engine-uninit.leaf.js +22 -0
  122. package/dist/utility/chart/local-kscript-source-revalidation.util.d.ts +62 -0
  123. package/dist/utility/chart/local-kscript-source-revalidation.util.js +123 -0
  124. package/dist/utility/chart/local-kscript-warmup-depth.util.d.ts +214 -0
  125. package/dist/utility/chart/local-kscript-warmup-depth.util.js +376 -0
  126. package/dist/utility/chart/local-technical-script-live-apply-coalescer.util.d.ts +85 -0
  127. package/dist/utility/chart/local-technical-script-live-apply-coalescer.util.js +197 -0
  128. package/dist/utility/chart/local-technical-script-range.leaf.d.ts +72 -0
  129. package/dist/utility/chart/local-technical-script-range.leaf.js +126 -0
  130. package/dist/utility/chart/mixed-mode.util.d.ts +167 -0
  131. package/dist/utility/chart/mixed-mode.util.js +139 -0
  132. package/dist/utility/chart/ohlcv-row-readiness.util.d.ts +36 -0
  133. package/dist/utility/chart/ohlcv-row-readiness.util.js +90 -0
  134. package/dist/utility/chart/opra-user-scripts-gate.util.d.ts +19 -0
  135. package/dist/utility/chart/opra-user-scripts-gate.util.js +32 -0
  136. package/dist/utility/chart/overlay-execution-guard-key.leaf.d.ts +8 -0
  137. package/dist/utility/chart/overlay-execution-guard-key.leaf.js +10 -0
  138. package/dist/utility/chart/price-precision.util.d.ts +40 -0
  139. package/dist/utility/chart/price-precision.util.js +70 -0
  140. package/dist/utility/chart/profile-block-size.util.d.ts +64 -0
  141. package/dist/utility/chart/profile-block-size.util.js +141 -0
  142. package/dist/utility/chart/protected-kscript-degenerate-rows.leaf.d.ts +11 -0
  143. package/dist/utility/chart/protected-kscript-degenerate-rows.leaf.js +29 -0
  144. package/dist/utility/chart/protected-kscript-empty-output.util.d.ts +28 -0
  145. package/dist/utility/chart/protected-kscript-empty-output.util.js +84 -0
  146. package/dist/utility/chart/run-interval-unservable.leaf.d.ts +9 -0
  147. package/dist/utility/chart/run-interval-unservable.leaf.js +20 -0
  148. package/dist/utility/chart/run-interval-warmup.leaf.d.ts +19 -0
  149. package/dist/utility/chart/run-interval-warmup.leaf.js +35 -0
  150. package/dist/utility/chart/titan-constants.pin.d.ts +9 -5
  151. package/dist/utility/chart/titan-constants.pin.js +18 -5
  152. package/dist/utility/chart/warmup-backfill-retry.leaf.d.ts +9 -0
  153. package/dist/utility/chart/warmup-backfill-retry.leaf.js +9 -0
  154. package/dist/utility/chart/wrun-bar-session-facts.util.d.ts +11 -2
  155. package/dist/utility/chart/wrun-bar-session-facts.util.js +10 -3
  156. package/dist/utility/chart/wrun-run-result.util.d.ts +5 -1
  157. package/dist/utility/chart/wrun-run-result.util.js +20 -14
  158. package/dist/utility/common/data-processing.util.d.ts +138 -0
  159. package/dist/utility/common/data-processing.util.js +346 -0
  160. package/dist/utility/common/visible-timeout.util.d.ts +13 -4
  161. package/dist/utility/common/visible-timeout.util.js +23 -8
  162. package/dist/utility/exchange-format.leaf.d.ts +1 -0
  163. package/dist/utility/exchange-format.leaf.js +47 -0
  164. package/dist/utility/market-events/earnings-scope.util.d.ts +60 -0
  165. package/dist/utility/market-events/earnings-scope.util.js +92 -0
  166. package/dist/utility/market-events/market-events.util.d.ts +147 -0
  167. package/dist/utility/market-events/market-events.util.js +392 -0
  168. package/dist/utility/market-events/zoned-clock.util.d.ts +1 -0
  169. package/dist/utility/market-events/zoned-clock.util.js +11 -0
  170. package/dist/utility/options/option-venue-disclosure.util.d.ts +43 -0
  171. package/dist/utility/options/option-venue-disclosure.util.js +56 -0
  172. package/dist/utility/scriptEditor/package-semver.util.d.ts +51 -0
  173. package/dist/utility/scriptEditor/package-semver.util.js +120 -0
  174. package/dist/utility/scriptEditor/temp-script-id.util.d.ts +18 -0
  175. package/dist/utility/scriptEditor/temp-script-id.util.js +25 -0
  176. package/dist/utility/symbol-selection/markets-request-from-symbols.leaf.d.ts +20 -0
  177. package/dist/utility/symbol-selection/markets-request-from-symbols.leaf.js +81 -0
  178. package/dist/utility/v2/governed-tier.leaf.d.ts +103 -0
  179. package/dist/utility/v2/governed-tier.leaf.js +113 -0
  180. package/dist/utility/watchlist/import/import-request.leaf.d.ts +10 -0
  181. package/dist/utility/watchlist/import/import-request.leaf.js +10 -0
  182. package/dist/utility/wrun/sources/lanes/series.js +2 -2
  183. package/dist/utility/wrun/sources/row-lanes/option_contract_state.d.ts +4 -4
  184. package/dist/utility/wrun/sources/row-lanes/option_contract_state.js +5 -6
  185. package/dist/utility/wrun/wrun-alert-outputs.registry.d.ts +166 -0
  186. package/dist/utility/wrun/wrun-alert-outputs.registry.js +219 -0
  187. package/dist/utility/wrun/wrun-bar-count.util.d.ts +83 -0
  188. package/dist/utility/wrun/wrun-bar-count.util.js +259 -0
  189. package/dist/utility/wrun/wrun-chart-context-names.util.d.ts +84 -0
  190. package/dist/utility/wrun/wrun-chart-context-names.util.js +186 -0
  191. package/dist/utility/wrun/wrun-chart-market-facts.util.d.ts +253 -0
  192. package/dist/utility/wrun/wrun-chart-market-facts.util.js +731 -0
  193. package/dist/utility/wrun/wrun-cloud-opra-stamp.util.d.ts +28 -0
  194. package/dist/utility/wrun/wrun-cloud-opra-stamp.util.js +45 -0
  195. package/dist/utility/wrun/wrun-coin-lane-live.util.d.ts +18 -0
  196. package/dist/utility/wrun/wrun-coin-lane-live.util.js +47 -0
  197. package/dist/utility/wrun/wrun-deadline.util.js +2 -1
  198. package/dist/utility/wrun/wrun-debug-output.util.d.ts +39 -0
  199. package/dist/utility/wrun/wrun-debug-output.util.js +63 -0
  200. package/dist/utility/wrun/wrun-declared-warmup.util.d.ts +113 -0
  201. package/dist/utility/wrun/wrun-declared-warmup.util.js +181 -0
  202. package/dist/utility/wrun/wrun-draft-legend-note.util.d.ts +43 -0
  203. package/dist/utility/wrun/wrun-draft-legend-note.util.js +158 -0
  204. package/dist/utility/wrun/wrun-draft-overlay.util.d.ts +181 -0
  205. package/dist/utility/wrun/wrun-draft-overlay.util.js +357 -0
  206. package/dist/utility/wrun/wrun-draw-skipped.leaf.d.ts +16 -0
  207. package/dist/utility/wrun/wrun-draw-skipped.leaf.js +16 -0
  208. package/dist/utility/wrun/wrun-earnings-facts.util.d.ts +42 -0
  209. package/dist/utility/wrun/wrun-earnings-facts.util.js +131 -0
  210. package/dist/utility/wrun/wrun-first-run-depth.util.d.ts +32 -0
  211. package/dist/utility/wrun/wrun-first-run-depth.util.js +118 -0
  212. package/dist/utility/wrun/wrun-gate-plane-readers.util.d.ts +24 -0
  213. package/dist/utility/wrun/wrun-gate-plane-readers.util.js +31 -0
  214. package/dist/utility/wrun/wrun-held-lanes.util.d.ts +32 -0
  215. package/dist/utility/wrun/wrun-held-lanes.util.js +94 -0
  216. package/dist/utility/wrun/wrun-host-visible-clock.util.d.ts +2 -0
  217. package/dist/utility/wrun/wrun-host-visible-clock.util.js +17 -0
  218. package/dist/utility/wrun/wrun-host.service.d.ts +266 -0
  219. package/dist/utility/wrun/wrun-host.service.js +655 -0
  220. package/dist/utility/wrun/wrun-inert-legend.util.d.ts +33 -0
  221. package/dist/utility/wrun/wrun-inert-legend.util.js +125 -0
  222. package/dist/utility/wrun/wrun-input-requirements.leaf.d.ts +155 -0
  223. package/dist/utility/wrun/wrun-input-requirements.leaf.js +450 -0
  224. package/dist/utility/wrun/wrun-integration-route.util.d.ts +51 -0
  225. package/dist/utility/wrun/wrun-integration-route.util.js +59 -0
  226. package/dist/utility/wrun/wrun-latest-history.leaf.d.ts +8 -0
  227. package/dist/utility/wrun/wrun-latest-history.leaf.js +8 -0
  228. package/dist/utility/wrun/wrun-legend-hover.lazy.d.ts +12 -0
  229. package/dist/utility/wrun/wrun-legend-hover.lazy.js +96 -0
  230. package/dist/utility/wrun/wrun-lifecycle-runtime.util.d.ts +21 -0
  231. package/dist/utility/wrun/wrun-lifecycle-runtime.util.js +21 -0
  232. package/dist/utility/wrun/wrun-live-hidden-hold.util.d.ts +23 -0
  233. package/dist/utility/wrun/wrun-live-hidden-hold.util.js +13 -0
  234. package/dist/utility/wrun/wrun-live-intake.util.d.ts +374 -0
  235. package/dist/utility/wrun/wrun-live-intake.util.js +2027 -0
  236. package/dist/utility/wrun/wrun-live-patch.util.d.ts +116 -0
  237. package/dist/utility/wrun/wrun-live-patch.util.js +523 -0
  238. package/dist/utility/wrun/wrun-live-tick.util.d.ts +619 -0
  239. package/dist/utility/wrun/wrun-live-tick.util.js +4974 -0
  240. package/dist/utility/wrun/wrun-loading-owner.util.d.ts +58 -0
  241. package/dist/utility/wrun/wrun-loading-owner.util.js +89 -0
  242. package/dist/utility/wrun/wrun-official-scope.leaf.d.ts +29 -0
  243. package/dist/utility/wrun/wrun-official-scope.leaf.js +36 -0
  244. package/dist/utility/wrun/wrun-oi-lane.util.d.ts +27 -0
  245. package/dist/utility/wrun/wrun-oi-lane.util.js +42 -0
  246. package/dist/utility/wrun/wrun-options-stop.util.d.ts +52 -0
  247. package/dist/utility/wrun/wrun-options-stop.util.js +123 -0
  248. package/dist/utility/wrun/wrun-overlay-drivers.util.d.ts +719 -0
  249. package/dist/utility/wrun/wrun-overlay-drivers.util.js +1180 -0
  250. package/dist/utility/wrun/wrun-overlay-lifecycle.lazy.d.ts +50 -0
  251. package/dist/utility/wrun/wrun-overlay-lifecycle.lazy.js +131 -0
  252. package/dist/utility/wrun/wrun-overlay-lifecycle.util.d.ts +118 -0
  253. package/dist/utility/wrun/wrun-overlay-lifecycle.util.js +466 -0
  254. package/dist/utility/wrun/wrun-overlay-metadata.util.d.ts +45 -0
  255. package/dist/utility/wrun/wrun-overlay-metadata.util.js +112 -0
  256. package/dist/utility/wrun/wrun-overlay-recovery.util.d.ts +114 -0
  257. package/dist/utility/wrun/wrun-overlay-recovery.util.js +971 -0
  258. package/dist/utility/wrun/wrun-overlay-run.util.d.ts +858 -0
  259. package/dist/utility/wrun/wrun-overlay-run.util.js +11013 -0
  260. package/dist/utility/wrun/wrun-panel-mount.util.d.ts +24 -9
  261. package/dist/utility/wrun/wrun-panel-mount.util.js +138 -43
  262. package/dist/utility/wrun/wrun-param-map.util.d.ts +19 -4
  263. package/dist/utility/wrun/wrun-param-map.util.js +40 -47
  264. package/dist/utility/wrun/wrun-param-values.util.d.ts +9 -3
  265. package/dist/utility/wrun/wrun-param-values.util.js +5 -5
  266. package/dist/utility/wrun/wrun-prefix-cohort.util.d.ts +93 -0
  267. package/dist/utility/wrun/wrun-prefix-cohort.util.js +484 -0
  268. package/dist/utility/wrun/wrun-prefix-lanes.util.d.ts +114 -0
  269. package/dist/utility/wrun/wrun-prefix-lanes.util.js +486 -0
  270. package/dist/utility/wrun/wrun-prefix-proof.util.d.ts +317 -0
  271. package/dist/utility/wrun/wrun-prefix-proof.util.js +630 -0
  272. package/dist/utility/wrun/wrun-refusal-surface.util.d.ts +73 -0
  273. package/dist/utility/wrun/wrun-refusal-surface.util.js +380 -0
  274. package/dist/utility/wrun/wrun-refusal-text.util.d.ts +15 -0
  275. package/dist/utility/wrun/wrun-refusal-text.util.js +40 -0
  276. package/dist/utility/wrun/wrun-replay-lane.util.d.ts +139 -0
  277. package/dist/utility/wrun/wrun-replay-lane.util.js +520 -0
  278. package/dist/utility/wrun/wrun-replay-rows.util.d.ts +21 -0
  279. package/dist/utility/wrun/wrun-replay-rows.util.js +172 -0
  280. package/dist/utility/wrun/wrun-row-source-factory.d.ts +53 -0
  281. package/dist/utility/wrun/wrun-row-source-factory.js +435 -0
  282. package/dist/utility/wrun/wrun-run-cells.util.d.ts +36 -0
  283. package/dist/utility/wrun/wrun-run-cells.util.js +46 -0
  284. package/dist/utility/wrun/wrun-run-interval-session.util.d.ts +133 -0
  285. package/dist/utility/wrun/wrun-run-interval-session.util.js +121 -0
  286. package/dist/utility/wrun/wrun-run-interval.util.d.ts +98 -0
  287. package/dist/utility/wrun/wrun-run-interval.util.js +207 -0
  288. package/dist/utility/wrun/wrun-run-retained.util.d.ts +122 -0
  289. package/dist/utility/wrun/wrun-run-retained.util.js +255 -0
  290. package/dist/utility/wrun/wrun-sandbox-row-source.d.ts +184 -0
  291. package/dist/utility/wrun/wrun-sandbox-row-source.js +444 -0
  292. package/dist/utility/wrun/wrun-script-inputs.util.js +4 -4
  293. package/dist/utility/wrun/wrun-series-stream.util.d.ts +86 -0
  294. package/dist/utility/wrun/wrun-series-stream.util.js +537 -0
  295. package/dist/utility/wrun/wrun-sheet-remembered.util.d.ts +21 -0
  296. package/dist/utility/wrun/wrun-sheet-remembered.util.js +36 -0
  297. package/dist/utility/wrun/wrun-signal-sound-reasons.leaf.d.ts +7 -0
  298. package/dist/utility/wrun/wrun-signal-sound-reasons.leaf.js +12 -0
  299. package/dist/utility/wrun/wrun-socket-row-source.js +4 -2
  300. package/dist/utility/wrun/wrun-source-rows.util.d.ts +175 -3
  301. package/dist/utility/wrun/wrun-source-rows.util.js +294 -8
  302. package/dist/utility/wrun/wrun-stats-strip.util.d.ts +46 -0
  303. package/dist/utility/wrun/wrun-stats-strip.util.js +87 -0
  304. package/dist/utility/wrun/wrun-table-chrome.util.d.ts +163 -0
  305. package/dist/utility/wrun/wrun-table-chrome.util.js +557 -0
  306. package/dist/utility/wrun/wrun-text-params.util.d.ts +11 -6
  307. package/dist/utility/wrun/wrun-text-params.util.js +19 -30
  308. package/dist/utility/wrun/wrun-transient-rerun.util.d.ts +64 -0
  309. package/dist/utility/wrun/wrun-transient-rerun.util.js +317 -0
  310. package/dist/utility/wrun/wrun-twin-lookback.util.d.ts +10 -0
  311. package/dist/utility/wrun/wrun-twin-lookback.util.js +43 -0
  312. package/dist/utility/wrun/wrun-warmup-head-store.util.d.ts +41 -0
  313. package/dist/utility/wrun/wrun-warmup-head-store.util.js +120 -0
  314. package/dist/utility/wrun-alert-params.leaf.d.ts +24 -0
  315. package/dist/utility/wrun-alert-params.leaf.js +24 -0
  316. package/dist/utils/replay/replay-buffer-math.d.ts +148 -0
  317. package/dist/utils/replay/replay-buffer-math.js +684 -0
  318. package/dist/workers/wrun/wrun-abi-host.d.ts +190 -0
  319. package/dist/workers/wrun/wrun-abi-host.js +1201 -0
  320. package/dist/workers/wrun/wrun-engine-handler.d.ts +37 -0
  321. package/dist/workers/wrun/wrun-engine-handler.js +211 -0
  322. package/package.json +3 -3
@@ -0,0 +1,655 @@
1
+ /**
2
+ * Main-thread WRUN host: compiles a package's wasm (sha256-verified against
3
+ * the metadata pin when present), owns the sandbox worker, and runs packed
4
+ * series requests through it. One shared worker serves every dev overlay;
5
+ * requests are id-matched, and a request that outlives its timeout poisons
6
+ * the worker (terminate + respawn) so a spinning guest cannot wedge later
7
+ * runs.
8
+ *
9
+ * Isolation: a death of the shared worker (the run timeout, or an error
10
+ * event with a request in flight) rejects every pending request with
11
+ * `WrunWorkerPoisonError` naming the live sessions lost with it,
12
+ * quarantines the package that was running (its metadata id plus wasm
13
+ * digest) on the kScript self-heal ladder (30 s, doubling per repeat,
14
+ * capped at 5 min) so its next requests refuse at once with
15
+ * `WrunQuarantinedError` instead of killing the worker again, and throttles
16
+ * the respawn to one per window so several spinning packages (or a Retry
17
+ * that overrides the quarantine) cannot kill and respawn the worker on
18
+ * every request. A Retry or a settings save passes `overrideQuarantine`;
19
+ * its success clears the package's quarantine.
20
+ *
21
+ * wrun-3 (Indicator handles): the sheet's `handles` section and the other
22
+ * wrun-3 sheet fields are checked here before every run (the same place the
23
+ * string slots are), the request carries the declared handle defaults and
24
+ * the widened ABI, and the worker's answer carries the handle ledger's live
25
+ * set, which rides beside the rows it belongs to (`attachWrunHandles`) so
26
+ * the run-result adapter picks it up from the rows every integration route
27
+ * already hands it. The run's skipped draw calls (a call one bar's values
28
+ * could not carry, recorded instead of refusing the run) ride the same way
29
+ * (`attachWrunDrawSkips`), for the run's one warning row.
30
+ *
31
+ * wrun-3 (Indicator strategies): a sheet that declares `strategy` is read
32
+ * and resolved here before every run (the om validator's rules, then the
33
+ * shared host's resolver against the instance's params), the request
34
+ * carries the engine's declared config, the chart interval and the broker
35
+ * feed (the primary lane's OHLC per row, `strategyBars`, supplied by the
36
+ * overlay lanes from the chart's own candles), and the worker's answer
37
+ * carries the engine's StrategyOutput, which rides beside the rows
38
+ * (`attachWrunStrategy`) exactly like the handle set.
39
+ */
40
+ import { ensureWrunChartHostSharedHost, wrunChartHostEnv } from '../../host-env.js';
41
+ import { abiAtLeast, attachWrunLive, WrunLiveOrderError, wrunLiveOf } from '../../interfaces/wrun-runtime.interface.js';
42
+ import { LOCAL_ENGINE_SELF_HEAL_RESET_GRACE_MS, localEngineSelfHealDelayMs, } from '../chart/local-engine-self-heal-backoff.util.js';
43
+ import { attachWrunStrategy, readWrunStrategySheet, wrunStrategyParamsOf } from './wrun-box-segment.util.js';
44
+ import { assertWrunSheetAbiCoupling, attachWrunDrawSkips, attachWrunHandles, readWrunHandleDefaults, } from './wrun-handles.util.js';
45
+ import { clampWrunModuleMemory } from './wrun-memory-clamp.util.js';
46
+ import { packWrunRows, unpackWrunResponse, wrunAbiVersion } from './wrun-pack.util.js';
47
+ import { WrunQuarantinedError, WrunWorkerPoisonError } from './wrun-registry-errors.util.js';
48
+ import { bindWrunHostLiveSeriesEnd } from './wrun-overlay-drivers.util.js';
49
+ /** Sources the kit marks daemon-only (`WRUN_DAEMON_ONLY_SOURCES`, a Set of source names; a kit that
50
+ * supplies per-source disclosure wording is a record read by the same key) are computed by the daemon,
51
+ * which owns their dependencies: the first input declaring one refuses the browser run by name. The
52
+ * chart's own candle classes (`ohlcv`, `time`) are served off the chart's rows and never need the kit,
53
+ * so a plain package dispatches synchronously; any other declared class asks the kit (`warm` loads it
54
+ * ahead of the first add). The table is one of the two the run path still reads from the kit: the
55
+ * shared host entry does not export it. */
56
+ export function assertWrunBrowserSources(metadata) {
57
+ const candidates = [];
58
+ for (const input of metadata.inputs) {
59
+ for (const source of [input.source, metadata.inputSources[input.name]?.source]) {
60
+ if (typeof source === 'string' && source !== 'ohlcv' && source !== 'time')
61
+ candidates.push([input.name, source]);
62
+ }
63
+ }
64
+ if (candidates.length === 0)
65
+ return;
66
+ return wrunChartHostEnv()
67
+ .transport.loadWrunKit()
68
+ .then(({ wrunIndicatorKit }) => {
69
+ const daemonOnlySources = wrunIndicatorKit.WRUN_DAEMON_ONLY_SOURCES;
70
+ if (!daemonOnlySources)
71
+ return;
72
+ for (const [name, source] of candidates) {
73
+ const disclosure = typeof daemonOnlySources.has === 'function'
74
+ ? daemonOnlySources.has(source) && 'computed on your daemon, not in the tab'
75
+ : Reflect.get(daemonOnlySources, source);
76
+ if (typeof disclosure === 'string')
77
+ throw new Error(`Input '${name}' (${source}): ${disclosure}`);
78
+ }
79
+ });
80
+ }
81
+ const WRUN_RUN_TIMEOUT_MS = 20_000;
82
+ /** One respawn of the shared worker per window (the kScript shared worker's
83
+ * `restartWithReseedBackoff` rule, sized for this host's 20 s run timeout
84
+ * instead of kScript's 90 s call timeouts): a second death inside the window
85
+ * after a respawn holds the next respawn until the window closes, and every
86
+ * request meanwhile fails fast with the death's poison error. The quarantine
87
+ * below bounds ONE package's deaths geometrically; this window bounds the
88
+ * worker's deaths whatever mix of packages (or overrides) causes them. */
89
+ export const WRUN_WORKER_RESPAWN_WINDOW_MS = 60_000;
90
+ /** `strategyBars` stride: open, high, low, close per row. */
91
+ const STRATEGY_BAR_STRIDE = 4;
92
+ /** How many compiled modules the host keeps by wasm digest (compileModule). Every package version, draft Run
93
+ * and REPL compile mints a digest, and a compiled module is mostly native memory the heap never shows. */
94
+ export const WRUN_MODULE_CACHE_CAPACITY = 16;
95
+ /** The quarantine key of a package: its metadata id plus the wasm digest the
96
+ * metadata pins, so a republished build (new digest) starts clean while every
97
+ * overlay of the same build shares one hold (two charts, two instances: a
98
+ * per-overlay key would let the second instance spin the worker again). An
99
+ * unpinned sheet (dev loader, REPL) keys by id alone. */
100
+ export function wrunHostQuarantineKey(metadata) {
101
+ return metadata.wasm_sha256 ? `${metadata.id}@${metadata.wasm_sha256}` : metadata.id;
102
+ }
103
+ /** The poison rejection every request pending at a death receives. The class
104
+ * is what code reads (`isWrunWorkerPoisonError`); the message keeps the
105
+ * host's own sentences (the culprit's deadline sentence is what the run
106
+ * deadline reader in runtime-diagnostics.util names the trap from, and a
107
+ * worker error's own message is what the legend shows); every rejection of
108
+ * one death carries that death's one context record. */
109
+ function wrunWorkerPoisonError(death, message) {
110
+ const error = new WrunWorkerPoisonError(death.reason, death.casualtySessionKeys, death.context);
111
+ error.message = message;
112
+ return error;
113
+ }
114
+ /** A live tick was asked of a session the worker no longer holds (never
115
+ * started, disposed, dropped after a failed tick, or lost to a worker
116
+ * poison/respawn). Callers rebuild via a fresh full run instead of treating
117
+ * this as a compute error. */
118
+ export class WrunLiveSessionLostError extends Error {
119
+ constructor(message) {
120
+ super(message);
121
+ this.name = 'WrunLiveSessionLostError';
122
+ }
123
+ }
124
+ /** A live tick's block was refused before evaluation because its rows run
125
+ * backwards against the worker session's watermark: the session survives,
126
+ * and the caller reseeds it from its buffers (the worker and the context
127
+ * disagree) instead of retrying the same block. The class is the one the
128
+ * ABI host throws inside the worker (`code: 'live-order'` on the wire). */
129
+ export { WrunLiveOrderError };
130
+ /** The live block accounting rides beside the rows (the registry lives with
131
+ * the wire types); re-exported here for the tick lane's reader. */
132
+ export { attachWrunLive, wrunLiveOf };
133
+ /**
134
+ * Pack a run request for the sheet's ABI. The wrun-3 sheet rules (handles,
135
+ * label position, text style, the strategy section) are checked first,
136
+ * beside the packer's own string-slot checks, so a bad sheet refuses by
137
+ * name before any worker hop; a wrun-3 request also carries the sheet's
138
+ * declared handle defaults and, for a strategy package, the engine config
139
+ * the sheet resolved to (full runs and live starts: the session keeps it)
140
+ * plus the block's broker feed (every block, live ticks included).
141
+ */
142
+ function packWrunRunRequest(metadata, rows, initArgs, strategy, configure, textParams) {
143
+ assertWrunSheetAbiCoupling(metadata);
144
+ const sheet = readWrunStrategySheet(metadata);
145
+ const packed = packWrunRows(metadata, rows, initArgs, textParams);
146
+ if (!abiAtLeast(wrunAbiVersion(metadata), 'wrun-3'))
147
+ return packed;
148
+ // A sheet with no `handles` section sends no defaults: the ledger then refuses every draw call by name
149
+ // (`wrun_draw_kind_undeclared`, style, colour and delete included, the om hosts' rule), where an empty map
150
+ // declares the section with no kind.
151
+ const request = {
152
+ ...packed.request,
153
+ ...(metadata.handles !== undefined ? { handleDefaults: readWrunHandleDefaults(metadata) } : {}),
154
+ };
155
+ if (sheet === undefined)
156
+ return { request, transfer: packed.transfer };
157
+ if (strategy === undefined || strategy.bars.length !== rows.length) {
158
+ throw new Error(`Indicator ${metadata.id}: the strategy feed is missing (${strategy?.bars.length ?? 'no'} bars for ` +
159
+ `${rows.length} rows); a strategy package runs over the primary lane's own candles, one per input row`);
160
+ }
161
+ const strategyBars = new Float64Array(rows.length * STRATEGY_BAR_STRIDE);
162
+ strategy.bars.forEach((bar, row) => {
163
+ const at = row * STRATEGY_BAR_STRIDE;
164
+ strategyBars[at] = bar.open;
165
+ strategyBars[at + 1] = bar.high;
166
+ strategyBars[at + 2] = bar.low;
167
+ strategyBars[at + 3] = bar.close;
168
+ });
169
+ request.strategyBars = strategyBars;
170
+ if (configure) {
171
+ // The shared host's resolver: the engine's defaults, every literal as
172
+ // declared, every param link read from the instance's params with the
173
+ // engine's own value rule (an out-of-range value falls back to the
174
+ // default and is reported, the engine's STRATEGY_INVALID_PARAM_OVERRIDE),
175
+ // and the engine's inert-parameter warnings with the same text.
176
+ const resolution = wrunChartHostEnv()
177
+ .sharedHost()
178
+ .resolveWrunStrategySheet(sheet, {
179
+ params: wrunStrategyParamsOf(metadata, initArgs),
180
+ title: strategy.title ?? metadata.name,
181
+ });
182
+ for (const issue of resolution.issues)
183
+ console.warn(`[wrun] Indicator ${metadata.id}: ${issue.message}`);
184
+ for (const warning of resolution.warnings)
185
+ console.warn(`[wrun] Indicator ${metadata.id}: ${warning.message}`);
186
+ request.strategy = {
187
+ config: resolution.config,
188
+ ...(strategy.intervalMs !== undefined ? { intervalMs: strategy.intervalMs } : {}),
189
+ };
190
+ }
191
+ return { request, transfer: [...packed.transfer, strategyBars.buffer] };
192
+ }
193
+ export class WrunBrowserHost {
194
+ worker = null;
195
+ pending = new Map();
196
+ requestSeq = 0;
197
+ /** Compiles by wasm digest, least recently used first (Map order: a hit moves its entry to the end). The cache
198
+ * only dedupes compiles and owns no module: a mounted overlay keeps the module it was handed (its record), and
199
+ * a live session keeps its instance in the worker (live ticks name the session, never a module), so an
200
+ * eviction stops neither. */
201
+ moduleCache = new Map();
202
+ /** Live sessions the current worker holds (installed by an ok live-start,
203
+ * dropped by live-end, a sessionLost answer, or the worker's death). */
204
+ liveSessionKeys = new Set();
205
+ /** The epoch (live context generation) of the newest live-start dispatched per session key: an end naming
206
+ * another epoch leaves the key's bookkeeping to that newer start. */
207
+ liveStartEpochs = new Map();
208
+ /** Quarantined packages by key; a record outlives its hold by the ladder's
209
+ * reset grace so a repeat death escalates (pruned on the next death). */
210
+ quarantines = new Map();
211
+ lastDeath = null;
212
+ /** When the worker was last spawned AFTER a death (a respawn); null until
213
+ * the first death, so the first spawn ever never opens a window. */
214
+ lastRespawnAt = null;
215
+ respawnHeldUntil = 0;
216
+ /** Spin the sandbox worker and load the shared host (the compile's module
217
+ * rewrite, the packer, the strategy resolver) and the authoring kit (the
218
+ * run path's two kit tables, the daemon-only sources and the token
219
+ * names) ahead of the first add (the Indicators tab opening is the
220
+ * signal), so the first package a reader mounts pays neither the worker
221
+ * spawn nor a module parse on its click. Idempotent; a load failure
222
+ * surfaces on the first compile or run as before, never here. A held
223
+ * respawn is not warmed around: the window exists to keep the worker
224
+ * down. */
225
+ warm() {
226
+ if (this.respawnHold() === null)
227
+ this.ensureWorker();
228
+ void wrunChartHostEnv()
229
+ .loadSharedHost()
230
+ .catch(() => undefined);
231
+ void wrunChartHostEnv()
232
+ .transport.loadWrunKit()
233
+ .catch(() => undefined);
234
+ }
235
+ /** The active quarantine of a package, if its hold is still running. */
236
+ quarantineOf(metadata) {
237
+ const record = this.quarantines.get(wrunHostQuarantineKey(metadata));
238
+ return record !== undefined && Date.now() < record.until ? record : undefined;
239
+ }
240
+ /** Forget every quarantine and the respawn window (specs only). */
241
+ resetGuardsForTests() {
242
+ this.quarantines.clear();
243
+ this.lastDeath = null;
244
+ this.lastRespawnAt = null;
245
+ this.respawnHeldUntil = 0;
246
+ }
247
+ /** Compile (and cache) a package module. The cache key is the sha256 of
248
+ * the bytes, so identical bytes compile once whatever package name they
249
+ * arrive under. When the metadata pins `wasm_sha256`, a mismatch refuses
250
+ * before compilation; so does a memory the clamp refuses (a maximum or a
251
+ * starting size over the worker's memory limit, shared or 64-bit memory),
252
+ * and a memory declared with no maximum compiles with the limit as its
253
+ * maximum (clampWrunModuleMemory).
254
+ *
255
+ * The cache is an LRU of WRUN_MODULE_CACHE_CAPACITY compiled modules.
256
+ * Every consumer of a digest in flight shares its one compile, and a
257
+ * compile in flight is never evicted; eviction drops compiled entries
258
+ * only, least recently used first, so the cache passes the capacity
259
+ * only while more compiles than that are in flight. A failed compile is
260
+ * not cached: its entry leaves before its consumers see the failure, and
261
+ * the next request compiles again. */
262
+ async compileModule(wasmBytes, metadata) {
263
+ const digest = await sha256Hex(wasmBytes);
264
+ if (metadata.wasm_sha256 && metadata.wasm_sha256 !== digest) {
265
+ throw new Error(`WRUN ${metadata.id}: wasm sha256 mismatch (metadata pins ${metadata.wasm_sha256}, bytes are ${digest})`);
266
+ }
267
+ let entry = this.moduleCache.get(digest);
268
+ if (entry) {
269
+ // A hit is the most recent use: set again below, at the end of the order eviction reads from the front.
270
+ this.moduleCache.delete(digest);
271
+ }
272
+ else {
273
+ // Clamp-at-load: the worker checks the memory only after a guest call
274
+ // returns, so a memory with no maximum let one onBar() take hundreds
275
+ // of MB first. With the limit stamped as the maximum, the engine
276
+ // refuses the growth inside the call (the guest traps). A refusal
277
+ // throws here, before anything is cached, like the sha mismatch.
278
+ const bounded = clampWrunModuleMemory(new Uint8Array(wasmBytes));
279
+ // The module the worker instantiates exports every mutable global
280
+ // under __wrun_g<index> so the live lane's snapshot/restore covers the
281
+ // module's counters beside its memory (a compiler keeps top-level
282
+ // scalars in globals; a memory-only restore left them post-row and a
283
+ // same-bar or close-confirm re-evaluation then read stale state).
284
+ // Identity (the sha pin above, the cache key) stays over the original
285
+ // bytes; only the memory and export sections change. The rewriter is
286
+ // the shared host's `prepareModuleBytes` (the same rewrite under every
287
+ // ABI), loaded at the first compile and never on chart boot: this host
288
+ // sits on the chart's startup graph through the driver registry, and a
289
+ // viewer who never mounts an Indicator must not pay for host.js.
290
+ const abi = wrunAbiVersion(metadata);
291
+ const created = {
292
+ compiled: false,
293
+ module: wrunChartHostEnv()
294
+ .loadSharedHost()
295
+ .then(({ prepareModuleBytes }) => WebAssembly.compile(prepareModuleBytes(bounded, abi)))
296
+ .then((module) => {
297
+ created.compiled = true;
298
+ this.trimModuleCache();
299
+ return module;
300
+ }, (error) => {
301
+ if (this.moduleCache.get(digest) === created)
302
+ this.moduleCache.delete(digest);
303
+ throw error;
304
+ }),
305
+ };
306
+ entry = created;
307
+ }
308
+ this.moduleCache.set(digest, entry);
309
+ this.trimModuleCache();
310
+ return entry.module;
311
+ }
312
+ /** Evict compiled entries, least recently used first, until the cache is back at its capacity (a compile
313
+ * in flight stays: its consumers share it). */
314
+ trimModuleCache() {
315
+ for (const [digest, entry] of this.moduleCache) {
316
+ if (this.moduleCache.size <= WRUN_MODULE_CACHE_CAPACITY)
317
+ return;
318
+ if (entry.compiled)
319
+ this.moduleCache.delete(digest);
320
+ }
321
+ }
322
+ async runSeries(input) {
323
+ const lane = this.admit(input.metadata, input.overrideQuarantine);
324
+ const sourceCheck = assertWrunBrowserSources(input.metadata);
325
+ if (sourceCheck)
326
+ await sourceCheck;
327
+ // The packer and the strategy resolver read the shared host (loaded once, off the boot graph;
328
+ // a loaded host adds no await, so a warm run dispatches in the same task as before).
329
+ const hostLoading = ensureWrunChartHostSharedHost();
330
+ if (hostLoading)
331
+ await hostLoading;
332
+ const { request: packed, transfer } = packWrunRunRequest(input.metadata, input.rows, input.initArgs, input.strategy, true, input.textParams);
333
+ const id = ++this.requestSeq;
334
+ const request = {
335
+ id,
336
+ module: input.module,
337
+ mode: input.mode ?? 'historical',
338
+ ...packed,
339
+ };
340
+ const response = await this.dispatch(request, transfer, lane);
341
+ return this.unpack(response, input.metadata, input.rows);
342
+ }
343
+ /** Full run that also opens (or replaces) a live forming-bar session under
344
+ * `sessionKey` in the worker: the guest stays instantiated, so later
345
+ * `runLiveRows` ticks execute only the new/revised rows. `epoch` is the
346
+ * live context generation opening the session: the worker installs the
347
+ * session only while that epoch is still the newest it has seen for the
348
+ * key (see the worker's ownership rule). */
349
+ async startLiveSeries(input) {
350
+ const lane = this.admit(input.metadata, input.overrideQuarantine);
351
+ const sourceCheck = assertWrunBrowserSources(input.metadata);
352
+ if (sourceCheck)
353
+ await sourceCheck;
354
+ // The packer and the strategy resolver read the shared host (loaded once, off the boot graph;
355
+ // a loaded host adds no await, so a warm run dispatches in the same task as before).
356
+ const hostLoading = ensureWrunChartHostSharedHost();
357
+ if (hostLoading)
358
+ await hostLoading;
359
+ const { request: packed, transfer } = packWrunRunRequest(input.metadata, input.rows, input.initArgs, input.strategy, true, input.textParams);
360
+ const id = ++this.requestSeq;
361
+ if (input.epoch !== undefined)
362
+ this.liveStartEpochs.set(input.sessionKey, input.epoch);
363
+ else
364
+ this.liveStartEpochs.delete(input.sessionKey);
365
+ const request = {
366
+ kind: 'live-start',
367
+ sessionKey: input.sessionKey,
368
+ id,
369
+ module: input.module,
370
+ mode: 'live',
371
+ ...(input.epoch !== undefined ? { epoch: input.epoch } : {}),
372
+ ...packed,
373
+ };
374
+ const response = await this.dispatch(request, transfer, {
375
+ ...lane,
376
+ session: { key: input.sessionKey, opens: true },
377
+ });
378
+ return this.unpack(response, input.metadata, input.rows);
379
+ }
380
+ /** One live tick: evaluate only `rows` (the new/revised forming-bar rows)
381
+ * on the open session. Rejects with WrunLiveSessionLostError when the
382
+ * worker no longer holds the session. A wrun-3 session answers the
383
+ * handle ledger's FULL live set with every tick (the wire replaces the
384
+ * drawing set wholesale), attached to the returned rows; a strategy
385
+ * session likewise answers the whole StrategyOutput after the tick (the
386
+ * broker config rides the session, only the rows' broker feed ships). */
387
+ async runLiveRows(input) {
388
+ const lane = this.admit(input.metadata, input.overrideQuarantine);
389
+ const sourceCheck = assertWrunBrowserSources(input.metadata);
390
+ if (sourceCheck)
391
+ await sourceCheck;
392
+ // The packer and the strategy resolver read the shared host (loaded once, off the boot graph;
393
+ // a loaded host adds no await, so a warm run dispatches in the same task as before).
394
+ const hostLoading = ensureWrunChartHostSharedHost();
395
+ if (hostLoading)
396
+ await hostLoading;
397
+ // initArgs ride the session (init already ran); pack an empty block.
398
+ const { request: packed, transfer } = packWrunRunRequest(input.metadata, input.rows, [], input.strategy, false);
399
+ const id = ++this.requestSeq;
400
+ const request = {
401
+ kind: 'live-rows',
402
+ sessionKey: input.sessionKey,
403
+ id,
404
+ rowCount: packed.rowCount,
405
+ stride: packed.stride,
406
+ ts: packed.ts,
407
+ argCounts: packed.argCounts,
408
+ values: packed.values,
409
+ cellIndexes: packed.cellIndexes,
410
+ cellLens: packed.cellLens,
411
+ cellOffsets: packed.cellOffsets,
412
+ cells: packed.cells,
413
+ ...(packed.strategyBars !== undefined ? { strategyBars: packed.strategyBars } : {}),
414
+ };
415
+ const response = await this.dispatch(request, transfer, {
416
+ ...lane,
417
+ session: { key: input.sessionKey, opens: false },
418
+ });
419
+ return this.unpack(response, input.metadata, input.rows);
420
+ }
421
+ /** Dispose one live session. Fire-and-forget: nothing to await, and a
422
+ * worker that is not running holds no sessions to dispose. With `epoch`
423
+ * (the live context generation that opened it), only that generation's
424
+ * session and start: the worker judges, it knows which epoch installed
425
+ * (a run ending what it opened never ends a newer owner's session under
426
+ * the same key). Without, whatever the key holds (the teardown). */
427
+ endLiveSeries(sessionKey, epoch) {
428
+ if (epoch === undefined || this.liveStartEpochs.get(sessionKey) === epoch) {
429
+ this.liveSessionKeys.delete(sessionKey);
430
+ this.liveStartEpochs.delete(sessionKey);
431
+ for (const entry of this.pending.values())
432
+ if (entry.session?.key === sessionKey)
433
+ entry.session = undefined;
434
+ }
435
+ if (!this.worker)
436
+ return;
437
+ const request = {
438
+ kind: 'live-end',
439
+ id: ++this.requestSeq,
440
+ sessionKey,
441
+ ...(epoch !== undefined ? { epoch } : {}),
442
+ };
443
+ // No pending entry: the ok response for an untracked id is ignored by
444
+ // the onmessage handler, and a failure to dispose is indistinguishable
445
+ // from a worker respawn (both drop the session).
446
+ this.worker.postMessage(request);
447
+ }
448
+ destroy() {
449
+ this.failAllPending(new Error('WRUN host destroyed'));
450
+ this.liveSessionKeys.clear();
451
+ this.worker?.terminate();
452
+ this.worker = null;
453
+ }
454
+ /** Unpack the rows against the caller's axis and hang the handle set, the
455
+ * run's skipped draw calls, the strategy output and the live block
456
+ * accounting (when the worker answered them) on that rows array. */
457
+ unpack(response, metadata, rows) {
458
+ const unpacked = unpackWrunResponse(response,
459
+ // The request's ts buffer was transferred with the request; re-derive
460
+ // the axis from the caller's rows, which the response is aligned to.
461
+ rows.map((row) => row.ts), metadata.outputs.length, metadata.string_slots?.length ?? 0);
462
+ if (response.handles !== undefined)
463
+ attachWrunHandles(unpacked, response.handles);
464
+ if (response.skipped !== undefined) {
465
+ attachWrunDrawSkips(unpacked, { skipped: response.skipped, skippedCount: response.skippedCount ?? 0 });
466
+ }
467
+ if (response.strategy !== undefined)
468
+ attachWrunStrategy(unpacked, response.strategy);
469
+ if (response.live !== undefined)
470
+ attachWrunLive(unpacked, response.live);
471
+ return unpacked;
472
+ }
473
+ /** The quarantine gate every request passes before any packing or worker
474
+ * hop: a quarantined package refuses at once (nothing posted, no worker
475
+ * spawned) unless the caller overrides. The refusal carries the death's
476
+ * reason and the package's strikes (the heal ladder reads them). Returns
477
+ * the lane the pending entry remembers. */
478
+ admit(metadata, overrideQuarantine) {
479
+ const quarantineKey = wrunHostQuarantineKey(metadata);
480
+ const quarantine = overrideQuarantine ? undefined : this.quarantineOf(metadata);
481
+ if (quarantine) {
482
+ throw new WrunQuarantinedError(quarantineKey, quarantine.until, quarantine.reason, quarantine.strikes);
483
+ }
484
+ return { quarantineKey, overrideQuarantine: overrideQuarantine === true };
485
+ }
486
+ dispatch(request, transfer, lane) {
487
+ const held = this.respawnHold();
488
+ if (held)
489
+ return Promise.reject(held);
490
+ const worker = this.ensureWorker();
491
+ return new Promise((resolve, reject) => {
492
+ // A run that never answers means the guest is spinning; the worker is
493
+ // poisoned and replaced so later runs start clean.
494
+ const timer = setTimeout(() => this.poisonWorker('timeout', 'WRUN worker terminated after a timed-out run', request.id), WRUN_RUN_TIMEOUT_MS);
495
+ this.pending.set(request.id, { ...lane, resolve, reject, timer });
496
+ worker.postMessage(request, transfer);
497
+ });
498
+ }
499
+ ensureWorker() {
500
+ if (this.worker)
501
+ return this.worker;
502
+ // A spawn after a death is a respawn: it opens the window a second
503
+ // death must stay out of.
504
+ if (this.lastDeath !== null)
505
+ this.lastRespawnAt = Date.now();
506
+ // The host's engine port spawns the sandbox worker (web: the worker factory, with the worker script's URL and
507
+ // the factory's failure source, both the app's), synchronously, as the host's own call did.
508
+ this.worker = wrunChartHostEnv().engine.spawnWorker({
509
+ // The sandbox worker posts no handshake: any message proves it up. No ready deadline: the run
510
+ // timeout, the quarantine and the respawn window own this worker's liveness.
511
+ readiness: { mode: 'first-message' },
512
+ onMessage: (event) => {
513
+ const response = event.data;
514
+ const pending = this.pending.get(response.id);
515
+ if (!pending)
516
+ return;
517
+ this.pending.delete(response.id);
518
+ clearTimeout(pending.timer);
519
+ const { session } = pending;
520
+ if (response.ok) {
521
+ // The package answered: an overridden quarantine is cleared by the
522
+ // success, and an opened session is one the worker now holds.
523
+ if (pending.overrideQuarantine)
524
+ this.quarantines.delete(pending.quarantineKey);
525
+ if (session?.opens)
526
+ this.liveSessionKeys.add(session.key);
527
+ pending.resolve(response);
528
+ }
529
+ else if (response.sessionLost) {
530
+ if (session)
531
+ this.liveSessionKeys.delete(session.key);
532
+ pending.reject(new WrunLiveSessionLostError(response.error));
533
+ }
534
+ else if (response.code === 'live-order')
535
+ pending.reject(new WrunLiveOrderError(response.error));
536
+ else {
537
+ // A failed tick drops its session in the worker; a failed start
538
+ // never replaces the session already open under its key.
539
+ if (session && !session.opens)
540
+ this.liveSessionKeys.delete(session.key);
541
+ pending.reject(new Error(response.error));
542
+ }
543
+ },
544
+ // A worker-level error (a script or module chunk that would not load, an
545
+ // uncaught throw in the worker script) leaves the Worker unable to answer
546
+ // anything: keep it installed and every later run would post into a void
547
+ // and only settle at the 20s timeout. The factory already terminated it
548
+ // (and beaconed a script that would not load, naming the worker file);
549
+ // mirror the timeout path: poison it now so the next run respawns a clean
550
+ // worker and this failure fails fast. A replaced or terminated
551
+ // incarnation's late events reach nobody, so a late one is never another
552
+ // death.
553
+ onDead: (death) => this.poisonWorker('worker-error', death.message || 'WRUN worker error'),
554
+ });
555
+ return this.worker;
556
+ }
557
+ /**
558
+ * The shared worker died: quarantine the package that was running (the
559
+ * timed-out request's, or the oldest in flight when the error event fired, the
560
+ * worker answers in dispatch order), terminate the worker, remember the
561
+ * death for the respawn window, and reject every pending request with the
562
+ * poison error naming the live sessions lost with the worker. Nothing in
563
+ * flight means nothing to quarantine (a worker that dies idle is only a
564
+ * death for the window). `message` is what every casualty reads; the
565
+ * timed-out request keeps its own deadline sentence. The death's context
566
+ * (cause, the culprit's package and session, the budget a timeout used up)
567
+ * is recorded here once, frozen, and rides every rejection of this death,
568
+ * the respawn hold's included, so a casualty can name who held the sandbox.
569
+ */
570
+ poisonWorker(reason, message, culpritId) {
571
+ const now = Date.now();
572
+ const culprit = culpritId !== undefined ? this.pending.get(culpritId) : this.pending.values().next().value;
573
+ if (culprit !== undefined)
574
+ this.quarantine(culprit.quarantineKey, reason, now);
575
+ const casualties = new Set(this.liveSessionKeys);
576
+ for (const entry of this.pending.values())
577
+ if (entry.session)
578
+ casualties.add(entry.session.key);
579
+ const casualtySessionKeys = [...casualties];
580
+ this.liveSessionKeys.clear();
581
+ this.worker?.terminate();
582
+ this.worker = null;
583
+ const kind = reason === 'timeout' || reason === 'worker-error' ? reason : 'unknown';
584
+ const context = Object.freeze({
585
+ kind,
586
+ ...(culprit !== undefined ? { quarantineKey: culprit.quarantineKey } : {}),
587
+ ...(culprit?.session !== undefined ? { sessionKey: culprit.session.key } : {}),
588
+ // The run clock starts at dispatch: the budget bounds the hold, not the execution.
589
+ ...(kind === 'timeout' ? { heldMs: WRUN_RUN_TIMEOUT_MS } : {}),
590
+ at: now,
591
+ });
592
+ const death = { reason, casualtySessionKeys, message, context };
593
+ this.lastDeath = death;
594
+ if (this.lastRespawnAt !== null && now - this.lastRespawnAt < WRUN_WORKER_RESPAWN_WINDOW_MS) {
595
+ this.respawnHeldUntil = this.lastRespawnAt + WRUN_WORKER_RESPAWN_WINDOW_MS;
596
+ }
597
+ for (const [id, entry] of this.pending) {
598
+ clearTimeout(entry.timer);
599
+ const own = reason === 'timeout' && id === culpritId ? `WRUN run ${id} timed out after ${WRUN_RUN_TIMEOUT_MS}ms` : message;
600
+ entry.reject(wrunWorkerPoisonError(death, own));
601
+ }
602
+ this.pending.clear();
603
+ }
604
+ /** Put (or keep) a package on the ladder: a death while its previous hold
605
+ * runs, or inside the reset grace after it, is a repeat and doubles the
606
+ * hold (capped); a later death starts over at the base hold. Records past
607
+ * the grace are forgotten here. */
608
+ quarantine(key, reason, now) {
609
+ for (const [staleKey, record] of this.quarantines) {
610
+ if (now - record.until >= LOCAL_ENGINE_SELF_HEAL_RESET_GRACE_MS)
611
+ this.quarantines.delete(staleKey);
612
+ }
613
+ const strikes = (this.quarantines.get(key)?.strikes ?? 0) + 1;
614
+ this.quarantines.set(key, { key, until: now + localEngineSelfHealDelayMs(strikes), reason, strikes });
615
+ }
616
+ /** The rejection a request gets while the respawn is held: the last death's
617
+ * poison error (its casualties are still unrebuilt, no worker ran since,
618
+ * and it carries that death's context), marked as held. Null when a worker
619
+ * runs or the window has closed. */
620
+ respawnHold() {
621
+ if (this.worker !== null || this.lastDeath === null || Date.now() >= this.respawnHeldUntil)
622
+ return null;
623
+ return wrunWorkerPoisonError(this.lastDeath, `${this.lastDeath.message} (respawn held)`);
624
+ }
625
+ failAllPending(error) {
626
+ for (const pending of this.pending.values()) {
627
+ clearTimeout(pending.timer);
628
+ pending.reject(error);
629
+ }
630
+ this.pending.clear();
631
+ }
632
+ }
633
+ let sharedHost = null;
634
+ export function getWrunBrowserHost() {
635
+ sharedHost ??= new WrunBrowserHost();
636
+ return sharedHost;
637
+ }
638
+ // The overlay teardown ends a live series through this (wrun-overlay-drivers.util keeps no import
639
+ // of the host): bound as the host evaluates, before its worker can open a session. A spec that
640
+ // mocks the drivers util partially has no binder (reading a missing export of a mocked module
641
+ // throws at access time), so the bind is skipped there rather than failing the import.
642
+ try {
643
+ bindWrunHostLiveSeriesEnd((sessionKey) => getWrunBrowserHost().endLiveSeries(sessionKey));
644
+ }
645
+ catch {
646
+ // partial module mock (specs): no teardown door to bind
647
+ }
648
+ /** Clear the shared host's quarantines and respawn window between specs. */
649
+ export function __resetWrunBrowserHostGuardsForTests() {
650
+ sharedHost?.resetGuardsForTests();
651
+ }
652
+ async function sha256Hex(bytes) {
653
+ const digest = await crypto.subtle.digest('SHA-256', bytes);
654
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
655
+ }