@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,171 @@
1
+ /**
2
+ * Typed text settings (wrun-5, openmarket docs/WRUN5_ABI.md, the capability
3
+ * round's section 3): the sheet contract's plain-text rule and byte caps,
4
+ * mirrored from the kit package's runtime entry, the shared host
5
+ * (`wrunHostPlainText`, the ABI tables' two caps, the channel's import and
6
+ * refusal names) so the dialog, the run path, the hosted-lane maps and the
7
+ * sandbox worker apply ONE rule from an import-free leaf the kScript socket
8
+ * worker and the boot graph may read (neither loads a package).
9
+ * tests/utility/wrun/wrun-text-params.kit-mirror.spec.ts pins every mirrored
10
+ * value against the installed host entry, code point by code point.
11
+ *
12
+ * The host owns the typed value and applies the rule BEFORE it reaches the
13
+ * module, the dialog, a legend, an alert arm or a cloud run:
14
+ * 1. CRLF and CR become LF.
15
+ * 2. Every Unicode format character goes (the bidi controls U+202A..U+202E
16
+ * and U+2066..U+2069, the zero-width characters, the byte order mark, the
17
+ * soft hyphen, the invisible operators, the rest of Cf), and every
18
+ * control character but the newline (C0, DEL, C1).
19
+ * 3. On a one-line setting (`multiline` absent or false) every newline
20
+ * becomes a space.
21
+ * 4. The bytes are bounded by the param's `max_bytes`: a longer value is
22
+ * refused at the dialog and never truncated silently; a persisted value
23
+ * over its cap (saved under an older, wider cap) reads as the declared
24
+ * default.
25
+ * The result is plain text wherever it is shown (never HTML, markdown or a
26
+ * link) and is never re-read as a template.
27
+ *
28
+ * Worker-safe on purpose (types only): the sandbox worker and the kScript
29
+ * socket worker read it, and neither graph may reach i18n or the chart
30
+ * constants (tests/workers/worker-runtime-boundary.spec.ts).
31
+ */
32
+ /** The bytes one text setting may carry (the string-slot cap, so a slot can
33
+ * echo a setting whole) and the cap a declaration gets when it names none
34
+ * (the shared host's ABI tables, maxTextParamBytes / defaultTextParamBytes). */
35
+ export const WRUN_MAX_TEXT_PARAM_BYTES = 4096;
36
+ export const WRUN_DEFAULT_TEXT_PARAM_BYTES = 256;
37
+ /** The characters a host strips from typed text at its boundary (the kit's
38
+ * WRUN_TEXT_DISGUISE_PATTERN, a pattern for the `u` flag, what the shared
39
+ * host's wrunHostPlainText strips): every Unicode format character and every
40
+ * control character but the newline. */
41
+ export const WRUN_TEXT_DISGUISE_PATTERN = '[\\p{Cf}\\u0000-\\u0009\\u000b-\\u001f\\u007f-\\u009f]';
42
+ const TEXT_DISGUISE_RE = new RegExp(WRUN_TEXT_DISGUISE_PATTERN, 'gu');
43
+ /** The wrun-5 text channel's two imports (the ones the shared host links under wrun-5). */
44
+ export const WRUN5_TEXT_IMPORTS = ['wrun:wrun_param_len', 'wrun:wrun_param_bytes'];
45
+ /** The refusal names a host raises on the text channel (codes of the shared
46
+ * host's refusal table), one per rule. */
47
+ export const WRUN5_TEXT_REFUSALS = {
48
+ /** A text import called outside init(). */
49
+ phase: 'wrun_text_param_phase',
50
+ /** The copy would land outside the module's exported memory. */
51
+ memory: 'wrun_text_param_memory',
52
+ };
53
+ const UTF8 = new TextEncoder();
54
+ /** Plain text, the way every host hands it on: CRLF and CR become LF, the
55
+ * disguise characters are removed, and on a one-line setting every newline
56
+ * becomes a space. What a module reads, a dialog shows and a legend carries. */
57
+ export function wrunPlainText(text, options = {}) {
58
+ const lines = text.replace(/\r\n?/g, '\n').replace(TEXT_DISGUISE_RE, '');
59
+ return options.multiline === true ? lines : lines.replace(/\n/g, ' ');
60
+ }
61
+ /** True when the text carries a character {@link wrunPlainText} would remove
62
+ * (or a newline on a one-line setting). */
63
+ export function wrunTextHasDisguise(text, options = {}) {
64
+ return wrunPlainText(text, options) !== text;
65
+ }
66
+ /** The UTF-8 byte length of a text: the unit a text param's init slot and
67
+ * its `max_bytes` speak in. */
68
+ export function wrunTextByteLength(text) {
69
+ return UTF8.encode(text).length;
70
+ }
71
+ /** The entities a legend suffix carries for one literal character: the HTML
72
+ * specials (TitanCharts writes `define.customTitle` through innerHTML after
73
+ * DOMPurify, which keeps `a[href]`, `img[src]` and `style`) and `$`
74
+ * (titan's own `$token` pass re-expands a string customTitle against the
75
+ * overlay's raw settings, so a typed `$period` must not read as one). The
76
+ * entities decode back to the characters at the innerHTML sink; a consumer
77
+ * that renders the suffix as text decodes them with
78
+ * {@link wrunLegendLiteralText}. */
79
+ const LEGEND_LITERAL_ENTITIES = [
80
+ ['&', '&'],
81
+ ['<', '&lt;'],
82
+ ['>', '&gt;'],
83
+ ['"', '&quot;'],
84
+ ["'", '&#39;'],
85
+ ['$', '&#36;'],
86
+ ];
87
+ /** A value inserted into a legend suffix as LITERAL text (guards G1 and G4):
88
+ * every HTML special and `$` as its entity, so the innerHTML legend shows
89
+ * the characters themselves, never a link, an image or a re-expanded token. */
90
+ export function wrunLegendLiteral(text) {
91
+ let out = text;
92
+ for (const [char, entity] of LEGEND_LITERAL_ENTITIES)
93
+ out = out.split(char).join(entity);
94
+ return out;
95
+ }
96
+ /** The inverse of {@link wrunLegendLiteral} for a consumer that renders the
97
+ * suffix as text (the indicator menu's inputs line): the six entities back
98
+ * to their characters, `&amp;` last so a literal `&lt;` typed by a user
99
+ * (escaped as `&amp;lt;`) comes back as `&lt;`, not `<`. */
100
+ export function wrunLegendLiteralText(text) {
101
+ let out = text;
102
+ for (const [char, entity] of [...LEGEND_LITERAL_ENTITIES].reverse())
103
+ out = out.split(entity).join(char);
104
+ return out;
105
+ }
106
+ /** A sheet param (or a declaration row) of the text kind. */
107
+ export function isWrunTextParam(param) {
108
+ return param.type === 'text';
109
+ }
110
+ /** The byte cap a text param enforces: its `max_bytes` when it is an integer
111
+ * within the contract's bounds, else the default cap. */
112
+ export function wrunTextParamCap(param) {
113
+ const cap = param.max_bytes;
114
+ return typeof cap === 'number' && Number.isInteger(cap) && cap >= 1 && cap <= WRUN_MAX_TEXT_PARAM_BYTES
115
+ ? cap
116
+ : WRUN_DEFAULT_TEXT_PARAM_BYTES;
117
+ }
118
+ /** The declared words of a text param, plain (a published sheet carries none
119
+ * of the stripped characters; the rule is applied again so a hand-edited
120
+ * sheet cannot smuggle one in). */
121
+ export function wrunTextParamDefault(param) {
122
+ const declared = typeof param.text_default === 'string' ? param.text_default : '';
123
+ return wrunPlainText(declared, { multiline: param.multiline === true });
124
+ }
125
+ /** A typed value as the host hands it on: plain text within the cap, or
126
+ * undefined when the value is not a string or its plain bytes are over the
127
+ * cap (the caller decides what stands in: the dialog refuses the edit, the
128
+ * run path reads the declared default). */
129
+ export function wrunTextValueWithinCap(raw, options) {
130
+ if (typeof raw !== 'string')
131
+ return undefined;
132
+ const plain = wrunPlainText(raw, { multiline: options.multiline === true });
133
+ const cap = options.maxBytes ?? WRUN_DEFAULT_TEXT_PARAM_BYTES;
134
+ return wrunTextByteLength(plain) <= cap ? plain : undefined;
135
+ }
136
+ /** One text param's run value from its flat setting: the stored string plain
137
+ * and within the cap, else the declared default. */
138
+ export function wrunTextParamValue(param, raw) {
139
+ const multiline = param.multiline === true;
140
+ return wrunTextValueWithinCap(raw, { multiline, maxBytes: wrunTextParamCap(param) }) ?? wrunTextParamDefault(param);
141
+ }
142
+ /** Every text param's run value by name (the ONE derivation the init slot's
143
+ * byte count, the text channel's bytes, the legend title and the hosted
144
+ * lanes' maps all read): the overlay's flat setting plain and within the
145
+ * cap, else the declared default. Empty for a sheet without text params. */
146
+ export function wrunTextParamValuesFromSettings(metadata, settings) {
147
+ const flat = settings !== null && typeof settings === 'object' ? settings : undefined;
148
+ const values = {};
149
+ for (const param of metadata.params ?? []) {
150
+ if (!isWrunTextParam(param))
151
+ continue;
152
+ values[param.name] = wrunTextParamValue(param, flat?.[param.name]);
153
+ }
154
+ return values;
155
+ }
156
+ /** The run request's text channel: the UTF-8 bytes of every text param keyed
157
+ * by its init slot (the param's index in `metadata.params`, the index
158
+ * `wrun_param_len` takes), derived from the same values the init slots'
159
+ * byte counts read. Undefined for a sheet without text params, so a
160
+ * wrun-1..4 request stays byte-identical to before. */
161
+ export function wrunTextParamsForRun(metadata, settings) {
162
+ const values = wrunTextParamValuesFromSettings(metadata, settings);
163
+ let slots;
164
+ (metadata.params ?? []).forEach((param, slot) => {
165
+ if (!isWrunTextParam(param))
166
+ return;
167
+ slots ??= {};
168
+ slots[slot] = UTF8.encode(values[param.name] ?? '');
169
+ });
170
+ return slots;
171
+ }
@@ -0,0 +1,71 @@
1
+ export type WrunTpoPeriod = 'day' | 'week' | 'month';
2
+ /** One price level of a period, the engine's 7-cell level tuple. */
3
+ export type WrunTpoLevelRow = [
4
+ price: number,
5
+ blockIds: number[],
6
+ tpoCount: number,
7
+ buyVolume: number,
8
+ sellVolume: number,
9
+ delta: number,
10
+ letters: string[]
11
+ ];
12
+ export interface WrunTpoPeriodMetrics {
13
+ periodStart: {
14
+ s: number;
15
+ };
16
+ periodEnd: {
17
+ s: number;
18
+ };
19
+ }
20
+ /** One period row: the period's start in ms, its levels ascending by price,
21
+ * then the metrics object (the engine reads the last cell as the metrics). */
22
+ export type WrunTpoPeriodRow = [number, ...Array<WrunTpoLevelRow | WrunTpoPeriodMetrics>];
23
+ export interface WrunTpoRowsInput {
24
+ /** The declaration name (the refusal names it). */
25
+ name: string;
26
+ period?: WrunTpoPeriod;
27
+ /** Minutes per letter, 1..240. */
28
+ letterMinutes: number;
29
+ /** The price row height, > 0. */
30
+ rowHeight: number;
31
+ /** The feeding bars' interval in ms: the chart's for candles and
32
+ * volume_profile rows, the leg's for an intrabar input. */
33
+ barIntervalMs: number;
34
+ /** Candle rows `[ts, open, high, low, close, volume]` (ms), the chart's own
35
+ * or an intrabar leg's; a price row counts every letter whose bar range
36
+ * covers it. */
37
+ bars?: ReadonlyArray<ArrayLike<number>>;
38
+ /** volume_profile rows `[ts, [low, high, buy, sell], ...]`; a bucket's
39
+ * volume lands on the row holding its midpoint. */
40
+ profileRows?: ReadonlyArray<ReadonlyArray<unknown>>;
41
+ /** The chart's exchange: CME-family venues anchor the day on the venue's open. */
42
+ exchange?: string;
43
+ /** The canvas this fold draws (`${overlayId}::tpo:${name}`): the periods it
44
+ * built are kept under it (wrun-canvas-cache.util) and a later call
45
+ * rebuilds only the periods whose rows changed. Absent: the whole fold. */
46
+ cacheKey?: string;
47
+ }
48
+ /**
49
+ * The refusal text when the letter is not a whole multiple of the feeding
50
+ * bars' interval (a 1h bar cannot say which 30-minute letter it traded in),
51
+ * undefined when the bars fit. The hint names an intrabar interval that
52
+ * divides the letter.
53
+ */
54
+ export declare function wrunTpoLetterMismatch(name: string, letterMinutes: number, barIntervalMs: number): string | undefined;
55
+ /** The most price rows one bar may expand into. A liquid venue's bar spans
56
+ * tens to a few hundred rows at the auto unit (a volatile BTC 15m bar at a
57
+ * 0.15 row sits near 4,000); a row height below the price noise would
58
+ * spend millions of rows per bar on every run and every tick, so the
59
+ * builder refuses it by name and the auto unit floors to fit (tpoChild). */
60
+ export declare const WRUN_TPO_MAX_ROWS_PER_BAR = 4096;
61
+ /** Spec probe: the source rows (bars or volume_profile rows) the last
62
+ * buildWrunTpoRows call walked to build levels; a warm call with a
63
+ * `cacheKey` walks only the periods whose rows changed. */
64
+ export declare function wrunTpoRowsLastFoldCount(): number;
65
+ /**
66
+ * Fold the feeding bars into TPO period rows (the engine's TPO_AGG shape).
67
+ * Throws the letter-mismatch refusal when the bars cannot place a letter.
68
+ * With a `cacheKey`, only the periods whose rows changed since the last call
69
+ * under that key are folded again; the rows equal the whole fold's.
70
+ */
71
+ export declare function buildWrunTpoRows(input: WrunTpoRowsInput): WrunTpoPeriodRow[];
@@ -0,0 +1,438 @@
1
+ /**
2
+ * TPO period rows for a wrun `plot.tpo` child (WRUN-STYLE g6 PT-tpo): the
3
+ * host folds the feeding bars (the chart's own candles, an intrabar leg's
4
+ * finer candles, or a volume_profile input's buckets) into the TPO_AGG row
5
+ * shape the engine already parses (titan renderers/tpo.ts extractTPOPeriod):
6
+ *
7
+ * [periodStartMs, ...levels, metrics]
8
+ * level = [price, blockIds[], tpoCount, buyVolume, sellVolume, delta, letters[]]
9
+ * metrics = { periodStart: { s }, periodEnd: { s } }
10
+ *
11
+ * A price row prints a letter for every letter interval of the period in
12
+ * which it traded (a bucket's volume lands on the row holding its midpoint)
13
+ * or lay inside a bar's high-low range (candles). Period bounds follow the
14
+ * native TPO session rules (tpo-session.util: the trading-day anchored day on
15
+ * CME-family venues, UTC days, ISO weeks and months elsewhere); letters come
16
+ * from generateTpoLettersTolerant. Single prints and poor extremes are not
17
+ * written: the engine derives them from the levels when the metrics omit
18
+ * them. Volumes come from volume_profile cells only (0 on candles).
19
+ *
20
+ * The forming period only (WRUN guardrails G3b): with a `cacheKey` the fold
21
+ * keeps every period it built in the canvas cache (wrun-canvas-cache.util),
22
+ * each with its rows' count and a content hash of the cells the fold reads,
23
+ * and a later call rebuilds only the periods whose rows changed: a live tick
24
+ * refolds the forming period, a day roll folds the new one (and the closed
25
+ * one once more when its last bar moved), a pan-back prepend folds the new
26
+ * days and the partial first one, a revised closed bar its own period. A
27
+ * parameter change (row height, period, letter minutes, exchange, bar
28
+ * interval) is another memo. The output equals the cache-less fold for every
29
+ * input: rows out of time order, or both sources at once, take that fold.
30
+ */
31
+ import { generateTpoLettersTolerant } from '../../indicators/controls/tpo-letter.util.js';
32
+ import { getNextTpoSessionStart, getTpoSessionStart, resolveTpoTimeRangeWindow, resolveTradingDayTpoTimeRange, } from '../../indicators/controls/tpo-session.util.js';
33
+ import { intervalLabelForMs } from '../chart/interval-ladder.util.js';
34
+ import { tpoPeriodWord } from '../chart/profile-row-height.util.js';
35
+ import { dropWrunCanvasCache, readWrunCanvasCache, writeWrunCanvasCache } from './wrun-canvas-cache.util.js';
36
+ const MINUTE_MS = 60_000;
37
+ function finite(value) {
38
+ return typeof value === 'number' && Number.isFinite(value);
39
+ }
40
+ /** A span's label for a message: the registry's interval word, else the ms count. */
41
+ function spanLabel(ms) {
42
+ return intervalLabelForMs(ms) ?? `${ms} ms`;
43
+ }
44
+ /**
45
+ * The refusal text when the letter is not a whole multiple of the feeding
46
+ * bars' interval (a 1h bar cannot say which 30-minute letter it traded in),
47
+ * undefined when the bars fit. The hint names an intrabar interval that
48
+ * divides the letter.
49
+ */
50
+ export function wrunTpoLetterMismatch(name, letterMinutes, barIntervalMs) {
51
+ const letterMs = letterMinutes * MINUTE_MS;
52
+ if (!finite(barIntervalMs) || barIntervalMs <= 0)
53
+ return undefined;
54
+ if (letterMs % barIntervalMs === 0)
55
+ return undefined;
56
+ const suggested = letterMinutes % 5 === 0 ? '5m' : '1m';
57
+ return (`tpo '${name}': ${letterMinutes}-minute letters need bars of ${letterMinutes} minutes or a whole divisor; ` +
58
+ `the bars here are ${spanLabel(barIntervalMs)} (declare an intrabar input with interval "${suggested}" and name it in cells)`);
59
+ }
60
+ /** The price of row `k` on the row grid, trimmed of float noise. */
61
+ function rowPrice(k, rowHeight) {
62
+ return Number((k * rowHeight).toPrecision(12));
63
+ }
64
+ function rowIndex(price, rowHeight) {
65
+ return Math.floor(price / rowHeight + 1e-9);
66
+ }
67
+ /** The most price rows one bar may expand into. A liquid venue's bar spans
68
+ * tens to a few hundred rows at the auto unit (a volatile BTC 15m bar at a
69
+ * 0.15 row sits near 4,000); a row height below the price noise would
70
+ * spend millions of rows per bar on every run and every tick, so the
71
+ * builder refuses it by name and the auto unit floors to fit (tpoChild). */
72
+ export const WRUN_TPO_MAX_ROWS_PER_BAR = 4096;
73
+ /** The refusal for a row height too fine for the bars it folds: a bar that
74
+ * expands past the row cap, or a row grid past the safe integer range,
75
+ * where `k + 1` no longer names the next row. */
76
+ function tpoRowGridRefusal(name, rowHeight, from, to, price) {
77
+ if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to)) {
78
+ return `tpo '${name}': row_height ${rowHeight} is too fine for prices near ${price} (the row grid runs past 2^53; declare a larger row_height)`;
79
+ }
80
+ return `tpo '${name}': row_height ${rowHeight} expands one bar into ${to - from + 1} price rows, above the ${WRUN_TPO_MAX_ROWS_PER_BAR}-row limit (declare a larger row_height)`;
81
+ }
82
+ function tpoFoldSpecOf(input) {
83
+ const sessionType = tpoPeriodWord(input.period ?? 'day');
84
+ const customTimeRange = resolveTradingDayTpoTimeRange({
85
+ sessionType,
86
+ ...(input.exchange !== undefined ? { exchange: input.exchange } : {}),
87
+ });
88
+ return {
89
+ name: input.name,
90
+ rowHeight: finite(input.rowHeight) && input.rowHeight > 0 ? input.rowHeight : 1,
91
+ sessionType,
92
+ customTimeRange,
93
+ letterSec: Math.max(1, Math.round(input.letterMinutes * 60)),
94
+ letterMinutes: input.letterMinutes,
95
+ };
96
+ }
97
+ function levelOf(period, k) {
98
+ let entry = period.levels.get(k);
99
+ if (entry === undefined) {
100
+ entry = { blocks: new Set(), buy: 0, sell: 0 };
101
+ period.levels.set(k, entry);
102
+ }
103
+ return entry;
104
+ }
105
+ /** A candle's rows on the grid, undefined for a row the fold skips (a time,
106
+ * high or low that is not a finite number, or a high under the low). */
107
+ function barRowSpan(spec, bar) {
108
+ const ts = bar[0];
109
+ const high = bar[2];
110
+ const low = bar[3];
111
+ if (!finite(ts) || !finite(high) || !finite(low) || high < low)
112
+ return undefined;
113
+ const from = rowIndex(low, spec.rowHeight);
114
+ const to = rowIndex(high, spec.rowHeight);
115
+ // Bounded before the walk: the row count per bar is capped and the grid
116
+ // indexes must be safe integers (past 2^53 `k + 1` stalls on `k`, and a
117
+ // `k <= to` loop never ends). The walk counts rows, never trusts `k`.
118
+ if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to) || to - from >= WRUN_TPO_MAX_ROWS_PER_BAR) {
119
+ throw new Error(tpoRowGridRefusal(spec.name, spec.rowHeight, from, to, low));
120
+ }
121
+ return { from, to };
122
+ }
123
+ function addBarRows(placed, span) {
124
+ for (let offset = 0; offset <= span.to - span.from; offset += 1) {
125
+ levelOf(placed.period, span.from + offset).blocks.add(placed.block);
126
+ }
127
+ }
128
+ /** A volume_profile row's buckets into its period, placed on the row's first
129
+ * usable bucket (a row without one places nothing). */
130
+ function addProfileRow(spec, row, place) {
131
+ let placed;
132
+ for (let at = 1; at < row.length; at += 1) {
133
+ const bucket = row[at];
134
+ if (!Array.isArray(bucket) || bucket.length < 4)
135
+ continue;
136
+ const [low, high, buy, sell] = bucket;
137
+ if (!finite(low) || !finite(high))
138
+ continue;
139
+ placed ??= place();
140
+ const entry = levelOf(placed.period, rowIndex((low + high) / 2, spec.rowHeight));
141
+ entry.blocks.add(placed.block);
142
+ if (finite(buy))
143
+ entry.buy += buy;
144
+ if (finite(sell))
145
+ entry.sell += sell;
146
+ }
147
+ }
148
+ /** A period's TPO_AGG row: the levels ascending by price, then the metrics. */
149
+ function periodRowOf(spec, period) {
150
+ const levels = [...period.levels.entries()]
151
+ .sort((a, b) => a[0] - b[0])
152
+ .map(([k, entry]) => {
153
+ const blockIds = [...entry.blocks].sort((a, b) => a - b);
154
+ return [
155
+ rowPrice(k, spec.rowHeight),
156
+ blockIds,
157
+ blockIds.length,
158
+ entry.buy,
159
+ entry.sell,
160
+ entry.buy - entry.sell,
161
+ generateTpoLettersTolerant(blockIds, spec.sessionType, spec.letterMinutes),
162
+ ];
163
+ });
164
+ const metrics = {
165
+ periodStart: { s: period.startSec },
166
+ periodEnd: { s: period.endSec },
167
+ };
168
+ return [period.startSec * 1000, ...levels, metrics];
169
+ }
170
+ /** The source rows the last call walked to build levels (the spec probe). */
171
+ let lastFoldRows = 0;
172
+ /** Spec probe: the source rows (bars or volume_profile rows) the last
173
+ * buildWrunTpoRows call walked to build levels; a warm call with a
174
+ * `cacheKey` walks only the periods whose rows changed. */
175
+ export function wrunTpoRowsLastFoldCount() {
176
+ return lastFoldRows;
177
+ }
178
+ /** The whole fold: every row placed by the session rule, every period built. */
179
+ function foldEveryRow(input, spec) {
180
+ const periods = new Map();
181
+ const place = (tsMs) => {
182
+ const sec = Math.floor(tsMs / 1000);
183
+ const startSec = getTpoSessionStart(sec, spec.sessionType, spec.customTimeRange);
184
+ let period = periods.get(startSec);
185
+ if (period === undefined) {
186
+ period = {
187
+ startSec,
188
+ endSec: getNextTpoSessionStart(sec, spec.sessionType, spec.customTimeRange),
189
+ levels: new Map(),
190
+ };
191
+ periods.set(startSec, period);
192
+ }
193
+ return { period, block: Math.max(0, Math.floor((sec - startSec) / spec.letterSec)) };
194
+ };
195
+ for (const bar of input.bars ?? []) {
196
+ lastFoldRows += 1;
197
+ const span = barRowSpan(spec, bar);
198
+ if (span === undefined)
199
+ continue;
200
+ addBarRows(place(bar[0]), span);
201
+ }
202
+ for (const row of input.profileRows ?? []) {
203
+ const ts = row[0];
204
+ if (!finite(ts))
205
+ continue;
206
+ lastFoldRows += 1;
207
+ addProfileRow(spec, row, () => place(ts));
208
+ }
209
+ return [...periods.values()].sort((a, b) => a.startSec - b.startSec).map((period) => periodRowOf(spec, period));
210
+ }
211
+ /** Parameter sets kept per canvas (the cap's retries fit). */
212
+ const WRUN_TPO_MEMOS_PER_KEY = 8;
213
+ // The content hash: two 32-bit lanes over the bits of every cell the fold
214
+ // reads, so a revised row anywhere in a period changes its hash. A cell that
215
+ // is not a finite number hashes as NaN: the fold treats every such cell alike.
216
+ const HASH_SEED_A = 0x2f6b9a3d;
217
+ const HASH_SEED_B = 0x1b873593;
218
+ const HASH_CELL = new Float64Array(1);
219
+ const HASH_HALVES = new Uint32Array(HASH_CELL.buffer);
220
+ let laneA = HASH_SEED_A;
221
+ let laneB = HASH_SEED_B;
222
+ function mixHash(hash, word) {
223
+ let k = Math.imul(word, 0xcc9e2d51);
224
+ k = (k << 15) | (k >>> 17);
225
+ k = Math.imul(k, 0x1b873593);
226
+ let h = hash ^ k;
227
+ h = (h << 13) | (h >>> 19);
228
+ return (Math.imul(h, 5) + 0xe6546b64) | 0;
229
+ }
230
+ function hashWord(word) {
231
+ laneA = mixHash(laneA, word);
232
+ laneB = mixHash(laneB, ~word);
233
+ }
234
+ function hashCell(value) {
235
+ HASH_CELL[0] = finite(value) ? value : Number.NaN;
236
+ const low = HASH_HALVES[0];
237
+ const high = HASH_HALVES[1];
238
+ laneA = mixHash(mixHash(laneA, low), high);
239
+ laneB = mixHash(mixHash(laneB, high), low);
240
+ }
241
+ /** The cells of one source row the fold reads: a candle's time, high and
242
+ * low; a volume_profile row's time and every bucket's shape and bounds and
243
+ * volumes. */
244
+ function hashSourceRow(kind, row) {
245
+ hashCell(row[0]);
246
+ if (kind === 'bars') {
247
+ hashCell(row[2]);
248
+ hashCell(row[3]);
249
+ return;
250
+ }
251
+ hashWord(row.length);
252
+ for (let at = 1; at < row.length; at += 1) {
253
+ const bucket = row[at];
254
+ if (!Array.isArray(bucket) || bucket.length < 4) {
255
+ hashWord(-1);
256
+ continue;
257
+ }
258
+ hashCell(bucket[0]);
259
+ hashCell(bucket[1]);
260
+ hashCell(bucket[2]);
261
+ hashCell(bucket[3]);
262
+ }
263
+ }
264
+ /**
265
+ * The first second a period's start no longer answers for: up to it, the whole
266
+ * fold's place() rule (getTpoSessionStart) maps every row from the period's
267
+ * first one to the period's start. That is the next start, except on a Daily
268
+ * trading-day range, whose window ends where its trading does (CME: 17:00 ET):
269
+ * the maintenance hour after it already belongs to the next session.
270
+ */
271
+ function tpoPeriodLimitSec(spec, startSec, endSec) {
272
+ if (spec.sessionType !== 'Daily')
273
+ return endSec;
274
+ const window = resolveTpoTimeRangeWindow(startSec, spec.customTimeRange);
275
+ return window !== undefined && window.endSec > startSec && window.endSec < endSec ? window.endSec : endSec;
276
+ }
277
+ /**
278
+ * The source's rows grouped by period, in time order, each group hashed.
279
+ * Every row lands where the whole fold places it (its session start, the
280
+ * fold's place() rule), looked up only when a row leaves the current period's
281
+ * window (`tpoPeriodLimitSec`), never per row: a memo period answers for its
282
+ * own window without a lookup, and a row the rule hands to the next period
283
+ * opens that period here too (a CME row in the 17:00 to 18:00 ET maintenance
284
+ * hour belongs to the session that opens at 18:00, at its first letter). Rows
285
+ * whose time is not a finite number are skipped, as the fold skips them.
286
+ * Undefined when the rows are not in time order or their periods are not:
287
+ * the caller takes the whole fold.
288
+ */
289
+ function groupTpoRows(source, spec, held) {
290
+ const groups = [];
291
+ const rows = source.rows;
292
+ let group;
293
+ let lastTs = Number.NEGATIVE_INFINITY;
294
+ let heldAt = 0;
295
+ const close = () => {
296
+ if (group === undefined)
297
+ return;
298
+ group.hashA = laneA;
299
+ group.hashB = laneB;
300
+ };
301
+ for (let at = 0; at < rows.length; at += 1) {
302
+ const row = rows[at];
303
+ const ts = row[0];
304
+ if (!finite(ts))
305
+ continue;
306
+ if (ts < lastTs)
307
+ return undefined;
308
+ lastTs = ts;
309
+ const sec = Math.floor(ts / 1000);
310
+ if (group === undefined || sec >= group.limitSec) {
311
+ // The row leaves the current period's window: a memo period whose window holds it
312
+ // answers, else the session rule does.
313
+ while (heldAt < held.length && held[heldAt].limitSec <= sec)
314
+ heldAt += 1;
315
+ const covering = heldAt < held.length && held[heldAt].startSec <= sec ? held[heldAt] : undefined;
316
+ const startSec = covering?.startSec ?? getTpoSessionStart(sec, spec.sessionType, spec.customTimeRange);
317
+ if (group !== undefined && startSec === group.startSec) {
318
+ // Still the period past its limit (a range whose window ends before its next start).
319
+ group.limitSec = sec + 1;
320
+ }
321
+ else {
322
+ if (group !== undefined && startSec < group.endSec)
323
+ return undefined;
324
+ close();
325
+ const memo = heldAt < held.length && held[heldAt].startSec === startSec ? held[heldAt] : undefined;
326
+ const endSec = memo?.endSec ?? getNextTpoSessionStart(sec, spec.sessionType, spec.customTimeRange);
327
+ const limitSec = memo?.limitSec ?? tpoPeriodLimitSec(spec, startSec, endSec);
328
+ group = { startSec, endSec, limitSec, first: at, last: at, count: 0, hashA: 0, hashB: 0, held: memo };
329
+ groups.push(group);
330
+ laneA = HASH_SEED_A;
331
+ laneB = HASH_SEED_B;
332
+ }
333
+ }
334
+ group.last = at;
335
+ group.count += 1;
336
+ hashSourceRow(source.kind, row);
337
+ }
338
+ close();
339
+ return groups;
340
+ }
341
+ /** One group's period row, folded from its own rows (null when they place nothing). */
342
+ function foldTpoGroup(spec, source, group) {
343
+ const built = {};
344
+ const placeAt = (sec) => {
345
+ built.period ??= {
346
+ startSec: group.startSec,
347
+ endSec: getNextTpoSessionStart(sec, spec.sessionType, spec.customTimeRange),
348
+ levels: new Map(),
349
+ };
350
+ return { period: built.period, block: Math.max(0, Math.floor((sec - group.startSec) / spec.letterSec)) };
351
+ };
352
+ for (let at = group.first; at <= group.last; at += 1) {
353
+ if (source.kind === 'bars') {
354
+ const bar = source.rows[at];
355
+ if (!finite(bar[0]))
356
+ continue;
357
+ lastFoldRows += 1;
358
+ const span = barRowSpan(spec, bar);
359
+ if (span !== undefined)
360
+ addBarRows(placeAt(Math.floor(bar[0] / 1000)), span);
361
+ }
362
+ else {
363
+ const row = source.rows[at];
364
+ const ts = row[0];
365
+ if (!finite(ts))
366
+ continue;
367
+ lastFoldRows += 1;
368
+ addProfileRow(spec, row, () => placeAt(Math.floor(ts / 1000)));
369
+ }
370
+ }
371
+ return built.period === undefined ? null : periodRowOf(spec, built.period);
372
+ }
373
+ /** The memo key of a call: every term a period row depends on. */
374
+ function tpoFoldParams(input, spec, kind) {
375
+ return [kind, spec.rowHeight, spec.sessionType, input.letterMinutes, input.exchange ?? '', input.barIntervalMs].join('|');
376
+ }
377
+ /** The fold under a `cacheKey`: every period whose rows match the memo's
378
+ * count and hash keeps its row, the others fold again; the memo becomes
379
+ * this call's periods. */
380
+ function foldWithMemo(input, spec, cacheKey) {
381
+ const bars = input.bars ?? [];
382
+ const profileRows = input.profileRows ?? [];
383
+ // Both sources at once never comes from a canvas child: the whole fold.
384
+ if (bars.length > 0 && profileRows.length > 0)
385
+ return foldEveryRow(input, spec);
386
+ const source = profileRows.length > 0 ? { kind: 'profile', rows: profileRows } : { kind: 'bars', rows: bars };
387
+ const params = tpoFoldParams(input, spec, source.kind);
388
+ const cached = readWrunCanvasCache(cacheKey);
389
+ const memos = cached?.kind === 'tpo' ? cached.memos.filter((memo) => memo.params !== params) : [];
390
+ const memo = cached?.kind === 'tpo' ? cached.memos.find((entry) => entry.params === params) : undefined;
391
+ const groups = groupTpoRows(source, spec, memo?.periods ?? []);
392
+ if (groups === undefined) {
393
+ // Rows out of time order: the whole fold, and this parameter set's memo goes.
394
+ if (memos.length > 0)
395
+ writeWrunCanvasCache(cacheKey, { kind: 'tpo', memos });
396
+ else
397
+ dropWrunCanvasCache(cacheKey);
398
+ return foldEveryRow(input, spec);
399
+ }
400
+ const rows = [];
401
+ const periods = [];
402
+ for (const group of groups) {
403
+ const held = group.held;
404
+ const row = held !== undefined && held.count === group.count && held.hashA === group.hashA && held.hashB === group.hashB
405
+ ? held.row
406
+ : foldTpoGroup(spec, source, group);
407
+ periods.push({
408
+ startSec: group.startSec,
409
+ endSec: group.endSec,
410
+ limitSec: group.limitSec,
411
+ count: group.count,
412
+ hashA: group.hashA,
413
+ hashB: group.hashB,
414
+ row,
415
+ });
416
+ if (row !== null)
417
+ rows.push(row);
418
+ }
419
+ memos.push({ params, periods });
420
+ if (memos.length > WRUN_TPO_MEMOS_PER_KEY)
421
+ memos.splice(0, memos.length - WRUN_TPO_MEMOS_PER_KEY);
422
+ writeWrunCanvasCache(cacheKey, { kind: 'tpo', memos });
423
+ return rows;
424
+ }
425
+ /**
426
+ * Fold the feeding bars into TPO period rows (the engine's TPO_AGG shape).
427
+ * Throws the letter-mismatch refusal when the bars cannot place a letter.
428
+ * With a `cacheKey`, only the periods whose rows changed since the last call
429
+ * under that key are folded again; the rows equal the whole fold's.
430
+ */
431
+ export function buildWrunTpoRows(input) {
432
+ const mismatch = wrunTpoLetterMismatch(input.name, input.letterMinutes, input.barIntervalMs);
433
+ if (mismatch !== undefined)
434
+ throw new Error(mismatch);
435
+ lastFoldRows = 0;
436
+ const spec = tpoFoldSpecOf(input);
437
+ return input.cacheKey === undefined ? foldEveryRow(input, spec) : foldWithMemo(input, spec, input.cacheKey);
438
+ }