@orangecharts/wrun-chart-host 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 (198) hide show
  1. package/README.md +72 -0
  2. package/dist/constants/governed-exchanges.constants.d.ts +11 -0
  3. package/dist/constants/governed-exchanges.constants.js +11 -0
  4. package/dist/constants/indicator-sets.constants.d.ts +8 -0
  5. package/dist/constants/indicator-sets.constants.js +8 -0
  6. package/dist/constants/interval.constants.d.ts +34 -0
  7. package/dist/constants/interval.constants.js +121 -0
  8. package/dist/constants/scriptEditor/technicalIndicatorScriptKeys.constants.d.ts +28 -0
  9. package/dist/constants/scriptEditor/technicalIndicatorScriptKeys.constants.js +65 -0
  10. package/dist/constants/tpo-color-schemes.constants.d.ts +30 -0
  11. package/dist/constants/tpo-color-schemes.constants.js +32 -0
  12. package/dist/host-env.d.ts +102 -0
  13. package/dist/host-env.js +26 -0
  14. package/dist/index.d.ts +93 -0
  15. package/dist/index.js +96 -0
  16. package/dist/indicators/controls/tpo-letter.util.d.ts +2 -0
  17. package/dist/indicators/controls/tpo-letter.util.js +13 -0
  18. package/dist/indicators/controls/tpo-session.util.d.ts +99 -0
  19. package/dist/indicators/controls/tpo-session.util.js +389 -0
  20. package/dist/interfaces/kscript-diagnostics.interface.d.ts +64 -0
  21. package/dist/interfaces/kscript-diagnostics.interface.js +1 -0
  22. package/dist/interfaces/om-panel-data.interface.d.ts +103 -0
  23. package/dist/interfaces/om-panel-data.interface.js +7 -0
  24. package/dist/interfaces/wrun-runtime.interface.d.ts +2659 -0
  25. package/dist/interfaces/wrun-runtime.interface.js +55 -0
  26. package/dist/utility/chart/calendar-interval.util.d.ts +24 -0
  27. package/dist/utility/chart/calendar-interval.util.js +81 -0
  28. package/dist/utility/chart/candle-bar-end.util.d.ts +15 -0
  29. package/dist/utility/chart/candle-bar-end.util.js +23 -0
  30. package/dist/utility/chart/cme-realtime.util.d.ts +24 -0
  31. package/dist/utility/chart/cme-realtime.util.js +53 -0
  32. package/dist/utility/chart/interval-ladder.util.d.ts +27 -0
  33. package/dist/utility/chart/interval-ladder.util.js +92 -0
  34. package/dist/utility/chart/kscript-drawing-prep.util.d.ts +40 -0
  35. package/dist/utility/chart/kscript-drawing-prep.util.js +184 -0
  36. package/dist/utility/chart/kscript-drawing-safe-area.util.d.ts +95 -0
  37. package/dist/utility/chart/kscript-drawing-safe-area.util.js +805 -0
  38. package/dist/utility/chart/kscript-legend-entries.util.d.ts +166 -0
  39. package/dist/utility/chart/kscript-legend-entries.util.js +538 -0
  40. package/dist/utility/chart/kscript-output-role.util.d.ts +32 -0
  41. package/dist/utility/chart/kscript-output-role.util.js +215 -0
  42. package/dist/utility/chart/kscript-provenance-keys.util.d.ts +22 -0
  43. package/dist/utility/chart/kscript-provenance-keys.util.js +56 -0
  44. package/dist/utility/chart/kscript-run-result-normalize.util.d.ts +53 -0
  45. package/dist/utility/chart/kscript-run-result-normalize.util.js +476 -0
  46. package/dist/utility/chart/kscript-run-result-shape.util.d.ts +14 -0
  47. package/dist/utility/chart/kscript-run-result-shape.util.js +66 -0
  48. package/dist/utility/chart/kscript-titancharts-container.util.d.ts +29 -0
  49. package/dist/utility/chart/kscript-titancharts-container.util.js +151 -0
  50. package/dist/utility/chart/kscript-viewport-overlays.util.d.ts +83 -0
  51. package/dist/utility/chart/kscript-viewport-overlays.util.js +443 -0
  52. package/dist/utility/chart/om-panel-push-style.util.d.ts +78 -0
  53. package/dist/utility/chart/om-panel-push-style.util.js +301 -0
  54. package/dist/utility/chart/om-panel.util.d.ts +166 -0
  55. package/dist/utility/chart/om-panel.util.js +815 -0
  56. package/dist/utility/chart/om-series.util.d.ts +42 -0
  57. package/dist/utility/chart/om-series.util.js +330 -0
  58. package/dist/utility/chart/om-target.util.d.ts +11 -0
  59. package/dist/utility/chart/om-target.util.js +24 -0
  60. package/dist/utility/chart/om-widget.util.d.ts +148 -0
  61. package/dist/utility/chart/om-widget.util.js +413 -0
  62. package/dist/utility/chart/overlay-output-budget.util.d.ts +16 -0
  63. package/dist/utility/chart/overlay-output-budget.util.js +109 -0
  64. package/dist/utility/chart/overlay-paint-flags.util.d.ts +24 -0
  65. package/dist/utility/chart/overlay-paint-flags.util.js +55 -0
  66. package/dist/utility/chart/profile-row-height.util.d.ts +21 -0
  67. package/dist/utility/chart/profile-row-height.util.js +110 -0
  68. package/dist/utility/chart/session-interval.util.d.ts +1 -0
  69. package/dist/utility/chart/session-interval.util.js +35 -0
  70. package/dist/utility/chart/technical-script-legend-value.util.d.ts +18 -0
  71. package/dist/utility/chart/technical-script-legend-value.util.js +53 -0
  72. package/dist/utility/chart/trading-day.util.d.ts +70 -0
  73. package/dist/utility/chart/trading-day.util.js +238 -0
  74. package/dist/utility/chart/wrun-legend-name.util.d.ts +25 -0
  75. package/dist/utility/chart/wrun-legend-name.util.js +87 -0
  76. package/dist/utility/chart/wrun-run-result.util.d.ts +977 -0
  77. package/dist/utility/chart/wrun-run-result.util.js +5179 -0
  78. package/dist/utility/chart/wrun-visibility-chart.util.d.ts +25 -0
  79. package/dist/utility/chart/wrun-visibility-chart.util.js +22 -0
  80. package/dist/utility/indicators/heatmap-sensitivity.util.d.ts +62 -0
  81. package/dist/utility/indicators/heatmap-sensitivity.util.js +82 -0
  82. package/dist/utility/number-format.util.d.ts +68 -0
  83. package/dist/utility/number-format.util.js +188 -0
  84. package/dist/utility/v2/opra-governed.util.d.ts +1 -0
  85. package/dist/utility/v2/opra-governed.util.js +13 -0
  86. package/dist/utility/wrun/wrun-auto-row.util.d.ts +54 -0
  87. package/dist/utility/wrun/wrun-auto-row.util.js +96 -0
  88. package/dist/utility/wrun/wrun-batched-marks.util.d.ts +341 -0
  89. package/dist/utility/wrun/wrun-batched-marks.util.js +938 -0
  90. package/dist/utility/wrun/wrun-batched-readout.util.d.ts +75 -0
  91. package/dist/utility/wrun/wrun-batched-readout.util.js +171 -0
  92. package/dist/utility/wrun/wrun-box-segment.util.d.ts +185 -0
  93. package/dist/utility/wrun/wrun-box-segment.util.js +570 -0
  94. package/dist/utility/wrun/wrun-build-memo.util.d.ts +133 -0
  95. package/dist/utility/wrun/wrun-build-memo.util.js +301 -0
  96. package/dist/utility/wrun/wrun-builtin-twin-ports.util.d.ts +25 -0
  97. package/dist/utility/wrun/wrun-builtin-twin-ports.util.js +75 -0
  98. package/dist/utility/wrun/wrun-builtin-twin.util.d.ts +9 -0
  99. package/dist/utility/wrun/wrun-builtin-twin.util.js +40 -0
  100. package/dist/utility/wrun/wrun-canvas-cache.util.d.ts +28 -0
  101. package/dist/utility/wrun/wrun-canvas-cache.util.js +56 -0
  102. package/dist/utility/wrun/wrun-canvas-readout.util.d.ts +69 -0
  103. package/dist/utility/wrun/wrun-canvas-readout.util.js +53 -0
  104. package/dist/utility/wrun/wrun-canvases.util.d.ts +295 -0
  105. package/dist/utility/wrun/wrun-canvases.util.js +1432 -0
  106. package/dist/utility/wrun/wrun-cap-notice.util.d.ts +77 -0
  107. package/dist/utility/wrun/wrun-cap-notice.util.js +296 -0
  108. package/dist/utility/wrun/wrun-card-style.util.d.ts +154 -0
  109. package/dist/utility/wrun/wrun-card-style.util.js +539 -0
  110. package/dist/utility/wrun/wrun-chart-context.util.d.ts +89 -0
  111. package/dist/utility/wrun/wrun-chart-context.util.js +213 -0
  112. package/dist/utility/wrun/wrun-chart-names.util.d.ts +23 -0
  113. package/dist/utility/wrun/wrun-chart-names.util.js +33 -0
  114. package/dist/utility/wrun/wrun-chart-time.util.d.ts +12 -0
  115. package/dist/utility/wrun/wrun-chart-time.util.js +23 -0
  116. package/dist/utility/wrun/wrun-child-overlay-id.util.d.ts +13 -0
  117. package/dist/utility/wrun/wrun-child-overlay-id.util.js +44 -0
  118. package/dist/utility/wrun/wrun-color-facts.util.d.ts +40 -0
  119. package/dist/utility/wrun/wrun-color-facts.util.js +88 -0
  120. package/dist/utility/wrun/wrun-color-settings.lazy.d.ts +26 -0
  121. package/dist/utility/wrun/wrun-color-settings.lazy.js +9 -0
  122. package/dist/utility/wrun/wrun-color-settings.util.d.ts +351 -0
  123. package/dist/utility/wrun/wrun-color-settings.util.js +1363 -0
  124. package/dist/utility/wrun/wrun-footprint-modes.util.d.ts +23 -0
  125. package/dist/utility/wrun/wrun-footprint-modes.util.js +24 -0
  126. package/dist/utility/wrun/wrun-frames.d.ts +217 -0
  127. package/dist/utility/wrun/wrun-frames.js +1021 -0
  128. package/dist/utility/wrun/wrun-handles.util.d.ts +792 -0
  129. package/dist/utility/wrun/wrun-handles.util.js +2050 -0
  130. package/dist/utility/wrun/wrun-heatmap-cell-budget.util.d.ts +156 -0
  131. package/dist/utility/wrun/wrun-heatmap-cell-budget.util.js +342 -0
  132. package/dist/utility/wrun/wrun-hosted-wire-caps.d.ts +218 -0
  133. package/dist/utility/wrun/wrun-hosted-wire-caps.js +667 -0
  134. package/dist/utility/wrun/wrun-hosted-wire.util.d.ts +40 -0
  135. package/dist/utility/wrun/wrun-hosted-wire.util.js +27 -0
  136. package/dist/utility/wrun/wrun-hover.util.d.ts +182 -0
  137. package/dist/utility/wrun/wrun-hover.util.js +534 -0
  138. package/dist/utility/wrun/wrun-hud-looks.util.d.ts +246 -0
  139. package/dist/utility/wrun/wrun-hud-looks.util.js +587 -0
  140. package/dist/utility/wrun/wrun-integration-budget.util.d.ts +47 -0
  141. package/dist/utility/wrun/wrun-integration-budget.util.js +122 -0
  142. package/dist/utility/wrun/wrun-latest-snapshot.d.ts +19 -0
  143. package/dist/utility/wrun/wrun-latest-snapshot.js +7 -0
  144. package/dist/utility/wrun/wrun-levels-child.util.d.ts +131 -0
  145. package/dist/utility/wrun/wrun-levels-child.util.js +514 -0
  146. package/dist/utility/wrun/wrun-lifecycle.contract.d.ts +75 -0
  147. package/dist/utility/wrun/wrun-lifecycle.contract.js +9 -0
  148. package/dist/utility/wrun/wrun-market-facts.util.d.ts +116 -0
  149. package/dist/utility/wrun/wrun-market-facts.util.js +238 -0
  150. package/dist/utility/wrun/wrun-output-style.util.d.ts +344 -0
  151. package/dist/utility/wrun/wrun-output-style.util.js +1239 -0
  152. package/dist/utility/wrun/wrun-overlay-identity.util.d.ts +84 -0
  153. package/dist/utility/wrun/wrun-overlay-identity.util.js +142 -0
  154. package/dist/utility/wrun/wrun-overlay-result.util.d.ts +120 -0
  155. package/dist/utility/wrun/wrun-overlay-result.util.js +219 -0
  156. package/dist/utility/wrun/wrun-pack.util.d.ts +70 -0
  157. package/dist/utility/wrun/wrun-pack.util.js +301 -0
  158. package/dist/utility/wrun/wrun-pane-format.util.d.ts +180 -0
  159. package/dist/utility/wrun/wrun-pane-format.util.js +299 -0
  160. package/dist/utility/wrun/wrun-panel-style.lazy.d.ts +25 -0
  161. package/dist/utility/wrun/wrun-panel-style.lazy.js +15 -0
  162. package/dist/utility/wrun/wrun-panel-style.util.d.ts +174 -0
  163. package/dist/utility/wrun/wrun-panel-style.util.js +726 -0
  164. package/dist/utility/wrun/wrun-param-values.util.d.ts +69 -0
  165. package/dist/utility/wrun/wrun-param-values.util.js +230 -0
  166. package/dist/utility/wrun/wrun-refusal.util.d.ts +263 -0
  167. package/dist/utility/wrun/wrun-refusal.util.js +1259 -0
  168. package/dist/utility/wrun/wrun-registry-errors.util.d.ts +199 -0
  169. package/dist/utility/wrun/wrun-registry-errors.util.js +257 -0
  170. package/dist/utility/wrun/wrun-render-select.util.d.ts +336 -0
  171. package/dist/utility/wrun/wrun-render-select.util.js +1157 -0
  172. package/dist/utility/wrun/wrun-script-inputs.util.d.ts +434 -0
  173. package/dist/utility/wrun/wrun-script-inputs.util.js +1971 -0
  174. package/dist/utility/wrun/wrun-setting-words.lazy.d.ts +20 -0
  175. package/dist/utility/wrun/wrun-setting-words.lazy.js +9 -0
  176. package/dist/utility/wrun/wrun-setting-words.util.d.ts +79 -0
  177. package/dist/utility/wrun/wrun-setting-words.util.js +176 -0
  178. package/dist/utility/wrun/wrun-socket-row-store.d.ts +98 -0
  179. package/dist/utility/wrun/wrun-socket-row-store.js +417 -0
  180. package/dist/utility/wrun/wrun-style-flags.util.d.ts +18 -0
  181. package/dist/utility/wrun/wrun-style-flags.util.js +21 -0
  182. package/dist/utility/wrun/wrun-style-words.util.d.ts +148 -0
  183. package/dist/utility/wrun/wrun-style-words.util.js +439 -0
  184. package/dist/utility/wrun/wrun-table-look.util.d.ts +125 -0
  185. package/dist/utility/wrun/wrun-table-look.util.js +225 -0
  186. package/dist/utility/wrun/wrun-text-look.util.d.ts +51 -0
  187. package/dist/utility/wrun/wrun-text-look.util.js +227 -0
  188. package/dist/utility/wrun/wrun-text-params.util.d.ts +106 -0
  189. package/dist/utility/wrun/wrun-text-params.util.js +171 -0
  190. package/dist/utility/wrun/wrun-tpo-rows.util.d.ts +71 -0
  191. package/dist/utility/wrun/wrun-tpo-rows.util.js +438 -0
  192. package/dist/utility/wrun/wrun-twin-compute-inputs.util.d.ts +14 -0
  193. package/dist/utility/wrun/wrun-twin-compute-inputs.util.js +58 -0
  194. package/dist/utility/wrun/wrun-visibility-table.d.ts +437 -0
  195. package/dist/utility/wrun/wrun-visibility-table.js +237 -0
  196. package/dist/utility/wrun/wrun-volume-profile.util.d.ts +37 -0
  197. package/dist/utility/wrun/wrun-volume-profile.util.js +278 -0
  198. package/package.json +38 -0
@@ -0,0 +1,1157 @@
1
+ /**
2
+ * `selectRenderables`: the WRUN renderer/drawing selection lifecycle over a
3
+ * finished row set, ported faithfully from the om reference runtime
4
+ * (openmarket packages/cli/src/runner/wrun/runtime.ts) so a package's
5
+ * declared visuals select identically under the browser host:
6
+ *
7
+ * - `text`: one entry per READY row whose slot is PRESENT (a written empty
8
+ * string is an entry; an unwritten slot skips the row).
9
+ * - `label`: the LAST ready row whose slot is present AND nonempty AND whose
10
+ * x/y outputs are finite there; later absent or empty rows never clear an
11
+ * earlier winner.
12
+ * - `table`: the LAST ready row where EVERY cell slot is present.
13
+ * - `shape`: one entry per ready row whose output is finite, gated (when
14
+ * `where` is declared) to rows where the gate output is finite and nonzero.
15
+ * With `color_by` (scaffold 21) the bgcolor ladder rule lands on the mark:
16
+ * the rung floors into `colors`, a finite out-of-range index clamps to
17
+ * entry 0, a non-finite rung selects NO mark, and each selected row
18
+ * carries its resolved `color` exactly like the daemon.
19
+ * - `stats_row`: one entry per ready row, NaN carried, never dropped; a renderer declared (or
20
+ * painted) `visible: false` selects nothing at all, no entry and no rows.
21
+ * - `bgcolor`: one entry per ready row whose `where` gate is finite and
22
+ * nonzero; with `color_by` a non-finite rung drops the row entirely (a
23
+ * background record IS a color), and the selection carries the raw rung
24
+ * for the adapter's ladder. Declared text/label color+size pass through
25
+ * untouched on the selection wrapper.
26
+ * - `barcolor`: the bgcolor selection exactly (same gate, same ladder, same
27
+ * accounting) under its own kind, so the adapter paints the bar's own
28
+ * candle instead of its background.
29
+ * - `card` drawings: the LAST ready row with finite referenced outputs and
30
+ * present referenced slots; sparks take the bounded ready-row history ending
31
+ * at that winner. An absent value declaration resolves to an empty value.
32
+ * WRUN-STYLE g3: the headline (DW01) resolves on the winning row like a
33
+ * row value; the title and the row labels resolve their `{{templates}}`
34
+ * there (DW14: a declared output or string slot by name, `{{name:format}}`
35
+ * a format word, the chart's `{{symbol}}` / `{{exchange}}` / `{{timeframe}}`
36
+ * from the select context; an unknown name stays as written), their
37
+ * references joining the complete-row gate; every number prints through
38
+ * `formatWrunNumber` (DW23: the shared words plus `pct`; an undeclared
39
+ * format keeps today's six significant digits) at the context's price
40
+ * digits.
41
+ * - `inset`: every ready row, retaining non-finite values as series gaps.
42
+ * - levels, panels, ladder, feed and matrices consume run-level frame
43
+ * snapshots. An unwritten slot selects null; invalid written content fails
44
+ * the run by slot. A levels frame also passes the declaration cross-checks
45
+ * (`checkWrunLevelsFrame`: DL-stacked, DL-scale, the DL-time-anchored
46
+ * spans shape, charged 16 per span and per row); a panel frame's chrome
47
+ * (SC17) is charged beside its rows; a matrix (MX-price-matrix) selects
48
+ * through `selectWrunMatrix` on the same budget.
49
+ * - minicharts consumes its frame the same way and selects the grid exactly
50
+ * as the chart's mini-chart grid overlay reads it, through the shared
51
+ * host's om mapping (`wrunMiniChartGridPayload`), beside
52
+ * the drawing's z; every panel and every candle counts as an entry.
53
+ * - ladder, feed and meter carry a `title` (DW15): the frame's, else the
54
+ * declared one (chart names substituted; a meter's templates resolve on
55
+ * its own row), else the declaration name.
56
+ * - meter binds the last ready row's fraction and optional string slot.
57
+ * - other drawings: the LAST ready row ONLY; all coordinates finite (and a label's
58
+ * slot present) = the object exists with `createdBar` = that row's index;
59
+ * any NaN or absent slot = no object, regardless of earlier rows. A box's
60
+ * declared `text` slot is read on that row (DW31; unwritten = no text).
61
+ *
62
+ * The expanded selection is capped at 8 MiB with the reference accounting
63
+ * (16 bytes per selected entry + 8 per carried number + UTF-8 bytes of every
64
+ * carried string, table cells charging 8 extra per cell, copied metadata
65
+ * charged once per renderer/drawing that carries it), checked incrementally
66
+ * and refusing by name (`wrun_render_result_too_large`). The run-result
67
+ * translator charges handles and strategy into this same counter.
68
+ *
69
+ * This module rides the wasm host worker (wrun-abi-host imports it), so it
70
+ * restates the template placeholder grammar (the one wrun-hover.util and the
71
+ * om runtime share) instead of importing wrun-hover.util, whose formatter
72
+ * chain pulls the i18n plugin.
73
+ */
74
+ import { selectWrunMatrix } from './wrun-canvases.util.js';
75
+ import { substituteWrunChartNames } from './wrun-chart-context.util.js';
76
+ import { wrunChartHostEnv } from '../../host-env.js';
77
+ import { checkWrunLevelsFrame } from './wrun-levels-child.util.js';
78
+ import { formatWrunNumber } from './wrun-style-words.util.js';
79
+ import { wrunBuildUnitReads } from './wrun-build-memo.util.js';
80
+ import { wrunRowVisibleHere } from './wrun-market-facts.util.js';
81
+ import { invalidWrunFrame, parseWrunFeedFrame, parseWrunLadderFrame, parseWrunLevelsFrame, parseWrunMiniChartsFrame, parseWrunPanelFrame, } from './wrun-frames.js';
82
+ /** The expanded render result's cap, om's (runtime.ts WRUN_RENDER_RESULT_LIMIT_BYTES): the run's
83
+ * own string budget (WRUN_STRING_RUN_LIMIT_BYTES, 8 MiB), since the selection carries the strings
84
+ * the run wrote plus per-entry overhead and a lower cap would refuse output the run already
85
+ * admitted. It guards materialization only; the worker's write caps are its own
86
+ * (wrun-abi-host: the string run limit, and wrun-4's frame transport limit). */
87
+ export const WRUN_RENDER_RESULT_LIMIT_BYTES = 8 * 1024 * 1024;
88
+ /** The kit's code for an expanded result over the render budget. */
89
+ export const WRUN_RENDER_RESULT_TOO_LARGE = 'wrun_render_result_too_large';
90
+ /** The budget's refusal mapped to the kit's: its code (`code`) and the sentence the kit's own shaper refuses
91
+ * with, so a browser run over the budget refuses by the code a cloud run's refusal carries. */
92
+ export class WrunRenderBudgetRefusal extends Error {
93
+ code = WRUN_RENDER_RESULT_TOO_LARGE;
94
+ constructor(limitBytes) {
95
+ super(`WRUN render result exceeds ${limitBytes} bytes expanded (${WRUN_RENDER_RESULT_TOO_LARGE}): ` +
96
+ 'fewer rows, shorter strings, or fewer renderers/drawings');
97
+ this.name = 'WrunRenderBudgetRefusal';
98
+ }
99
+ }
100
+ /** One counter follows the selection, frame consumers, handles and strategy: the browser lane's one
101
+ * accounting of the render cap (the sandbox row source charges nothing of its own). */
102
+ export function createWrunRenderBudget() {
103
+ let spent = 0;
104
+ return {
105
+ get spent() {
106
+ return spent;
107
+ },
108
+ spend(bytes) {
109
+ spent += bytes;
110
+ if (spent > WRUN_RENDER_RESULT_LIMIT_BYTES)
111
+ throw new WrunRenderBudgetRefusal(WRUN_RENDER_RESULT_LIMIT_BYTES);
112
+ },
113
+ };
114
+ }
115
+ /** Values only: object keys are schema, strings and numbers are carried data. */
116
+ export function wrunRenderValueBytes(value) {
117
+ if (typeof value === 'number')
118
+ return 8;
119
+ if (typeof value === 'string')
120
+ return utf8ByteLength(value);
121
+ if (Array.isArray(value))
122
+ return value.reduce((bytes, item) => bytes + wrunRenderValueBytes(item), 0);
123
+ if (value !== null && typeof value === 'object')
124
+ return wrunRenderValueBytes(Object.values(value));
125
+ return 0;
126
+ }
127
+ /** The outputs a renderer is drawn from: its value or its anchor (a stats row's or a shape's
128
+ * output, an inset's, a text's y, a label's point, a tint's gate), never a colour ladder. */
129
+ function wrunRendererDrawnFrom(renderer) {
130
+ switch (renderer.kind) {
131
+ case 'inset':
132
+ case 'shape':
133
+ case 'stats_row':
134
+ return [renderer.output];
135
+ case 'text':
136
+ return [renderer.y];
137
+ case 'label':
138
+ return [renderer.x, renderer.y];
139
+ case 'bgcolor':
140
+ case 'barcolor':
141
+ return [renderer.where];
142
+ default:
143
+ return [];
144
+ }
145
+ }
146
+ const selectionBytes = new WeakMap();
147
+ export function wrunSelectionBytes(selection) {
148
+ const accounted = selectionBytes.get(selection);
149
+ if (accounted !== undefined)
150
+ return accounted;
151
+ // A supplied or cloned selection has no local accounting receipt. Include
152
+ // every carried value and the selected-entry overhead at this boundary.
153
+ let entries = selection.drawings.length;
154
+ let tableCells = 0;
155
+ for (const renderer of selection.renderers) {
156
+ if (renderer.kind === 'label')
157
+ entries += renderer.label === null ? 0 : 1;
158
+ else if (renderer.kind === 'table') {
159
+ entries += renderer.table === null ? 0 : 1;
160
+ tableCells += renderer.table?.cells.length ?? 0;
161
+ }
162
+ else
163
+ entries += renderer.rows.length;
164
+ }
165
+ for (const drawing of selection.drawings) {
166
+ if (drawing.kind === 'card' || drawing.kind === 'ladder')
167
+ entries += drawing.props?.rows.length ?? 0;
168
+ else if (drawing.kind === 'feed')
169
+ entries += drawing.props?.lines.length ?? 0;
170
+ else if (drawing.kind === 'minicharts')
171
+ entries += miniChartsEntries(drawing.props);
172
+ if (drawing.kind === 'card' && drawing.props.headline !== undefined)
173
+ entries += 1;
174
+ }
175
+ for (const level of selection.levels ?? []) {
176
+ if (level.frame)
177
+ entries += wrunLevelsFrameEntries(level.frame);
178
+ }
179
+ for (const panel of selection.panels ?? [])
180
+ entries += panel.frame?.rows.length ?? 0;
181
+ for (const matrix of selection.matrices ?? [])
182
+ entries += wrunMatrixCellCount(matrix.frame);
183
+ return wrunRenderValueBytes(selection) + entries * 16 + tableCells * 8;
184
+ }
185
+ /** A grid's selected entries: every panel and every candle, like a ladder row. */
186
+ function miniChartsEntries(grid) {
187
+ return (grid?.panels ?? []).reduce((sum, panel) => sum + 1 + panel.bars.length, 0);
188
+ }
189
+ /** The selected entries a levels frame counts: its rows, plus one per span
190
+ * on the spans shape (DL-time-anchored: 16 per span + 16 per row). */
191
+ function wrunLevelsFrameEntries(frame) {
192
+ const spans = frame.spans;
193
+ if (Array.isArray(spans)) {
194
+ return spans.reduce((entries, span) => entries + 1 + (Array.isArray(span?.prices) ? span.prices.length : 0), 0);
195
+ }
196
+ const prices = frame.prices;
197
+ return Array.isArray(prices) ? prices.length : 0;
198
+ }
199
+ /** The cells of a parsed matrix frame (16 bytes each, MX-price-matrix). */
200
+ function wrunMatrixCellCount(frame) {
201
+ const cells = frame === null ? undefined : frame.cells;
202
+ if (!Array.isArray(cells))
203
+ return 0;
204
+ return cells.reduce((count, row) => count + (Array.isArray(row) ? row.length : 0), 0);
205
+ }
206
+ /** The bytes a parsed levels frame charges on the shared budget: 16 per
207
+ * row (and per span) beside every carried number and string. */
208
+ function wrunLevelsFrameBytes(frame) {
209
+ return 16 * wrunLevelsFrameEntries(frame) + wrunRenderValueBytes(frame);
210
+ }
211
+ /** The template placeholder (`{{name}}`, `{{name:format}}`): the grammar the
212
+ * om runtime, the prebuild fold and wrun-hover.util share. */
213
+ const WRUN_TEMPLATE_PLACEHOLDER = /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)(?:\s*:\s*([^}\s]+))?\s*\}\}/g;
214
+ /** The declared names a template reads (a string slot first, else an
215
+ * output; anything else is text), added to a card's complete-row gate. */
216
+ function wrunTemplateRefs(template, ctx, outputs, slots) {
217
+ if (!template.includes('{{'))
218
+ return;
219
+ for (const match of template.matchAll(WRUN_TEMPLATE_PLACEHOLDER)) {
220
+ const name = match[1];
221
+ if (ctx.slotIndex.has(name))
222
+ slots.add(name);
223
+ else if (ctx.outputIndex.has(name))
224
+ outputs.add(name);
225
+ }
226
+ }
227
+ /** A template on one row: a slot prints its text (absent = ""), an output
228
+ * its value through the placeholder's format word, else its declared
229
+ * format, else six significant digits (non-finite = ""); a name that is
230
+ * neither stays as written; then the chart names fill `{{symbol}}`,
231
+ * `{{exchange}}` and `{{timeframe}}`. */
232
+ function wrunResolveTemplate(template, ready, ctx) {
233
+ const resolved = !template.includes('{{')
234
+ ? template
235
+ : template.replace(WRUN_TEMPLATE_PLACEHOLDER, (literal, name, format) => {
236
+ const slot = ctx.slotIndex.get(name);
237
+ if (slot !== undefined)
238
+ return ready.strings[slot] ?? '';
239
+ const index = ctx.outputIndex.get(name);
240
+ if (index === undefined)
241
+ return literal;
242
+ const value = ready.outputs[index] ?? Number.NaN;
243
+ if (!Number.isFinite(value))
244
+ return '';
245
+ const word = format ?? ctx.outputFormat.get(name);
246
+ return formatWrunNumber(value, {
247
+ ...(word !== undefined ? { format: word } : {}),
248
+ priceDigits: ctx.priceDigits,
249
+ });
250
+ });
251
+ return substituteWrunChartNames(resolved, ctx.chartNames);
252
+ }
253
+ /** The text a card row printed before WRUN-STYLE for its four format words
254
+ * (the pre-round valueText; om's legacyCardRowText prints the same bytes),
255
+ * undefined for any other word. */
256
+ function legacyCardRowText(value, format) {
257
+ switch (format) {
258
+ case 'int':
259
+ return String(Math.round(value));
260
+ case 'pct':
261
+ return `${(value * 100).toFixed(2)}%`;
262
+ case 'usd':
263
+ return `$${value.toFixed(2)}`;
264
+ case 'auto':
265
+ return String(Number(value.toPrecision(6)));
266
+ default:
267
+ return undefined;
268
+ }
269
+ }
270
+ /** The number-format half of a card value or headline (`format`,
271
+ * `decimals`, `signed`, `unit`) as a `formatWrunNumber` spec without
272
+ * undefined keys, at the chart's price digits. */
273
+ function wrunCardNumberSpec(entry, priceDigits) {
274
+ return {
275
+ ...(entry.format !== undefined ? { format: entry.format } : {}),
276
+ ...(entry.decimals !== undefined ? { decimals: entry.decimals } : {}),
277
+ ...(entry.signed !== undefined ? { signed: entry.signed } : {}),
278
+ ...(entry.unit !== undefined ? { unit: entry.unit } : {}),
279
+ ...(priceDigits !== undefined ? { priceDigits } : {}),
280
+ };
281
+ }
282
+ /** A frame's optional per-run `title` (DW15), read off whatever the frame
283
+ * host returns. */
284
+ function wrunFrameTitle(frame) {
285
+ const title = frame === null ? undefined : frame.title;
286
+ return typeof title === 'string' && title.length > 0 ? title : undefined;
287
+ }
288
+ export function selectWrunRenderables(rows, sheet, frames, budget = createWrunRenderBudget(), context,
289
+ /** A live tick's build memo over these rows (wrun-build-memo.util): a renderer none of whose inputs changed
290
+ * on the newest row takes back its selection. */
291
+ memo) {
292
+ const initialSpent = budget.spent;
293
+ const outputIndex = new Map();
294
+ const outputFormat = new Map();
295
+ for (const output of sheet.outputs) {
296
+ outputIndex.set(output.name, output.index);
297
+ if (typeof output.format === 'string')
298
+ outputFormat.set(output.name, output.format);
299
+ }
300
+ // Declared display offsets: per-row renderer kinds (text, shape, stats_row)
301
+ // carry the value output's `displacement_bars` in their selection wrapper.
302
+ // Rows are never shifted here; a declared 0 rides nothing. Anchored kinds
303
+ // (label, table, drawings) place by coordinate values and carry no offset.
304
+ const outputDisplacement = new Map();
305
+ for (const output of sheet.outputs) {
306
+ if (output.displacement_bars !== undefined && output.displacement_bars !== 0) {
307
+ outputDisplacement.set(output.name, output.displacement_bars);
308
+ }
309
+ }
310
+ const slotIndex = new Map();
311
+ for (const slot of sheet.string_slots ?? [])
312
+ slotIndex.set(slot.name, slot.index);
313
+ const requireOutput = (subject, ref) => {
314
+ const idx = outputIndex.get(ref);
315
+ if (idx === undefined) {
316
+ throw new Error(`WRUN ${subject} references '${ref}', which does not name a declared numeric output`);
317
+ }
318
+ return idx;
319
+ };
320
+ const requireSlot = (subject, ref) => {
321
+ const idx = slotIndex.get(ref);
322
+ if (idx === undefined) {
323
+ throw new Error(`WRUN ${subject} references '${ref}', which does not name a declared string slot`);
324
+ }
325
+ return idx;
326
+ };
327
+ const templates = {
328
+ outputIndex,
329
+ slotIndex,
330
+ outputFormat,
331
+ ...(context?.priceDigits !== undefined ? { priceDigits: context.priceDigits } : {}),
332
+ ...(context?.chartNames !== undefined ? { chartNames: context.chartNames } : {}),
333
+ };
334
+ // A declared widget title with the chart names filled (DW15); a frame's
335
+ // title wins over it, the declaration name stands in for both.
336
+ const declaredTitle = (title) => title === undefined ? undefined : substituteWrunChartNames(title, context?.chartNames);
337
+ // The ready rows (the rows with outputs) are read in place: the whole list is made once, only when a selection
338
+ // walks every bar; a live build's renderer that takes back its selection reads the bars after the memo's alone.
339
+ const readyAt = (at) => {
340
+ const row = rows[at];
341
+ return row.outputs === null ? undefined : { row: at, ts: row.ts, outputs: row.outputs, strings: row.strings ?? [] };
342
+ };
343
+ let everyReady;
344
+ const readyRows = () => {
345
+ if (everyReady === undefined) {
346
+ everyReady = [];
347
+ for (let at = 0; at < rows.length; at += 1) {
348
+ const ready = readyAt(at);
349
+ if (ready !== undefined)
350
+ everyReady.push(ready);
351
+ }
352
+ }
353
+ return everyReady;
354
+ };
355
+ /** The ready rows from bar `from` on, in bar order. */
356
+ const readyFrom = (from) => {
357
+ if (from <= 0)
358
+ return readyRows();
359
+ const ready = [];
360
+ for (let at = from; at < rows.length; at += 1) {
361
+ const row = readyAt(at);
362
+ if (row !== undefined)
363
+ ready.push(row);
364
+ }
365
+ return ready;
366
+ };
367
+ const spend = (bytes) => budget.spend(bytes);
368
+ /**
369
+ * A per-row renderer's selected rows (text, shape, stats_row, bgcolor, barcolor: each row a function of its own
370
+ * bar): `pick` selects one ready row into `into`, or nothing, and answers the budget bytes the row charges. In a
371
+ * live build's unit (wrun-build-memo.util) the bars before the memo's newest take back the rows its last build
372
+ * selected there, charging the bytes they charged, and only the bars from there on are read.
373
+ */
374
+ const selectRows = (pick) => {
375
+ const prefix = memo?.rowPrefix('select');
376
+ const selected = prefix === undefined ? [] : prefix.rows.slice(0, prefix.count);
377
+ let bytesBeforeNewest = prefix?.bytes ?? 0;
378
+ if (bytesBeforeNewest > 0)
379
+ spend(bytesBeforeNewest);
380
+ const newest = rows.length - 1;
381
+ for (const ready of readyFrom(prefix?.from ?? 0)) {
382
+ const bytes = pick(ready, selected);
383
+ if (bytes === 0)
384
+ continue;
385
+ spend(bytes);
386
+ if (ready.row < newest)
387
+ bytesBeforeNewest += bytes;
388
+ }
389
+ let countBeforeNewest = selected.length;
390
+ while (countBeforeNewest > 0 && selected[countBeforeNewest - 1].row >= newest)
391
+ countBeforeNewest -= 1;
392
+ memo?.notePrefix('select', selected, countBeforeNewest, bytesBeforeNewest);
393
+ return selected;
394
+ };
395
+ const metaBytes = (value) => (value === undefined ? 0 : utf8ByteLength(value));
396
+ const out = (ready, idx) => ready.outputs[idx] ?? Number.NaN;
397
+ const renderers = [];
398
+ // `visible_by` (kit 0.69.0): an output the market's size unit leaves out mounts nothing, nor any
399
+ // renderer drawn from it (wrunRendererDrawnFrom: a stats row that reads it hides with it); the
400
+ // module computed it all the same.
401
+ const sizeUnit = context?.sizeUnit ?? 0;
402
+ const hiddenOutputs = new Set(sheet.outputs.filter((output) => !wrunRowVisibleHere(output.visible_by, sizeUnit)).map((output) => output.name));
403
+ const declarations = [...(sheet.renderers ?? [])];
404
+ for (const output of sheet.outputs) {
405
+ if (output.plot !== 'inset')
406
+ continue;
407
+ if (!output.inset)
408
+ throw new Error(`WRUN inset output '${output.name}' needs an inset declaration`);
409
+ declarations.push({
410
+ kind: 'inset',
411
+ name: output.name,
412
+ output: output.name,
413
+ ...output.inset,
414
+ ...(output.color !== undefined ? { color: output.color } : {}),
415
+ });
416
+ }
417
+ const selectRenderer = (renderer) => {
418
+ switch (renderer.kind) {
419
+ case 'inset': {
420
+ const idx = requireOutput(`inset renderer '${renderer.name}' output`, renderer.output);
421
+ const selected = [];
422
+ for (const ready of readyRows()) {
423
+ spend(16 + 8 * 2);
424
+ selected.push([ready.ts, out(ready, idx)]);
425
+ }
426
+ const { name, output, dock, color } = renderer;
427
+ const height_px = renderer.height_px ?? 28;
428
+ const shape = renderer.shape ?? 'histogram';
429
+ spend(wrunRenderValueBytes({ name, output, dock, height_px, shape, color }));
430
+ renderers.push({
431
+ kind: 'inset',
432
+ name,
433
+ output,
434
+ dock,
435
+ height_px,
436
+ shape,
437
+ ...(color !== undefined ? { color } : {}),
438
+ rows: selected,
439
+ });
440
+ break;
441
+ }
442
+ case 'text': {
443
+ const yIdx = requireOutput(`text renderer '${renderer.name}' y`, renderer.y);
444
+ const slot = requireSlot(`text renderer '${renderer.name}' text`, renderer.text);
445
+ const selected = selectRows((ready, into) => {
446
+ const text = ready.strings[slot];
447
+ if (text === undefined)
448
+ return 0;
449
+ into.push({ row: ready.row, ts: ready.ts, y: out(ready, yIdx), text });
450
+ return 16 + 8 * 3 + utf8ByteLength(text);
451
+ });
452
+ const displacement = outputDisplacement.get(renderer.y);
453
+ spend(metaBytes(renderer.name) +
454
+ metaBytes(renderer.color) +
455
+ metaBytes(renderer.style) +
456
+ (renderer.size !== undefined ? 8 : 0) +
457
+ (displacement !== undefined ? 8 : 0));
458
+ renderers.push({
459
+ kind: 'text',
460
+ name: renderer.name,
461
+ ...(renderer.color !== undefined ? { color: renderer.color } : {}),
462
+ ...(renderer.size !== undefined ? { size: renderer.size } : {}),
463
+ ...(renderer.style !== undefined ? { style: renderer.style } : {}),
464
+ ...(displacement !== undefined ? { displacement_bars: displacement } : {}),
465
+ rows: selected,
466
+ });
467
+ break;
468
+ }
469
+ case 'label': {
470
+ // A label sits at an (x, y) point, or (wrun-3) in a corner named by
471
+ // `position`, where the point is optional; the sheet coupling check
472
+ // already refused a lone x or y, so a point is declared as a pair.
473
+ const { position } = renderer;
474
+ const hasPoint = renderer.x !== undefined && renderer.y !== undefined;
475
+ if (position === undefined && !hasPoint) {
476
+ throw new Error(`WRUN label renderer '${renderer.name}' needs x and y (or a corner position)`);
477
+ }
478
+ const xIdx = hasPoint ? requireOutput(`label renderer '${renderer.name}' x`, renderer.x) : -1;
479
+ const yIdx = hasPoint ? requireOutput(`label renderer '${renderer.name}' y`, renderer.y) : -1;
480
+ const slot = requireSlot(`label renderer '${renderer.name}' text`, renderer.text);
481
+ let label = null;
482
+ for (let at = rows.length - 1; at >= 0; at -= 1) {
483
+ const ready = readyAt(at);
484
+ if (ready === undefined)
485
+ continue;
486
+ const text = ready.strings[slot];
487
+ if (text === undefined || text.length === 0)
488
+ continue;
489
+ const x = hasPoint ? out(ready, xIdx) : Number.NaN;
490
+ const y = hasPoint ? out(ready, yIdx) : Number.NaN;
491
+ if (hasPoint && (!Number.isFinite(x) || !Number.isFinite(y)))
492
+ continue;
493
+ spend(16 + 8 * 4 + utf8ByteLength(text));
494
+ label = { row: ready.row, ts: ready.ts, x, y, text };
495
+ break;
496
+ }
497
+ spend(metaBytes(renderer.name) +
498
+ metaBytes(renderer.color) +
499
+ metaBytes(position) +
500
+ (renderer.size !== undefined ? 8 : 0));
501
+ renderers.push({
502
+ kind: 'label',
503
+ name: renderer.name,
504
+ ...(renderer.color !== undefined ? { color: renderer.color } : {}),
505
+ ...(renderer.size !== undefined ? { size: renderer.size } : {}),
506
+ ...(position !== undefined ? { position } : {}),
507
+ label,
508
+ });
509
+ break;
510
+ }
511
+ case 'table': {
512
+ const slots = renderer.cells.map((cell, cellIdx) => requireSlot(`table renderer '${renderer.name}' cells[${cellIdx}]`, cell));
513
+ let table = null;
514
+ for (let at = rows.length - 1; at >= 0; at -= 1) {
515
+ const ready = readyAt(at);
516
+ if (ready === undefined)
517
+ continue;
518
+ const cells = [];
519
+ let complete = true;
520
+ for (const slot of slots) {
521
+ const cell = ready.strings[slot];
522
+ if (cell === undefined) {
523
+ complete = false;
524
+ break;
525
+ }
526
+ cells.push(cell);
527
+ }
528
+ if (!complete)
529
+ continue;
530
+ spend(16 + 8 * 2 + cells.reduce((sum, cell) => sum + 8 + utf8ByteLength(cell), 0));
531
+ table = { row: ready.row, ts: ready.ts, cells };
532
+ break;
533
+ }
534
+ spend(metaBytes(renderer.name) + 8 * 2 + metaBytes(renderer.position));
535
+ renderers.push({
536
+ kind: 'table',
537
+ name: renderer.name,
538
+ rows: renderer.rows,
539
+ cols: renderer.cols,
540
+ ...(renderer.position !== undefined ? { position: renderer.position } : {}),
541
+ table,
542
+ });
543
+ break;
544
+ }
545
+ case 'shape': {
546
+ const valueIdx = requireOutput(`shape renderer '${renderer.name}' output`, renderer.output);
547
+ const whereIdx = renderer.where === undefined
548
+ ? undefined
549
+ : requireOutput(`shape renderer '${renderer.name}' where`, renderer.where);
550
+ const ladderIdx = renderer.color_by === undefined
551
+ ? undefined
552
+ : requireOutput(`shape renderer '${renderer.name}' color_by`, renderer.color_by);
553
+ if (ladderIdx !== undefined && (!renderer.colors || renderer.colors.length === 0)) {
554
+ throw new Error(`WRUN shape renderer '${renderer.name}' color_by needs a non-empty 'colors' table`);
555
+ }
556
+ const selected = selectRows((ready, into) => {
557
+ const value = out(ready, valueIdx);
558
+ if (!Number.isFinite(value))
559
+ return 0;
560
+ if (whereIdx !== undefined) {
561
+ const gate = out(ready, whereIdx);
562
+ if (!Number.isFinite(gate) || gate === 0)
563
+ return 0;
564
+ }
565
+ if (ladderIdx !== undefined) {
566
+ // Ladder marks (the bgcolor rule): floor the rung, clamp a finite
567
+ // out-of-range index to entry 0, and select NO mark on a
568
+ // non-finite rung (NaN and +/-Infinity alike; the static color
569
+ // never substitutes). The row carries its resolved color, the
570
+ // daemon's row shape.
571
+ const rung = out(ready, ladderIdx);
572
+ if (!Number.isFinite(rung))
573
+ return 0;
574
+ const colors = renderer.colors;
575
+ let at = Math.floor(rung);
576
+ if (at < 0 || at >= colors.length)
577
+ at = 0;
578
+ const color = colors[at];
579
+ into.push({ row: ready.row, ts: ready.ts, value, color });
580
+ return 16 + 8 * 3 + utf8ByteLength(color);
581
+ }
582
+ into.push({ row: ready.row, ts: ready.ts, value });
583
+ return 16 + 8 * 3;
584
+ });
585
+ const displacement = outputDisplacement.get(renderer.output);
586
+ // Every palette entry charges 8 bytes beside its UTF-8 bytes (the
587
+ // bgcolor accounting), spent before the palette is cloned below.
588
+ spend(metaBytes(renderer.name) +
589
+ metaBytes(renderer.shape) +
590
+ metaBytes(renderer.where) +
591
+ metaBytes(renderer.color) +
592
+ metaBytes(renderer.color_by) +
593
+ (renderer.colors ?? []).reduce((sum, entry) => sum + 8 + utf8ByteLength(entry), 0) +
594
+ (renderer.width !== undefined ? 8 : 0) +
595
+ (displacement !== undefined ? 8 : 0));
596
+ renderers.push({
597
+ kind: 'shape',
598
+ name: renderer.name,
599
+ shape: renderer.shape,
600
+ ...(renderer.where !== undefined ? { where: renderer.where } : {}),
601
+ ...(renderer.color !== undefined ? { color: renderer.color } : {}),
602
+ ...(renderer.color_by !== undefined ? { color_by: renderer.color_by } : {}),
603
+ ...(renderer.colors !== undefined ? { colors: [...renderer.colors] } : {}),
604
+ ...(renderer.width !== undefined ? { width: renderer.width } : {}),
605
+ ...(displacement !== undefined ? { displacement_bars: displacement } : {}),
606
+ rows: selected,
607
+ });
608
+ break;
609
+ }
610
+ case 'stats_row': {
611
+ const valueIdx = requireOutput(`stats_row renderer '${renderer.name}' output`, renderer.output);
612
+ // visible false: the row is switched off, so it selects nothing (absent = true; the output
613
+ // reference is still checked above), the om reference's rule.
614
+ if (renderer.visible === false)
615
+ break;
616
+ const selected = selectRows((ready, into) => {
617
+ into.push({ row: ready.row, ts: ready.ts, value: out(ready, valueIdx) });
618
+ return 16 + 8 * 3;
619
+ });
620
+ const displacement = outputDisplacement.get(renderer.output);
621
+ spend(metaBytes(renderer.name) +
622
+ metaBytes(renderer.title) +
623
+ metaBytes(renderer.format) +
624
+ metaBytes(renderer.polarity) +
625
+ (displacement !== undefined ? 8 : 0));
626
+ renderers.push({
627
+ kind: 'stats_row',
628
+ name: renderer.name,
629
+ ...(renderer.title !== undefined ? { title: renderer.title } : {}),
630
+ ...(renderer.format !== undefined ? { format: renderer.format } : {}),
631
+ ...(renderer.polarity !== undefined ? { polarity: renderer.polarity } : {}),
632
+ ...(displacement !== undefined ? { displacement_bars: displacement } : {}),
633
+ rows: selected,
634
+ });
635
+ break;
636
+ }
637
+ // One selection body for the two tint kinds (the om reference does the
638
+ // same): the gate, the ladder and the accounting are identical; the
639
+ // kind rides through so the adapter knows which surface (background or
640
+ // candle) the rows paint. Neither kind carries a displacement: a tint
641
+ // anchors to its own bar.
642
+ case 'bgcolor':
643
+ case 'barcolor': {
644
+ const whereIdx = requireOutput(`${renderer.kind} renderer '${renderer.name}' where`, renderer.where);
645
+ const ladderIdx = renderer.color_by === undefined
646
+ ? undefined
647
+ : requireOutput(`${renderer.kind} renderer '${renderer.name}' color_by`, renderer.color_by);
648
+ if (ladderIdx !== undefined && (!renderer.colors || renderer.colors.length === 0)) {
649
+ throw new Error(`WRUN ${renderer.kind} renderer '${renderer.name}' color_by needs a non-empty 'colors' table`);
650
+ }
651
+ const selected = selectRows((ready, into) => {
652
+ const gate = out(ready, whereIdx);
653
+ if (!Number.isFinite(gate) || gate === 0)
654
+ return 0;
655
+ let rung;
656
+ if (ladderIdx !== undefined) {
657
+ rung = out(ready, ladderIdx);
658
+ // A non-finite rung is NO record: a background row IS a color.
659
+ if (!Number.isFinite(rung))
660
+ return 0;
661
+ }
662
+ into.push({ row: ready.row, ts: ready.ts, ...(rung !== undefined ? { rung } : {}) });
663
+ return 16 + 8 * 3;
664
+ });
665
+ spend(metaBytes(renderer.name) +
666
+ metaBytes(renderer.where) +
667
+ metaBytes(renderer.color) +
668
+ metaBytes(renderer.color_by) +
669
+ (renderer.colors ?? []).reduce((sum, color) => sum + 8 + utf8ByteLength(color), 0));
670
+ renderers.push({
671
+ kind: renderer.kind,
672
+ name: renderer.name,
673
+ where: renderer.where,
674
+ ...(renderer.color !== undefined ? { color: renderer.color } : {}),
675
+ ...(renderer.color_by !== undefined ? { color_by: renderer.color_by } : {}),
676
+ ...(renderer.colors !== undefined ? { colors: [...renderer.colors] } : {}),
677
+ rows: selected,
678
+ });
679
+ break;
680
+ }
681
+ }
682
+ };
683
+ // A live build selects each declared renderer through its memo (wrun-build-memo.util): one whose columns and
684
+ // slots did not change on the newest row takes back its selection and charges its bytes again, in its turn.
685
+ // An inset (declared on its output) and a renderer whose name another one shares select on every build.
686
+ const memoNames = new Set();
687
+ const declaredNames = (sheet.renderers ?? []).map((renderer) => renderer.name);
688
+ const namesUnique = new Set(declaredNames).size === declaredNames.length;
689
+ for (const renderer of declarations) {
690
+ if (wrunRendererDrawnFrom(renderer).some((name) => name !== undefined && hiddenOutputs.has(name)))
691
+ continue;
692
+ const id = `select:${renderer.name}`;
693
+ if (memo === undefined || !namesUnique || renderer.kind === 'inset' || memoNames.has(id)) {
694
+ selectRenderer(renderer);
695
+ continue;
696
+ }
697
+ memoNames.add(id);
698
+ memo.payloadUnit(id, wrunBuildUnitReads(sheet, id, renderer), () => {
699
+ const from = renderers.length;
700
+ const spentBefore = budget.spent;
701
+ selectRenderer(renderer);
702
+ return { entries: renderers.slice(from), bytes: budget.spent - spentBefore };
703
+ }, (payload) => {
704
+ spend(payload.bytes);
705
+ renderers.push(...payload.entries);
706
+ });
707
+ }
708
+ const drawings = [];
709
+ let last;
710
+ for (let at = rows.length - 1; at >= 0 && last === undefined; at -= 1)
711
+ last = readyAt(at);
712
+ const frameSlots = new Map((sheet.frames ?? []).map((slot, at) => [slot.name, at]));
713
+ const requireFrame = (name) => {
714
+ const slot = frameSlots.get(name);
715
+ if (slot === undefined)
716
+ return invalidWrunFrame(name, 'undeclared frame slot');
717
+ return frames?.[slot];
718
+ };
719
+ const levels = sheet.levels?.map((declaration) => {
720
+ const { frame: slot, ...meta } = declaration;
721
+ const raw = requireFrame(slot);
722
+ // The frame host picks the pane or spans shape by the declaration's
723
+ // `span` (DL-time-anchored); the declaration cross-checks (DL-stacked
724
+ // series, DL-scale scale_max, the span shape) refuse as wrun_frame_invalid.
725
+ const frame = raw === undefined ? null : parseWrunLevelsFrame(raw, slot, declaration);
726
+ spend(wrunRenderValueBytes(meta));
727
+ if (frame) {
728
+ checkWrunLevelsFrame(declaration, frame, slot);
729
+ spend(wrunLevelsFrameBytes(frame));
730
+ }
731
+ return { ...meta, frame };
732
+ });
733
+ const panels = sheet.panels?.map((declaration) => {
734
+ const { frame: slot, ...meta } = declaration;
735
+ const raw = requireFrame(slot);
736
+ const frame = raw === undefined ? null : parseWrunPanelFrame(raw, slot, declaration);
737
+ spend(wrunRenderValueBytes(meta));
738
+ // The per-run chrome a frame carries beside its rows (SC17) is charged
739
+ // like the rows' values.
740
+ if (frame)
741
+ spend(16 * frame.rows.length + wrunRenderValueBytes(frame.rows) + wrunRenderValueBytes(frame.chrome));
742
+ return { ...meta, frame };
743
+ });
744
+ const matrices = sheet.matrices?.map((declaration) => {
745
+ const { frame: slot, ...meta } = declaration;
746
+ const raw = requireFrame(slot);
747
+ // The matrix selector parses the frame against the declaration and
748
+ // charges it (16 per cell + 8 per number + string bytes, MX-price-matrix).
749
+ const selected = selectWrunMatrix(declaration, raw, slot);
750
+ spend(wrunRenderValueBytes(meta) + selected.bytes);
751
+ return { ...meta, frame: selected.frame };
752
+ });
753
+ for (const drawing of sheet.drawings ?? []) {
754
+ if (drawing.kind === 'ladder' || drawing.kind === 'feed') {
755
+ const raw = requireFrame(drawing.frame);
756
+ const common = { name: drawing.name, createdBar: last?.row ?? 0, ts: last?.ts ?? 0 };
757
+ if (drawing.kind === 'ladder') {
758
+ const frame = raw === undefined ? null : parseWrunLadderFrame(raw, drawing.frame);
759
+ const divider = frame?.divider ?? drawing.divider;
760
+ const props = frame
761
+ ? {
762
+ title: wrunFrameTitle(frame) ?? declaredTitle(drawing.title) ?? drawing.name,
763
+ side: drawing.side,
764
+ ...(divider !== undefined ? { divider: { ...divider } } : {}),
765
+ rows: frame.rows,
766
+ }
767
+ : null;
768
+ spend(16 + wrunRenderValueBytes(common) + wrunRenderValueBytes(props) + (props ? 16 * props.rows.length : 0));
769
+ drawings.push({ ...common, kind: 'ladder', props });
770
+ }
771
+ else {
772
+ const frame = raw === undefined ? null : parseWrunFeedFrame(raw, drawing.frame);
773
+ const { anchor, offset, z } = drawing;
774
+ const props = frame
775
+ ? {
776
+ title: wrunFrameTitle(frame) ?? declaredTitle(drawing.title) ?? drawing.name,
777
+ lines: frame.lines,
778
+ ...(anchor !== undefined ? { anchor } : {}),
779
+ ...(offset !== undefined ? { offset: [...offset] } : {}),
780
+ ...(z !== undefined ? { z } : {}),
781
+ }
782
+ : null;
783
+ spend(16 + wrunRenderValueBytes(common) + wrunRenderValueBytes(props) + (props ? 16 * props.lines.length : 0));
784
+ drawings.push({ ...common, kind: 'feed', props });
785
+ }
786
+ continue;
787
+ }
788
+ if (drawing.kind === 'minicharts') {
789
+ // om's selection (runtime.ts selectRenderables): the frame through the
790
+ // one mapping every host shares, the accounting om's to the byte (16,
791
+ // 16 per panel and candle, the entry's carried values).
792
+ const raw = requireFrame(drawing.frame);
793
+ const props = raw === undefined
794
+ ? null
795
+ : wrunChartHostEnv()
796
+ .sharedHost()
797
+ .wrunMiniChartGridPayload(drawing, parseWrunMiniChartsFrame(raw, drawing.frame));
798
+ const z = drawing.z ?? 0;
799
+ spend(16 +
800
+ 16 * miniChartsEntries(props) +
801
+ wrunRenderValueBytes({ kind: drawing.kind, name: drawing.name, z, minicharts: props }));
802
+ drawings.push({
803
+ name: drawing.name,
804
+ createdBar: last?.row ?? 0,
805
+ ts: last?.ts ?? 0,
806
+ kind: 'minicharts',
807
+ z,
808
+ props,
809
+ });
810
+ continue;
811
+ }
812
+ if (drawing.kind === 'meter') {
813
+ const idx = requireOutput(`meter '${drawing.name}' fraction`, drawing.fraction.output);
814
+ const slot = typeof drawing.text === 'object' ? requireSlot(`meter '${drawing.name}' text`, drawing.text.slot) : undefined;
815
+ const fraction = last ? out(last, idx) : Number.NaN;
816
+ const text = slot !== undefined ? last?.strings[slot] : typeof drawing.text === 'string' ? drawing.text : undefined;
817
+ const valid = Number.isFinite(fraction) && fraction >= 0 && fraction <= 1 && (slot === undefined || text !== undefined);
818
+ const common = { name: drawing.name, createdBar: last?.row ?? 0, ts: last?.ts ?? 0 };
819
+ // The declared title's templates resolve on the meter's own row (the
820
+ // last ready one, DW14); an undeclared title is the name (DW15).
821
+ const props = valid && last !== undefined
822
+ ? {
823
+ title: drawing.title === undefined ? drawing.name : wrunResolveTemplate(drawing.title, last, templates),
824
+ label: drawing.label,
825
+ fraction,
826
+ ramp: [...drawing.ramp],
827
+ ...(text !== undefined ? { text } : {}),
828
+ ...(drawing.anchor !== undefined ? { anchor: drawing.anchor } : {}),
829
+ ...(drawing.offset !== undefined ? { offset: [...drawing.offset] } : {}),
830
+ ...(drawing.z !== undefined ? { z: drawing.z } : {}),
831
+ }
832
+ : null;
833
+ spend(16 + wrunRenderValueBytes(common) + wrunRenderValueBytes(props));
834
+ drawings.push({ ...common, kind: 'meter', props });
835
+ continue;
836
+ }
837
+ if (last === undefined)
838
+ continue;
839
+ if (drawing.kind === 'card') {
840
+ const card = selectCard(drawing, readyRows(), templates);
841
+ if (card) {
842
+ const { props } = card;
843
+ spend(16 +
844
+ 8 * 2 +
845
+ utf8ByteLength(card.name) +
846
+ utf8ByteLength(props.title) +
847
+ metaBytes(props.state) +
848
+ metaBytes(props.anchor) +
849
+ (props.offset !== undefined ? 16 : 0) +
850
+ (props.z !== undefined ? 8 : 0) +
851
+ (props.headline !== undefined
852
+ ? 16 + utf8ByteLength(props.headline.text) + metaBytes(props.headline.color)
853
+ : 0) +
854
+ props.rows.reduce((sum, row) => sum +
855
+ 16 +
856
+ utf8ByteLength(row.label) +
857
+ metaBytes(row.value) +
858
+ metaBytes(row.color) +
859
+ (row.countdown_to !== undefined ? 8 : 0) +
860
+ (row.clock ? 8 : 0) +
861
+ (row.spark ? 8 * row.spark.length : 0), 0));
862
+ drawings.push(card);
863
+ }
864
+ continue;
865
+ }
866
+ const style = {
867
+ ...('color' in drawing && drawing.color !== undefined ? { color: drawing.color } : {}),
868
+ ...('width' in drawing && drawing.width !== undefined ? { width: drawing.width } : {}),
869
+ ...('size' in drawing && drawing.size !== undefined ? { size: drawing.size } : {}),
870
+ ...('line_style' in drawing && drawing.line_style !== undefined ? { line_style: drawing.line_style } : {}),
871
+ };
872
+ // Copied metadata charges with the drawing it rides: the name, style
873
+ // strings by UTF-8 bytes, and 8 per style number.
874
+ const styleSpend = utf8ByteLength(drawing.name) +
875
+ metaBytes(style.color) +
876
+ metaBytes(style.line_style) +
877
+ (style.width !== undefined ? 8 : 0) +
878
+ (style.size !== undefined ? 8 : 0);
879
+ const finiteValues = (fields) => {
880
+ const values = {};
881
+ for (const [key, ref] of fields) {
882
+ const value = out(last, requireOutput(`${drawing.kind} drawing '${drawing.name}' ${key}`, ref));
883
+ if (!Number.isFinite(value))
884
+ return undefined;
885
+ values[key] = value;
886
+ }
887
+ return values;
888
+ };
889
+ switch (drawing.kind) {
890
+ case 'line': {
891
+ const values = finiteValues([
892
+ ['x1', drawing.x1],
893
+ ['y1', drawing.y1],
894
+ ['x2', drawing.x2],
895
+ ['y2', drawing.y2],
896
+ ]);
897
+ if (values === undefined)
898
+ break;
899
+ spend(16 + 8 * 2 + 8 * 4 + styleSpend);
900
+ drawings.push({ name: drawing.name, kind: 'line', createdBar: last.row, ts: last.ts, values, ...style });
901
+ break;
902
+ }
903
+ case 'box': {
904
+ const values = finiteValues([
905
+ ['left', drawing.left],
906
+ ['top', drawing.top],
907
+ ['right', drawing.right],
908
+ ['bottom', drawing.bottom],
909
+ ]);
910
+ if (values === undefined)
911
+ break;
912
+ // A declared `text` slot is read on the last ready row like a
913
+ // label's (DW31); unwritten there, the box simply carries no text.
914
+ const text = drawing.text === undefined
915
+ ? undefined
916
+ : last.strings[requireSlot(`box drawing '${drawing.name}' text`, drawing.text)];
917
+ spend(16 + 8 * 2 + 8 * 4 + metaBytes(text) + styleSpend);
918
+ drawings.push({
919
+ name: drawing.name,
920
+ kind: 'box',
921
+ createdBar: last.row,
922
+ ts: last.ts,
923
+ values,
924
+ ...(text !== undefined ? { text } : {}),
925
+ ...style,
926
+ });
927
+ break;
928
+ }
929
+ case 'polyline': {
930
+ const points = [];
931
+ let finite = true;
932
+ for (const [pointIdx, point] of drawing.points.entries()) {
933
+ const x = out(last, requireOutput(`polyline drawing '${drawing.name}' points[${pointIdx}].x`, point.x));
934
+ const y = out(last, requireOutput(`polyline drawing '${drawing.name}' points[${pointIdx}].y`, point.y));
935
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
936
+ finite = false;
937
+ break;
938
+ }
939
+ points.push({ x, y });
940
+ }
941
+ if (!finite)
942
+ break;
943
+ spend(16 + 8 * 2 + 16 * points.length + styleSpend);
944
+ drawings.push({
945
+ name: drawing.name,
946
+ kind: 'polyline',
947
+ createdBar: last.row,
948
+ ts: last.ts,
949
+ values: {},
950
+ points,
951
+ ...style,
952
+ });
953
+ break;
954
+ }
955
+ case 'label': {
956
+ const values = finiteValues([
957
+ ['x', drawing.x],
958
+ ['y', drawing.y],
959
+ ]);
960
+ if (values === undefined)
961
+ break;
962
+ const slot = requireSlot(`label drawing '${drawing.name}' text`, drawing.text);
963
+ const text = last.strings[slot];
964
+ if (text === undefined)
965
+ break;
966
+ spend(16 + 8 * 2 + 8 * 2 + utf8ByteLength(text) + styleSpend);
967
+ drawings.push({
968
+ name: drawing.name,
969
+ kind: 'label',
970
+ createdBar: last.row,
971
+ ts: last.ts,
972
+ values,
973
+ text,
974
+ ...style,
975
+ });
976
+ break;
977
+ }
978
+ }
979
+ }
980
+ const selection = {
981
+ renderers,
982
+ drawings,
983
+ ...(levels !== undefined ? { levels } : {}),
984
+ ...(panels !== undefined ? { panels } : {}),
985
+ ...(matrices !== undefined ? { matrices } : {}),
986
+ };
987
+ selectionBytes.set(selection, budget.spent - initialSpent);
988
+ return selection;
989
+ }
990
+ function selectCard(drawing, readyRows, templates) {
991
+ const { outputIndex, slotIndex, priceDigits } = templates;
992
+ const outputRefs = new Set();
993
+ const slotRefs = new Set();
994
+ if (drawing.state_by !== undefined)
995
+ outputRefs.add(drawing.state_by);
996
+ // The headline's references (DW01) and the title's template references
997
+ // (DW14) join the complete-row gate beside the rows'.
998
+ const { headline } = drawing;
999
+ if (headline !== undefined) {
1000
+ if (headline.output !== undefined)
1001
+ outputRefs.add(headline.output);
1002
+ if (headline.text !== undefined)
1003
+ slotRefs.add(headline.text);
1004
+ if (typeof headline.color === 'object')
1005
+ outputRefs.add(headline.color.color_by);
1006
+ }
1007
+ wrunTemplateRefs(drawing.title, templates, outputRefs, slotRefs);
1008
+ for (const row of drawing.rows) {
1009
+ if (typeof row.value === 'object') {
1010
+ if ('output' in row.value)
1011
+ outputRefs.add(row.value.output);
1012
+ else
1013
+ slotRefs.add(row.value.text);
1014
+ }
1015
+ if (typeof row.color === 'object')
1016
+ outputRefs.add(row.color.color_by);
1017
+ if (row.countdown_to !== undefined)
1018
+ outputRefs.add(row.countdown_to.output);
1019
+ wrunTemplateRefs(row.label, templates, outputRefs, slotRefs);
1020
+ if (row.spark !== undefined) {
1021
+ if (!Number.isInteger(row.spark.window) || row.spark.window < 2 || row.spark.window > 64) {
1022
+ throw new Error(`WRUN card '${drawing.name}' spark window must be an integer in 2..64`);
1023
+ }
1024
+ if (!outputIndex.has(row.spark.output)) {
1025
+ throw new Error(`WRUN card '${drawing.name}' spark references '${row.spark.output}', which does not name a declared numeric output`);
1026
+ }
1027
+ outputRefs.add(row.spark.output);
1028
+ }
1029
+ }
1030
+ // Missing declarations have no row data to gate on. Value references to
1031
+ // them stay empty; a declared but unwritten reference skips that row.
1032
+ const outputs = [...outputRefs].map((ref) => outputIndex.get(ref)).filter((index) => index !== undefined);
1033
+ const slots = [...slotRefs].map((ref) => slotIndex.get(ref)).filter((index) => index !== undefined);
1034
+ for (let at = readyRows.length - 1; at >= 0; at -= 1) {
1035
+ const ready = readyRows[at];
1036
+ if (!outputs.every((index) => Number.isFinite(ready.outputs[index])))
1037
+ continue;
1038
+ if (!slots.every((index) => ready.strings[index] !== undefined))
1039
+ continue;
1040
+ const output = (ref) => {
1041
+ const index = outputIndex.get(ref);
1042
+ return index === undefined ? Number.NaN : (ready.outputs[index] ?? Number.NaN);
1043
+ };
1044
+ const slotText = (ref) => {
1045
+ const index = slotIndex.get(ref);
1046
+ return index === undefined ? '' : (ready.strings[index] ?? '');
1047
+ };
1048
+ // A row's number: one of the card's four pre-WRUN-STYLE words alone
1049
+ // (`int`, `pct`, `usd`, `auto`, no companion) prints the text it always
1050
+ // printed, so an unchanged Indicator reads exactly as before on both
1051
+ // hosts (om formatWrunCardRowValue); every other word, and any row with
1052
+ // a `decimals`, `signed` or `unit` companion, prints through the shared
1053
+ // formatter (DW23) at the chart's digits. An undeclared format keeps the
1054
+ // six significant digits on both paths.
1055
+ const valueText = (value) => {
1056
+ if (typeof value !== 'object')
1057
+ return typeof value === 'number' && !Number.isFinite(value) ? '' : String(value);
1058
+ if ('text' in value)
1059
+ return slotText(value.text);
1060
+ const number = output(value.output);
1061
+ if (!Number.isFinite(number))
1062
+ return '';
1063
+ if (value.decimals === undefined && value.signed === undefined && value.unit === undefined) {
1064
+ const legacy = legacyCardRowText(number, value.format);
1065
+ if (legacy !== undefined)
1066
+ return legacy;
1067
+ }
1068
+ return formatWrunNumber(number, wrunCardNumberSpec(value, priceDigits));
1069
+ };
1070
+ // The row-colour ladder rule (floor, clamp a finite out-of-range index
1071
+ // to entry 0, no colour on a non-finite rung), shared by the rows and
1072
+ // the headline; a plain colour word rides verbatim. Daemon metadata owns
1073
+ // each palette on its row, so rows can use different ladders.
1074
+ const ladderColor = (color) => {
1075
+ if (typeof color !== 'object')
1076
+ return color;
1077
+ const rung = output(color.color_by);
1078
+ if (!Number.isFinite(rung))
1079
+ return undefined;
1080
+ return color.colors[Math.floor(rung)] ?? color.colors[0];
1081
+ };
1082
+ const rows = drawing.rows.map((row) => {
1083
+ const color = ladderColor(row.color);
1084
+ const countdown = row.countdown_to === undefined ? Number.NaN : output(row.countdown_to.output);
1085
+ const sparkIndex = row.spark === undefined ? undefined : outputIndex.get(row.spark.output);
1086
+ const spark = sparkIndex === undefined
1087
+ ? undefined
1088
+ : readyRows
1089
+ .slice(Math.max(0, at + 1 - row.spark.window), at + 1)
1090
+ .map((entry) => entry.outputs[sparkIndex])
1091
+ .filter(Number.isFinite);
1092
+ return {
1093
+ label: wrunResolveTemplate(row.label, ready, templates),
1094
+ ...(row.value !== undefined ? { value: valueText(row.value) } : {}),
1095
+ ...(color !== undefined ? { color } : {}),
1096
+ ...(Number.isFinite(countdown) ? { countdown_to: countdown } : {}),
1097
+ ...(row.clock === true ? { clock: true } : {}),
1098
+ ...(spark !== undefined ? { spark } : {}),
1099
+ };
1100
+ });
1101
+ let headlineSelection;
1102
+ if (headline !== undefined) {
1103
+ // One big number (the referenced output, formatted like a row value)
1104
+ // or one word (the referenced slot's text), in the ladder's colour.
1105
+ let text = headline.text === undefined ? '' : slotText(headline.text);
1106
+ if (headline.output !== undefined) {
1107
+ const number = output(headline.output);
1108
+ if (Number.isFinite(number))
1109
+ text = formatWrunNumber(number, wrunCardNumberSpec(headline, priceDigits));
1110
+ }
1111
+ const color = ladderColor(headline.color);
1112
+ headlineSelection = { text, ...(color !== undefined ? { color } : {}) };
1113
+ }
1114
+ const states = ['ok', 'armed', 'fired', 'error'];
1115
+ return {
1116
+ name: drawing.name,
1117
+ kind: 'card',
1118
+ createdBar: ready.row,
1119
+ ts: ready.ts,
1120
+ props: {
1121
+ title: wrunResolveTemplate(drawing.title, ready, templates),
1122
+ ...(drawing.state_by !== undefined ? { state: states[output(drawing.state_by)] ?? 'ok' } : {}),
1123
+ ...(drawing.anchor !== undefined ? { anchor: drawing.anchor } : {}),
1124
+ ...(drawing.offset !== undefined ? { offset: [...drawing.offset] } : {}),
1125
+ ...(drawing.z !== undefined ? { z: drawing.z } : {}),
1126
+ ...(headlineSelection !== undefined ? { headline: headlineSelection } : {}),
1127
+ rows,
1128
+ },
1129
+ };
1130
+ }
1131
+ return undefined;
1132
+ }
1133
+ /** UTF-8 byte length of a JS string without allocating (the selection
1134
+ * accounting's string unit; lone surrogates count as the 3 bytes their
1135
+ * U+FFFD replacement would encode to). */
1136
+ export function utf8ByteLength(value) {
1137
+ let bytes = 0;
1138
+ for (let i = 0; i < value.length; i += 1) {
1139
+ const code = value.charCodeAt(i);
1140
+ if (code < 0x80)
1141
+ bytes += 1;
1142
+ else if (code < 0x800)
1143
+ bytes += 2;
1144
+ else if (code >= 0xd800 && code < 0xdc00 && i + 1 < value.length) {
1145
+ const next = value.charCodeAt(i + 1);
1146
+ if (next >= 0xdc00 && next < 0xe000) {
1147
+ bytes += 4;
1148
+ i += 1;
1149
+ }
1150
+ else
1151
+ bytes += 3;
1152
+ }
1153
+ else
1154
+ bytes += 3;
1155
+ }
1156
+ return bytes;
1157
+ }