@orangecharts/wrun-chart-host 0.5.0 → 0.7.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 (157) hide show
  1. package/README.md +17 -8
  2. package/dist/constants/feature-flags.constants.js +7 -2
  3. package/dist/constants/marketCapabilities.constants.d.ts +5 -0
  4. package/dist/constants/marketCapabilities.constants.js +16 -0
  5. package/dist/host-env.d.ts +3 -19
  6. package/dist/host-ports.types.d.ts +36 -17
  7. package/dist/index.d.ts +12 -1
  8. package/dist/index.js +12 -1
  9. package/dist/indicators/controls/tpo-session.util.js +42 -18
  10. package/dist/interfaces/wrun-runtime.interface.d.ts +88 -13
  11. package/dist/interfaces/wrun-runtime.interface.js +17 -3
  12. package/dist/market-data/billing.interface.d.ts +2 -1
  13. package/dist/settings-templates/indicator-fields.js +10 -0
  14. package/dist/utility/chart/chart-mount-epoch.util.d.ts +12 -0
  15. package/dist/utility/chart/chart-mount-epoch.util.js +32 -0
  16. package/dist/utility/chart/crypto-index.leaf.d.ts +16 -0
  17. package/dist/utility/chart/crypto-index.leaf.js +19 -0
  18. package/dist/utility/chart/index-mode-admission.util.js +9 -1
  19. package/dist/utility/chart/index-mode.util.d.ts +11 -5
  20. package/dist/utility/chart/index-mode.util.js +22 -10
  21. package/dist/utility/chart/kscript-source-answer-budget.leaf.d.ts +36 -0
  22. package/dist/utility/chart/kscript-source-answer-budget.leaf.js +39 -0
  23. package/dist/utility/chart/kscript-source-degrade.leaf.d.ts +38 -1
  24. package/dist/utility/chart/kscript-source-degrade.leaf.js +39 -1
  25. package/dist/utility/chart/live-bucket.util.d.ts +2 -1
  26. package/dist/utility/chart/live-bucket.util.js +47 -15
  27. package/dist/utility/chart/local-kscript-warmup-depth.util.d.ts +15 -1
  28. package/dist/utility/chart/local-kscript-warmup-depth.util.js +9 -0
  29. package/dist/utility/chart/market-session-schedule.util.d.ts +3 -1
  30. package/dist/utility/chart/market-session-schedule.util.js +24 -2
  31. package/dist/utility/chart/marketKind.util.d.ts +12 -7
  32. package/dist/utility/chart/marketKind.util.js +15 -5
  33. package/dist/utility/chart/ny-calendar.util.d.ts +104 -0
  34. package/dist/utility/chart/ny-calendar.util.js +346 -0
  35. package/dist/utility/chart/om-panel.util.d.ts +14 -2
  36. package/dist/utility/chart/om-panel.util.js +108 -40
  37. package/dist/utility/chart/rth-session.util.d.ts +10 -7
  38. package/dist/utility/chart/rth-session.util.js +17 -22
  39. package/dist/utility/chart/trading-day.util.js +90 -18
  40. package/dist/utility/chart/us-equities-session.util.js +20 -67
  41. package/dist/utility/chart/wrun-bar-session-facts.util.js +14 -1
  42. package/dist/utility/common/time.util.d.ts +7 -1
  43. package/dist/utility/common/time.util.js +11 -41
  44. package/dist/utility/number-format.util.d.ts +17 -7
  45. package/dist/utility/number-format.util.js +18 -8
  46. package/dist/utility/options/option-symbol.util.js +13 -2
  47. package/dist/utility/symbol-selection/contract-expiry.util.js +9 -1
  48. package/dist/utility/watchlist/import/import-request.leaf.d.ts +4 -1
  49. package/dist/utility/watchlist/import/import-request.leaf.js +5 -2
  50. package/dist/utility/watchlist/import/tradingview-symbols.leaf.d.ts +25 -4
  51. package/dist/utility/watchlist/import/tradingview-symbols.leaf.js +62 -4
  52. package/dist/utility/wrun/run-schedule/wrun-chart-gate-reader.util.d.ts +19 -0
  53. package/dist/utility/wrun/run-schedule/wrun-chart-gate-reader.util.js +57 -0
  54. package/dist/utility/wrun/run-schedule/wrun-gate-reader-warm.util.d.ts +23 -0
  55. package/dist/utility/wrun/run-schedule/wrun-gate-reader-warm.util.js +90 -0
  56. package/dist/utility/wrun/run-schedule/wrun-lane-groups.util.d.ts +39 -0
  57. package/dist/utility/wrun/run-schedule/wrun-lane-groups.util.js +60 -0
  58. package/dist/utility/wrun/run-schedule/wrun-late-reads.util.d.ts +77 -0
  59. package/dist/utility/wrun/run-schedule/wrun-late-reads.util.js +195 -0
  60. package/dist/utility/wrun/run-schedule/wrun-own-candles.util.d.ts +56 -0
  61. package/dist/utility/wrun/run-schedule/wrun-own-candles.util.js +70 -0
  62. package/dist/utility/wrun/run-schedule/wrun-prefix-feeds.util.d.ts +53 -0
  63. package/dist/utility/wrun/run-schedule/wrun-prefix-feeds.util.js +239 -0
  64. package/dist/utility/wrun/sources/lanes/option_stats_10m.d.ts +16 -0
  65. package/dist/utility/wrun/sources/lanes/option_stats_10m.js +14 -0
  66. package/dist/utility/wrun/sources/lanes/options_flow.d.ts +43 -18
  67. package/dist/utility/wrun/sources/lanes/options_flow.js +209 -72
  68. package/dist/utility/wrun/sources/lanes/token_supply.js +5 -31
  69. package/dist/utility/wrun/sources/opra-option-lanes.util.d.ts +3 -18
  70. package/dist/utility/wrun/sources/opra-option-lanes.util.js +12 -57
  71. package/dist/utility/wrun/sources/row-lane-registry.d.ts +1 -1
  72. package/dist/utility/wrun/sources/row-lane-registry.js +22 -8
  73. package/dist/utility/wrun/sources/row-lanes/option_contract_flow.d.ts +61 -0
  74. package/dist/utility/wrun/sources/row-lanes/option_contract_flow.js +103 -8
  75. package/dist/utility/wrun/sources/row-lanes/option_contract_state.d.ts +5 -0
  76. package/dist/utility/wrun/sources/row-lanes/option_contract_state.js +24 -12
  77. package/dist/utility/wrun/sources/row-lanes/option_prints.d.ts +55 -0
  78. package/dist/utility/wrun/sources/row-lanes/option_prints.js +95 -18
  79. package/dist/utility/wrun/sources/row-lanes/option_strikes.d.ts +15 -1
  80. package/dist/utility/wrun/sources/row-lanes/option_strikes.js +23 -8
  81. package/dist/utility/wrun/sources/row-lanes/option_surface.js +11 -11
  82. package/dist/utility/wrun/sources/wrun-poll-lane.types.d.ts +14 -2
  83. package/dist/utility/wrun/sources/wrun-poll-lane.types.js +6 -3
  84. package/dist/utility/wrun/sources/wrun-poll-lanes.util.d.ts +43 -8
  85. package/dist/utility/wrun/sources/wrun-poll-lanes.util.js +77 -11
  86. package/dist/utility/wrun/sources/wrun-row-lane.types.d.ts +31 -16
  87. package/dist/utility/wrun/sources/wrun-row-lane.types.js +2 -0
  88. package/dist/utility/wrun/sources/wrun-row-lanes.util.d.ts +52 -12
  89. package/dist/utility/wrun/sources/wrun-row-lanes.util.js +110 -46
  90. package/dist/utility/wrun/wrun-bar-count.util.d.ts +17 -6
  91. package/dist/utility/wrun/wrun-bar-count.util.js +27 -12
  92. package/dist/utility/wrun/wrun-browser-sources.leaf.d.ts +10 -0
  93. package/dist/utility/wrun/wrun-browser-sources.leaf.js +12 -0
  94. package/dist/utility/wrun/wrun-coin-lane-live.util.d.ts +3 -3
  95. package/dist/utility/wrun/wrun-coin-lane-live.util.js +53 -18
  96. package/dist/utility/wrun/wrun-color-settings.util.d.ts +6 -0
  97. package/dist/utility/wrun/wrun-color-settings.util.js +45 -0
  98. package/dist/utility/wrun/wrun-draft-overlay.util.js +14 -8
  99. package/dist/utility/wrun/wrun-failure-cause.d.ts +1 -1
  100. package/dist/utility/wrun/wrun-failure-cause.js +14 -0
  101. package/dist/utility/wrun/wrun-frames.js +6 -2
  102. package/dist/utility/wrun/wrun-host.service.d.ts +131 -59
  103. package/dist/utility/wrun/wrun-host.service.js +391 -194
  104. package/dist/utility/wrun/wrun-hosted-wire-caps.d.ts +1 -1
  105. package/dist/utility/wrun/wrun-hosted-wire-caps.js +2 -0
  106. package/dist/utility/wrun/wrun-hover.util.d.ts +3 -0
  107. package/dist/utility/wrun/wrun-hover.util.js +25 -4
  108. package/dist/utility/wrun/wrun-input-requirements.leaf.js +7 -4
  109. package/dist/utility/wrun/wrun-kit-run-tables.util.d.ts +24 -0
  110. package/dist/utility/wrun/wrun-kit-run-tables.util.js +87 -0
  111. package/dist/utility/wrun/wrun-lifecycle.contract.d.ts +2 -1
  112. package/dist/utility/wrun/wrun-live-tick.util.d.ts +8 -2
  113. package/dist/utility/wrun/wrun-live-tick.util.js +35 -16
  114. package/dist/utility/wrun/wrun-opra-flow.leaf.d.ts +40 -13
  115. package/dist/utility/wrun/wrun-opra-flow.leaf.js +39 -12
  116. package/dist/utility/wrun/wrun-option-contract-flow.util.d.ts +70 -21
  117. package/dist/utility/wrun/wrun-option-contract-flow.util.js +257 -112
  118. package/dist/utility/wrun/wrun-option-prints.util.d.ts +62 -22
  119. package/dist/utility/wrun/wrun-option-prints.util.js +148 -46
  120. package/dist/utility/wrun/wrun-option-views.util.d.ts +262 -0
  121. package/dist/utility/wrun/wrun-option-views.util.js +356 -0
  122. package/dist/utility/wrun/wrun-options-chain.util.d.ts +23 -2
  123. package/dist/utility/wrun/wrun-options-chain.util.js +37 -3
  124. package/dist/utility/wrun/wrun-overlay-drivers.util.d.ts +20 -5
  125. package/dist/utility/wrun/wrun-overlay-drivers.util.js +32 -7
  126. package/dist/utility/wrun/wrun-overlay-recovery.util.d.ts +9 -3
  127. package/dist/utility/wrun/wrun-overlay-recovery.util.js +146 -18
  128. package/dist/utility/wrun/wrun-overlay-run.util.d.ts +52 -8
  129. package/dist/utility/wrun/wrun-overlay-run.util.js +816 -243
  130. package/dist/utility/wrun/wrun-pack.util.d.ts +2 -1
  131. package/dist/utility/wrun/wrun-pin-spelling.util.d.ts +5 -0
  132. package/dist/utility/wrun/wrun-pin-spelling.util.js +28 -12
  133. package/dist/utility/wrun/wrun-pin-venues.util.js +4 -6
  134. package/dist/utility/wrun/wrun-prefix-cohort.util.d.ts +1 -1
  135. package/dist/utility/wrun/wrun-prefix-cohort.util.js +1 -1
  136. package/dist/utility/wrun/wrun-present-bits.util.d.ts +9 -0
  137. package/dist/utility/wrun/wrun-present-bits.util.js +39 -0
  138. package/dist/utility/wrun/wrun-refusal-surface.util.d.ts +3 -2
  139. package/dist/utility/wrun/wrun-refusal-surface.util.js +5 -4
  140. package/dist/utility/wrun/wrun-refusal.util.d.ts +66 -6
  141. package/dist/utility/wrun/wrun-refusal.util.js +335 -40
  142. package/dist/utility/wrun/wrun-registry-errors.util.d.ts +5 -3
  143. package/dist/utility/wrun/wrun-sandbox-row-source.d.ts +2 -2
  144. package/dist/utility/wrun/wrun-sha256.leaf.d.ts +13 -0
  145. package/dist/utility/wrun/wrun-sha256.leaf.js +84 -0
  146. package/dist/utility/wrun/wrun-source-rows.util.js +11 -0
  147. package/dist/utility/wrun/wrun-tier-grid.util.d.ts +28 -3
  148. package/dist/utility/wrun/wrun-tier-grid.util.js +79 -19
  149. package/dist/utility/wrun/wrun-transient-rerun.util.d.ts +14 -3
  150. package/dist/utility/wrun/wrun-transient-rerun.util.js +33 -8
  151. package/dist/workers/wrun/wrun-abi-host.d.ts +15 -2
  152. package/dist/workers/wrun/wrun-abi-host.js +31 -12
  153. package/dist/workers/wrun/wrun-engine-handler.d.ts +11 -28
  154. package/dist/workers/wrun/wrun-engine-handler.js +181 -12
  155. package/package.json +5 -5
  156. package/dist/utility/wrun/wrun-opra-underlying.util.d.ts +0 -12
  157. package/dist/utility/wrun/wrun-opra-underlying.util.js +0 -1
@@ -0,0 +1,84 @@
1
+ /**
2
+ * SHA-256 of a wrun module's bytes, synchronously and with no global: the engine worker's load path
3
+ * (wrun-engine-handler.ts) hashes every module it is handed before it checks the sheet's `wasm_sha256` pin, and mints
4
+ * the module's cache key from the digest. The main thread never hashes a module (wrun-host.service.ts posts the bytes
5
+ * and reads the digest off the worker's reply), so nothing here may reach for `crypto.subtle`: it is missing outside a
6
+ * secure context, it answers only through a promise, and the worker's load has no await to spare before its cache
7
+ * entry exists.
8
+ *
9
+ * Ported from the phone's `wrunSha256Hex` (kiyotaka-frontend-app chart-web/src/wrun/wrun-memory-clamp.ts:242), which
10
+ * phase A moves onto this leaf before its own copy goes. FIPS 180-4 sections 4.2.2 and 5.3.3.
11
+ */
12
+ // The round constants, typed out rather than derived from the prime roots at load: a derived table would hang on each
13
+ // engine's Math.cbrt rounding, and a wrong constant refuses every package.
14
+ const SHA256_K = new Uint32Array([
15
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98,
16
+ 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
17
+ 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8,
18
+ 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
19
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
20
+ 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
21
+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
22
+ 0xc67178f2,
23
+ ]);
24
+ const SHA256_INIT = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
25
+ // One 64-byte block into `state`. Sums stay exact in doubles (five terms under 2^35), and the Uint32Array stores wrap
26
+ // them mod 2^32, which is the algorithm's own addition.
27
+ function sha256Block(state, w, view, offset) {
28
+ for (let i = 0; i < 16; i += 1)
29
+ w[i] = view.getUint32(offset + i * 4);
30
+ for (let i = 16; i < 64; i += 1) {
31
+ const x = w[i - 15];
32
+ const y = w[i - 2];
33
+ const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
34
+ const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
35
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1;
36
+ }
37
+ let [a, b, c, d, e, f, g, h] = state;
38
+ for (let i = 0; i < 64; i += 1) {
39
+ const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
40
+ const t1 = (h + s1 + ((e & f) ^ (~e & g)) + SHA256_K[i] + w[i]) | 0;
41
+ const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
42
+ const t2 = (s0 + ((a & b) ^ (a & c) ^ (b & c))) | 0;
43
+ h = g;
44
+ g = f;
45
+ f = e;
46
+ e = (d + t1) | 0;
47
+ d = c;
48
+ c = b;
49
+ b = a;
50
+ a = (t1 + t2) | 0;
51
+ }
52
+ state[0] += a;
53
+ state[1] += b;
54
+ state[2] += c;
55
+ state[3] += d;
56
+ state[4] += e;
57
+ state[5] += f;
58
+ state[6] += g;
59
+ state[7] += h;
60
+ }
61
+ /** SHA-256 of `bytes` (the view's own range) as 64 lowercase hex digits, synchronously. */
62
+ export function wrunSha256Hex(bytes) {
63
+ const state = Uint32Array.from(SHA256_INIT);
64
+ const w = new Uint32Array(64);
65
+ const length = bytes.byteLength;
66
+ const fullBlocks = Math.floor(length / 64);
67
+ const view = new DataView(bytes.buffer, bytes.byteOffset, length);
68
+ for (let block = 0; block < fullBlocks; block += 1)
69
+ sha256Block(state, w, view, block * 64);
70
+ const rest = length - fullBlocks * 64;
71
+ const tail = new Uint8Array(rest + 9 <= 64 ? 64 : 128);
72
+ tail.set(bytes.subarray(fullBlocks * 64));
73
+ tail[rest] = 0x80;
74
+ const tailView = new DataView(tail.buffer);
75
+ // The message length in bits, big-endian over the last 8 bytes: the high word first (length * 8 / 2^32).
76
+ tailView.setUint32(tail.length - 8, Math.floor(length / 0x20000000));
77
+ tailView.setUint32(tail.length - 4, (length * 8) >>> 0);
78
+ for (let offset = 0; offset < tail.length; offset += 64)
79
+ sha256Block(state, w, tailView, offset);
80
+ let hex = '';
81
+ for (let i = 0; i < 8; i += 1)
82
+ hex += state[i].toString(16).padStart(8, '0');
83
+ return hex;
84
+ }
@@ -352,6 +352,8 @@ import { findMonday } from '../chart/titan-constants.pin.js';
352
352
  import { wrunBarSessionFactsResolver, } from '../chart/wrun-bar-session-facts.util.js';
353
353
  import { wrunSettingRefusedMessage } from '../scriptEditor/wrun-runtime-diagnostics.leaf.js';
354
354
  import { attachWrunRefusal, wrunPinFinerSeed } from './wrun-refusal.util.js';
355
+ import { WRUN_BROWSER_REFUSED_CLASS_CODES } from './wrun-browser-sources.leaf.js';
356
+ import { wrunProtocolPendingSeed } from './wrun-protocol-pending.util.js';
355
357
  import { planWrunRowLaneInputs, wrunRowLaneCellRows } from './sources/wrun-row-lanes.util.js';
356
358
  import { wrunTradesLaneOf, wrunTradesLegLaneOf, wrunTradesLegOf } from './wrun-trades-lane.util.js';
357
359
  import { planWrunPollLaneInputs } from './sources/wrun-poll-lanes.util.js';
@@ -1964,6 +1966,15 @@ function checkWrunRowReads(metadata, sources, clock, hasRows) {
1964
1966
  * (the browser's per-row refusals, raised once). */
1965
1967
  function checkWrunLaneRead(metadata, input, source) {
1966
1968
  const unknownField = () => new Error(`WRUN ${metadata.id}: unknown ${source.source} field '${source.field}' (input '${input.name}')`);
1969
+ // A class the kit serves on the chart that the chart cannot read yet refuses by the kit's own code of the class,
1970
+ // its record the protocol gate's (wrun-browser-sources.leaf WRUN_BROWSER_REFUSED_CLASS_CODES).
1971
+ const refusedCode = Object.prototype.hasOwnProperty.call(WRUN_BROWSER_REFUSED_CLASS_CODES, source.source)
1972
+ ? WRUN_BROWSER_REFUSED_CLASS_CODES[source.source]
1973
+ : undefined;
1974
+ if (refusedCode !== undefined) {
1975
+ throw attachWrunRefusal(new Error(`WRUN ${metadata.id}: input '${input.name}' reads ${source.source}, which this version of the app cannot ` +
1976
+ `read yet (${refusedCode})`), wrunProtocolPendingSeed(source.source));
1977
+ }
1967
1978
  if (input.cellType === 'array') {
1968
1979
  if (!WRUN_LANE_CELL_CLASSES.has(source.source)) {
1969
1980
  throw new Error(`WRUN ${metadata.id}: celled source class '${source.source}' is not served by the ` +
@@ -20,6 +20,23 @@ export type WrunTierChoice = 'finest' | 'coarsest';
20
20
  /** Whether a tier fits a host bar: its width divides the bar's span (a day for a calendar bar) and the bar's
21
21
  * open sits on the tier's UTC grid, so the bar is a whole number of the tier's buckets. */
22
22
  export declare function wrunTierFitsBar(tier: Pick<WrunBackendTier, 'ms'>, barOpenMs: number, barMs: number): boolean;
23
+ /** The instants a host bar's rows cover, `[fromMs, toMs)`. */
24
+ export interface WrunHostBarSpan {
25
+ fromMs: number;
26
+ toMs: number;
27
+ }
28
+ /**
29
+ * The session a host bar covers when it is not its stamp to its end, under a session grid (a flow's plan, see the
30
+ * module header): a bar the CME session lattice stamps at a day or longer (cme-session-bucket.util: the trade date's
31
+ * 00:00Z label at 1d, its group's first trade date at 3d, its week's Monday at 1w, its month's 1st at a calendar
32
+ * length) runs from the 17:00 Chicago open before it (`cmeSessionBarOpenMs`, read inside the bar) to the open that
33
+ * starts the next bar (`cmeSessionBarEndMs`). Undefined for any other bar: no grid, a grid off the lattice (a UTC or
34
+ * a stock chart's), an intraday lattice width (its stamp is its open), a stamp the lattice books no row to.
35
+ */
36
+ export declare function wrunCmeSessionBarSpan(barOpenMs: number, intervalMs: number, sessionGrid: LiveBucketVenue | null | undefined): WrunHostBarSpan | undefined;
37
+ /** A host bar's span: its session under a session grid (`wrunCmeSessionBarSpan`), else its stamp to its end
38
+ * (`wrunHostGridFetchTo`: its calendar close on a calendar chart). */
39
+ export declare function wrunHostBarSpanOf(barOpenMs: number, intervalMs: number, sessionGrid?: LiveBucketVenue | null): WrunHostBarSpan;
23
40
  /** The finest tier that fits a host bar (the one its live bar is built from), or undefined when none fits
24
41
  * (a bar finer than every tier, or one whose open sits on no tier's grid). */
25
42
  export declare function wrunFinestTier(tiers: readonly WrunBackendTier[], barOpenMs: number, barMs: number): WrunBackendTier | undefined;
@@ -30,15 +47,20 @@ export interface WrunBarTier {
30
47
  barOpenMs: number;
31
48
  tier?: WrunBackendTier;
32
49
  partial: boolean;
50
+ /** The session the bar is fit, retained, served and asked over when it is not its stamp to its end (a CME session
51
+ * bar of a day or longer under a session grid: `wrunCmeSessionBarSpan`). */
52
+ span?: WrunHostBarSpan;
33
53
  }
34
54
  /** The tier rule over a host grid's bar opens (ascending): each bar's fitting tier that still retains it (the
35
- * finest, or with `choice: 'coarsest'` the coarsest that already serves the bar), else partial. */
55
+ * finest, or with `choice: 'coarsest'` the coarsest that already serves the bar), else partial. Under a session grid
56
+ * (a flow's plan) a CME session bar of a day or longer is judged over its session (`wrunCmeSessionBarSpan`). */
36
57
  export declare function wrunBarTiers(args: {
37
58
  tiers: readonly WrunBackendTier[];
38
59
  barOpens: readonly number[];
39
60
  barMs: number;
40
61
  nowMs: number;
41
62
  choice?: WrunTierChoice;
63
+ sessionGrid?: LiveBucketVenue | null;
42
64
  }): WrunBarTier[];
43
65
  /** One ask of a tier-planned fetch: a tier and the span of host bars it builds, `[fromMs, toMs)` (the last
44
66
  * bar's end, its calendar close on a calendar chart, so every bucket inside it is asked). */
@@ -48,7 +70,8 @@ export interface WrunTierSegment {
48
70
  toMs: number;
49
71
  }
50
72
  /** The asks a tier plan needs: each run of consecutive bars that read the same tier, as one segment (a
51
- * partial bar asks nothing, it is marked instead). */
73
+ * partial bar asks nothing, it is marked instead), from its first bar's open (its session's, when it has one) to its
74
+ * last bar's end. */
52
75
  export declare function wrunTierSegments(barTiers: readonly WrunBarTier[], barMs: number): WrunTierSegment[];
53
76
  /** Where a host-grid lane asks its tier rows through, for a chart window whose last bar opens at
54
77
  * `lastBarOpenMs`: that bar's END (`barEndMs`: its calendar close on a calendar chart, whose length is an
@@ -66,7 +89,8 @@ export interface WrunHostGridAsk {
66
89
  * The asks a host-grid lane makes over a chart window: with no tiers, ONE ask from the first bar's open to the
67
90
  * last bar's end; with tiers, one ask per run of bars on one tier (`wrunBarTiers` under the lane's `choice`, then
68
91
  * `wrunTierSegments`), and the bars no fitting tier retains, which ask nothing and are partial. `barOpens` are the
69
- * host bars of the window, ascending (`liveBucketStartsInRange` over the chart's bar grid).
92
+ * host bars of the window, ascending (`liveBucketStartsInRange` over the chart's bar grid). `sessionGrid` (a flow's
93
+ * plan: the chart's bar grid) asks a CME session bar of a day or longer over its session (`wrunHostBarSpanOf`).
70
94
  */
71
95
  export declare function wrunHostGridAsks(args: {
72
96
  tiers?: readonly WrunBackendTier[];
@@ -74,6 +98,7 @@ export declare function wrunHostGridAsks(args: {
74
98
  intervalMs: number;
75
99
  nowMs: number;
76
100
  choice?: WrunTierChoice;
101
+ sessionGrid?: LiveBucketVenue | null;
77
102
  }): {
78
103
  asks: WrunHostGridAsk[];
79
104
  partialBars: number[];
@@ -20,15 +20,24 @@
20
20
  * closed inside the lag, read the next finer tier that serves them (the finest when none does). Which bars are
21
21
  * partial does not change.
22
22
  *
23
+ * The session grid (`sessionGrid`, a FLOW's plan: every bucket inside a bar sums into it). A bar the CME session
24
+ * lattice stamps at a day or longer (1d, 3d, 1w, a calendar length on a CME Group chart) carries its trade date's
25
+ * label, 00:00Z, while its session opens at the 17:00 Chicago open before it (22:00Z or 23:00Z the evening before):
26
+ * an evening print belongs to the next trade date's bar. Under the session grid such a bar is fit, retained, served
27
+ * and asked over its session (`wrunCmeSessionBarSpan`), so no ask reads a UTC day bucket that straddles the 17:00
28
+ * flip (an hour bucket never does: the flip falls on the hour) and every ask starts at the session's open. Every other
29
+ * bar (an intraday lattice bar, a UTC or an anchored grid's) keeps its stamp to its end, and so does a snapshot's plan.
30
+ *
23
31
  * The landing. A tier's rows are stamped at their bucket opens; each lands on the host bar holding it
24
32
  * (`liveBucketStartMs` over the chart's bar-grid venue, `liveBucketVenueOf(metadata)`: the 09:30-anchored
25
- * bucket of a regular-session stock chart, the UTC floor elsewhere; an off-session row lands nowhere), and the
26
- * bar's rows fold by the class's landing: a FLOW sums (every tuple of a celled flow is kept, in time order; a
27
- * scalar column sums its finite values), a SNAPSHOT takes the newest SEALED row of the bar (a row whose tier
28
- * bucket has closed by the clock: a forming bucket is never read as the bar's state).
33
+ * bucket of a regular-session stock chart, a CME chart's session lattice, the UTC floor elsewhere; an off-session row
34
+ * lands nowhere), and the bar's rows fold by the class's landing: a FLOW sums (every tuple of a celled flow is kept,
35
+ * in time order; a scalar column sums its finite values), a SNAPSHOT takes the newest SEALED row of the bar (a row
36
+ * whose tier bucket has closed by the clock: a forming bucket is never read as the bar's state).
29
37
  */
30
38
  import { barEndMs, calendarMonthsOfMs } from '../chart/calendar-interval.util.js';
31
- import { liveBucketStartMs } from '../chart/live-bucket.util.js';
39
+ import { cmeSessionBarEndMs, cmeSessionBarOpenMs, isCmeSessionLatticeIntervalMs, } from '../chart/cme-session-bucket.util.js';
40
+ import { isCmeSessionLatticeVenue, liveBucketStartMs } from '../chart/live-bucket.util.js';
32
41
  import { wrunPartialMarkerTuple, wrunTuplesMarkedPartial } from './wrun-present-bits.util.js';
33
42
  const DAY_MS = 86_400_000;
34
43
  /** The span a tier must divide: the bar's own, or a day for a calendar bar (its span is no fixed number). */
@@ -52,15 +61,51 @@ function tierRetainsBar(tier, barOpenMs, nowMs) {
52
61
  function fittingTiers(tiers, barOpenMs, barMs) {
53
62
  return tiers.filter((tier) => wrunTierFitsBar(tier, barOpenMs, barMs)).sort((a, b) => a.ms - b.ms);
54
63
  }
64
+ /**
65
+ * The session a host bar covers when it is not its stamp to its end, under a session grid (a flow's plan, see the
66
+ * module header): a bar the CME session lattice stamps at a day or longer (cme-session-bucket.util: the trade date's
67
+ * 00:00Z label at 1d, its group's first trade date at 3d, its week's Monday at 1w, its month's 1st at a calendar
68
+ * length) runs from the 17:00 Chicago open before it (`cmeSessionBarOpenMs`, read inside the bar) to the open that
69
+ * starts the next bar (`cmeSessionBarEndMs`). Undefined for any other bar: no grid, a grid off the lattice (a UTC or
70
+ * a stock chart's), an intraday lattice width (its stamp is its open), a stamp the lattice books no row to.
71
+ */
72
+ export function wrunCmeSessionBarSpan(barOpenMs, intervalMs, sessionGrid) {
73
+ if (!Number.isFinite(barOpenMs) || !(intervalMs >= DAY_MS) || !isCmeSessionLatticeIntervalMs(intervalMs)) {
74
+ return undefined;
75
+ }
76
+ if (!isCmeSessionLatticeVenue(sessionGrid))
77
+ return undefined;
78
+ const toMs = cmeSessionBarEndMs(barOpenMs, intervalMs);
79
+ if (toMs === null)
80
+ return undefined;
81
+ const fromMs = cmeSessionBarOpenMs(toMs - 1, intervalMs);
82
+ return fromMs !== null && fromMs < toMs ? { fromMs, toMs } : undefined;
83
+ }
84
+ /** A host bar's span: its session under a session grid (`wrunCmeSessionBarSpan`), else its stamp to its end
85
+ * (`wrunHostGridFetchTo`: its calendar close on a calendar chart). */
86
+ export function wrunHostBarSpanOf(barOpenMs, intervalMs, sessionGrid) {
87
+ return (wrunCmeSessionBarSpan(barOpenMs, intervalMs, sessionGrid) ?? {
88
+ fromMs: barOpenMs,
89
+ toMs: wrunHostGridFetchTo(barOpenMs, intervalMs),
90
+ });
91
+ }
92
+ /** The tiers that fit a session (its length a whole number of the tier's buckets, its open on the tier's UTC grid),
93
+ * finest first: on a CME session the hour and finer, never the UTC day. */
94
+ function sessionTiers(tiers, span) {
95
+ const length = span.toMs - span.fromMs;
96
+ return tiers
97
+ .filter((tier) => tier.ms > 0 && length % tier.ms === 0 && span.fromMs % tier.ms === 0)
98
+ .sort((a, b) => a.ms - b.ms);
99
+ }
55
100
  /** The finest tier that fits a host bar (the one its live bar is built from), or undefined when none fits
56
101
  * (a bar finer than every tier, or one whose open sits on no tier's grid). */
57
102
  export function wrunFinestTier(tiers, barOpenMs, barMs) {
58
103
  return fittingTiers(tiers, barOpenMs, barMs)[0];
59
104
  }
60
105
  /** The coarsest of a bar's retaining tiers (finest first) that already serves the whole bar: a tier with a
61
- * `servedLagMs` serves it once the bar ended that long ago. None serving: the finest (the finest choice's tier). */
62
- function coarsestServingTier(retaining, barOpenMs, barMs, nowMs) {
63
- const barEnd = barEndMs(barOpenMs, barMs);
106
+ * `servedLagMs` serves it once the bar ended (`barEnd`) that long ago. None serving: the finest (the finest choice's
107
+ * tier). */
108
+ function coarsestServingTier(retaining, barEnd, nowMs) {
64
109
  for (let at = retaining.length - 1; at > 0; at -= 1) {
65
110
  const lag = retaining[at].servedLagMs;
66
111
  if (lag === undefined || barEnd + lag <= nowMs)
@@ -69,20 +114,28 @@ function coarsestServingTier(retaining, barOpenMs, barMs, nowMs) {
69
114
  return retaining[0];
70
115
  }
71
116
  /** The tier rule over a host grid's bar opens (ascending): each bar's fitting tier that still retains it (the
72
- * finest, or with `choice: 'coarsest'` the coarsest that already serves the bar), else partial. */
117
+ * finest, or with `choice: 'coarsest'` the coarsest that already serves the bar), else partial. Under a session grid
118
+ * (a flow's plan) a CME session bar of a day or longer is judged over its session (`wrunCmeSessionBarSpan`). */
73
119
  export function wrunBarTiers(args) {
74
120
  return args.barOpens.map((barOpenMs) => {
75
- const fitting = fittingTiers(args.tiers, barOpenMs, args.barMs);
76
- const retaining = fitting.filter((tier) => tierRetainsBar(tier, barOpenMs, args.nowMs));
121
+ const span = wrunCmeSessionBarSpan(barOpenMs, args.barMs, args.sessionGrid);
122
+ const fitting = span === undefined ? fittingTiers(args.tiers, barOpenMs, args.barMs) : sessionTiers(args.tiers, span);
123
+ const fromMs = span?.fromMs ?? barOpenMs;
124
+ const retaining = fitting.filter((tier) => tierRetainsBar(tier, fromMs, args.nowMs));
125
+ const spanned = span === undefined ? {} : { span };
77
126
  if (retaining.length > 0) {
78
- const tier = args.choice === 'coarsest' ? coarsestServingTier(retaining, barOpenMs, args.barMs, args.nowMs) : retaining[0];
79
- return { barOpenMs, tier, partial: false };
127
+ const barEnd = span?.toMs ?? barEndMs(barOpenMs, args.barMs);
128
+ const tier = args.choice === 'coarsest' ? coarsestServingTier(retaining, barEnd, args.nowMs) : retaining[0];
129
+ return { barOpenMs, tier, partial: false, ...spanned };
80
130
  }
81
- return fitting.length > 0 ? { barOpenMs, tier: fitting[0], partial: true } : { barOpenMs, partial: true };
131
+ return fitting.length > 0
132
+ ? { barOpenMs, tier: fitting[0], partial: true, ...spanned }
133
+ : { barOpenMs, partial: true, ...spanned };
82
134
  });
83
135
  }
84
136
  /** The asks a tier plan needs: each run of consecutive bars that read the same tier, as one segment (a
85
- * partial bar asks nothing, it is marked instead). */
137
+ * partial bar asks nothing, it is marked instead), from its first bar's open (its session's, when it has one) to its
138
+ * last bar's end. */
86
139
  export function wrunTierSegments(barTiers, barMs) {
87
140
  const segments = [];
88
141
  let open;
@@ -91,12 +144,12 @@ export function wrunTierSegments(barTiers, barMs) {
91
144
  open = undefined;
92
145
  continue;
93
146
  }
94
- const endMs = barEndMs(bar.barOpenMs, barMs);
147
+ const endMs = bar.span?.toMs ?? barEndMs(bar.barOpenMs, barMs);
95
148
  if (open !== undefined && open.tier.key === bar.tier.key) {
96
149
  open.toMs = endMs;
97
150
  continue;
98
151
  }
99
- open = { tier: bar.tier, fromMs: bar.barOpenMs, toMs: endMs };
152
+ open = { tier: bar.tier, fromMs: bar.span?.fromMs ?? bar.barOpenMs, toMs: endMs };
100
153
  segments.push(open);
101
154
  }
102
155
  return segments;
@@ -112,7 +165,8 @@ export function wrunHostGridFetchTo(lastBarOpenMs, intervalMs) {
112
165
  * The asks a host-grid lane makes over a chart window: with no tiers, ONE ask from the first bar's open to the
113
166
  * last bar's end; with tiers, one ask per run of bars on one tier (`wrunBarTiers` under the lane's `choice`, then
114
167
  * `wrunTierSegments`), and the bars no fitting tier retains, which ask nothing and are partial. `barOpens` are the
115
- * host bars of the window, ascending (`liveBucketStartsInRange` over the chart's bar grid).
168
+ * host bars of the window, ascending (`liveBucketStartsInRange` over the chart's bar grid). `sessionGrid` (a flow's
169
+ * plan: the chart's bar grid) asks a CME session bar of a day or longer over its session (`wrunHostBarSpanOf`).
116
170
  */
117
171
  export function wrunHostGridAsks(args) {
118
172
  const { barOpens, intervalMs } = args;
@@ -120,7 +174,12 @@ export function wrunHostGridAsks(args) {
120
174
  return { asks: [], partialBars: [] };
121
175
  if (args.tiers === undefined || args.tiers.length === 0) {
122
176
  return {
123
- asks: [{ fromMs: barOpens[0], toMs: wrunHostGridFetchTo(barOpens[barOpens.length - 1], intervalMs) }],
177
+ asks: [
178
+ {
179
+ fromMs: wrunHostBarSpanOf(barOpens[0], intervalMs, args.sessionGrid).fromMs,
180
+ toMs: wrunHostBarSpanOf(barOpens[barOpens.length - 1], intervalMs, args.sessionGrid).toMs,
181
+ },
182
+ ],
124
183
  partialBars: [],
125
184
  };
126
185
  }
@@ -130,6 +189,7 @@ export function wrunHostGridAsks(args) {
130
189
  barMs: intervalMs,
131
190
  nowMs: args.nowMs,
132
191
  choice: args.choice,
192
+ sessionGrid: args.sessionGrid,
133
193
  });
134
194
  return {
135
195
  asks: wrunTierSegments(bars, intervalMs),
@@ -17,12 +17,23 @@ export type WrunTransientRerunAdmission = 'no-driver' | 'in-flight' | 'queued' |
17
17
  * took the place of the last one waiting. */
18
18
  export type WrunTransientGraceEnd = 'painted' | 'teardown' | 'superseded';
19
19
  type WrunTransientRerunAdmit = (target: WrunTransientRerunTarget, trigger: WrunTransientRerunTrigger) => WrunTransientRerunAdmission;
20
+ /** How a caller holds a transient refusal (`holdWrunTransientRefusal`). */
21
+ export interface WrunTransientHoldOptions {
22
+ /**
23
+ * The host reruns this overlay itself, outside the executor (the mobile app's hosted lane: its protected run heal
24
+ * re-asks the overlay on its own ladder), so the grace holds it without a registered rerun driver. The admission
25
+ * still answers `no-driver` to the package's own triggers, so nothing here reruns it twice. Off by default: an
26
+ * overlay no driver runs shows its record at once.
27
+ */
28
+ hostReruns?: boolean;
29
+ }
20
30
  /**
21
31
  * Hold a transient refusal of this overlay inside its grace: true when it waits (a grace started, or the one running
22
- * took it in without restarting), false when it must show now (the overlay's grace ran out and it has not painted
23
- * since). `onExpire` shows the records still waiting once the deadline ends the grace; the grace keeps the first one.
32
+ * took it in without restarting), false when it must show now (no rerun driver runs the overlay and its host does not
33
+ * rerun it itself, or its grace ran out and it has not painted since). `onExpire` shows the records still waiting once
34
+ * the deadline ends the grace; the grace keeps the first one.
24
35
  */
25
- export declare function holdWrunTransientRefusal(target: WrunTransientRerunTarget, onExpire: () => void): boolean;
36
+ export declare function holdWrunTransientRefusal(target: WrunTransientRerunTarget, onExpire: () => void, options?: WrunTransientHoldOptions): boolean;
26
37
  /**
27
38
  * End the overlay's grace before its deadline: nothing waiting shows, and its load signal comes down. A paint or a
28
39
  * teardown also ends the overlay's failure streak (its next transient refusal gets a grace of its own); a record that
@@ -7,9 +7,13 @@
7
7
  * one shows it as before.
8
8
  *
9
9
  * - The grace (`holdWrunTransientRefusal`), asked by the refusal surface for a record whose cause is transient: one
10
- * per overlay (`chartIndex:indicatorId`). The first such record starts it and a later one never restarts it. While
11
- * it runs, its load signal shows the overlay loading (`raiseWrunGraceLoad`) and its deadline counts visible time
12
- * only (startVisibleTimeout), so a hidden tab never runs it out.
10
+ * per overlay (`chartIndex:indicatorId`), and only for an overlay a rerun driver runs (the drivers registry,
11
+ * `hasWrunOverlayDriver`, the one the rerun's admission asks): a revive or an add whose load failed registered none,
12
+ * so no event could rerun it, and its record shows at once with its Retry. A host that reruns an overlay itself,
13
+ * outside the executor (the mobile app's hosted lane, whose protected run heal re-asks it), says so on the hold
14
+ * (`hostReruns`), and the grace holds it without a driver. The first such record starts it and a
15
+ * later one never restarts it. While it runs, its load signal shows the overlay loading (`raiseWrunGraceLoad`) and
16
+ * its deadline counts visible time only (startVisibleTimeout), so a hidden tab never runs it out.
13
17
  * - Its end, one way each (data-loading rule 3): a paint (the refusal surface's retraction), the overlay's teardown,
14
18
  * a record that shows at once in place of the last one waiting (`endWrunTransientGrace`), or the deadline, which
15
19
  * hands the waiting records back to the refusal surface to show as they would have shown at once. Every end lowers
@@ -20,13 +24,15 @@
20
24
  * against the overlay's own work, and each trigger admits at most once per grace (`claimWrunTransientRerun`). An
21
25
  * event the dedupe met is owed one coalesced rerun once that work settles without a paint (`oweWrunTransientRerun`).
22
26
  *
23
- * Import graph: a leaf on the boot path (the refusal surface rides the drivers registry there). The chart instances
27
+ * Import graph: on the boot path beside the drivers registry it reads (the refusal surface rides the registry there,
28
+ * and the registry imports the surface: a cycle no module crosses at load, only at call time). The chart instances
24
29
  * and the chart store load with the first grace through the host's loaders, the recovery ladders bind themselves (they
25
30
  * load beside their ports, `chart.loadRunPorts`, when a grace asks before they evaluated): nothing heavy at import.
26
31
  */
27
32
  import { startVisibleTimeout } from '../common/visible-timeout.util.js';
28
33
  import { wrunHostVisibleClock } from './wrun-host-visible-clock.util.js';
29
34
  import { claimWrunGraceLoading, isWrunLoadingOwned, releaseWrunLoading } from './wrun-loading-owner.util.js';
35
+ import { hasWrunOverlayDriver } from './wrun-overlay-drivers.util.js';
30
36
  import { wrunChartHostEnv } from '../../host-env.js';
31
37
  /** How long a transient refusal waits, in visible time, before it shows. */
32
38
  export const WRUN_TRANSIENT_GRACE_MS = 20_000;
@@ -141,12 +147,25 @@ function raiseGraceSignal(key, grace) {
141
147
  }
142
148
  /**
143
149
  * Hold a transient refusal of this overlay inside its grace: true when it waits (a grace started, or the one running
144
- * took it in without restarting), false when it must show now (the overlay's grace ran out and it has not painted
145
- * since). `onExpire` shows the records still waiting once the deadline ends the grace; the grace keeps the first one.
150
+ * took it in without restarting), false when it must show now (no rerun driver runs the overlay and its host does not
151
+ * rerun it itself, or its grace ran out and it has not painted since). `onExpire` shows the records still waiting once
152
+ * the deadline ends the grace; the grace keeps the first one.
146
153
  */
147
- export function holdWrunTransientRefusal(target, onExpire) {
154
+ export function holdWrunTransientRefusal(target, onExpire, options = {}) {
148
155
  const key = keyOf(target);
149
156
  const running = graces.get(key);
157
+ const hostReruns = options.hostReruns === true || running?.hostReruns === true;
158
+ // No driver, no rerun: the admission answers `no-driver` to every trigger (a revive or an add whose load failed
159
+ // registered none), so a grace would only show loading over nothing and the same record 20 s late. A host that
160
+ // reruns the overlay itself (on this hold, or the one that started the running grace) is the rerun.
161
+ if (!hostReruns && !hasWrunOverlayDriver(target.indicatorId)) {
162
+ ring('wrun-transient-grace', {
163
+ chartIndex: target.chartIndex,
164
+ indicatorId: target.indicatorId,
165
+ verdict: 'no-driver',
166
+ });
167
+ return false;
168
+ }
150
169
  if (running) {
151
170
  raiseGraceSignal(key, running);
152
171
  ring('wrun-transient-grace', { ...running.target, verdict: 'again' });
@@ -163,6 +182,7 @@ export function holdWrunTransientRefusal(target, onExpire) {
163
182
  admitted: new Set(),
164
183
  owed: undefined,
165
184
  expire: onExpire,
185
+ hostReruns,
166
186
  };
167
187
  graces.set(key, grace);
168
188
  // The deadline is armed before the load signal: the store's loading watchdog arms its 20 s "Still loading" chip on
@@ -171,7 +191,12 @@ export function holdWrunTransientRefusal(target, onExpire) {
171
191
  // The host's suspension pauses the grace too (a suspended app never runs it out).
172
192
  wrunHostVisibleClock());
173
193
  raiseGraceSignal(key, grace);
174
- ring('wrun-transient-grace', { ...grace.target, verdict: 'held', graceMs: WRUN_TRANSIENT_GRACE_MS });
194
+ ring('wrun-transient-grace', {
195
+ ...grace.target,
196
+ verdict: 'held',
197
+ graceMs: WRUN_TRANSIENT_GRACE_MS,
198
+ ...(hostReruns ? { rerunner: 'host' } : {}),
199
+ });
175
200
  return true;
176
201
  }
177
202
  function expireWrunTransientGrace(key, grace) {
@@ -84,7 +84,7 @@
84
84
  * the string accounting and frame slots across calls, and history is
85
85
  * never re-executed per tick.
86
86
  */
87
- import { WrunLiveOrderError, type WrunAbiVersion, type WrunDrawSkips, type WrunLiveBlockStats, type WrunPackedRowsBlock, type WrunPackedRunOutput, type WrunPackedRunRequest } from '../../interfaces/wrun-runtime.interface.js';
87
+ import { WrunLiveOrderError, type WrunAbiVersion, type WrunDrawSkips, type WrunLiveBlockStats, type WrunModuleImport, type WrunPackedRowsBlock, type WrunPackedRunOutput, type WrunResolvedRunRequest } from '../../interfaces/wrun-runtime.interface.js';
88
88
  import { type WrunHandleDefaultsByKind, type WrunHandleRecord } from '../../utility/wrun/wrun-handles.util.js';
89
89
  import type { StrategyDeclaredConfig, StrategyOutput, WrunStrategyEvents, WrunStrategyReservedOutputs } from '@orangecharts/indicator-kit/host';
90
90
  /** The strategy half of a run (contract sections 2 and 5): the engine's
@@ -146,6 +146,11 @@ export interface WrunAbiSessionConfig {
146
146
  /** Test hook: observes every forming-bar restore (a same-bar replay and
147
147
  * the close-confirm re-evaluation alike). */
148
148
  onRestore?: () => void;
149
+ /** Called once the module is instantiated, right before the guest's first
150
+ * call (init()): from here the request executes. The engine worker posts
151
+ * its `running` here, so the client's run deadline never counts an
152
+ * instantiation still pending behind another request's turn. */
153
+ onInstantiated?: () => void;
149
154
  }
150
155
  /** A wrun-3 session answers the ledger's FULL live set beside every block's
151
156
  * rows (wire records in creation order), and the run's skipped draw calls
@@ -176,9 +181,17 @@ export { WrunLiveOrderError };
176
181
  export interface WrunAbiSession {
177
182
  runRows(block: WrunStrategyRowsBlock, mode: 'historical' | 'live'): WrunAbiSessionOutput;
178
183
  }
184
+ /** A compiled module's imports as the shared readers take them (`WrunModuleImport`, in
185
+ * WebAssembly.Module.imports() order), listed once per module and frozen: the engine worker's load answers this list
186
+ * on the module's handle, and every session of the module reads its import checks off the same list (the shared
187
+ * predicates of wrun-bar-count.util among them), so the main thread's handle and the worker's module answer alike. */
188
+ export declare function wrunModuleImportList(module: WebAssembly.Module): readonly WrunModuleImport[];
179
189
  export declare function createWrunAbiSession(config: WrunAbiSessionConfig): Promise<WrunAbiSession>;
180
- export declare function runWrunPackedRequest(request: WrunPackedRunRequest & WrunStrategyRunRequestFields, options?: {
190
+ /** One whole request against a fresh instance of the module the engine worker resolved for it (a resolved request:
191
+ * the wire request's module key and bytes already turned into the compiled module, never a wire request). */
192
+ export declare function runWrunPackedRequest(request: WrunResolvedRunRequest & WrunStrategyRunRequestFields, options?: {
181
193
  memoryLimitBytes?: number;
194
+ onInstantiated?: () => void;
182
195
  }): Promise<WrunAbiSessionOutput>;
183
196
  /** An AssemblyScript `string` in the guest's memory: UTF-16LE code units at `ptr`, the byte
184
197
  * length as the u32 at `ptr - 4` (the managed object header's rtSize). Null for a null
@@ -89,15 +89,16 @@ import { abiAtLeast, WrunLiveOrderError, } from '../../interfaces/wrun-runtime.i
89
89
  import { WRUN3_DRAW_REFUSALS, WrunDrawRefusalError, WrunHandleLedger, } from '../../utility/wrun/wrun-handles.util.js';
90
90
  import { WRUN_RENDER_RESULT_LIMIT_BYTES } from '../../utility/wrun/wrun-render-select.util.js';
91
91
  import { WRUN5_TEXT_IMPORTS, WRUN5_TEXT_REFUSALS, wrunPlainText } from '../../utility/wrun/wrun-text-params.util.js';
92
- import { WRUN6_BAR_REFUSALS, wrunModuleImportsBarCount } from '../../utility/wrun/wrun-bar-count.util.js';
92
+ import { WRUN6_BAR_REFUSALS, wrunImportsBarCount } from '../../utility/wrun/wrun-bar-count.util.js';
93
93
  import { WRUN_MEMORY_LIMIT_BYTES } from '../../utility/wrun/wrun-memory-clamp.util.js';
94
94
  import { wrunRunCellsRefusal } from '../../utility/wrun/wrun-run-cells.util.js';
95
95
  const WRUN_GLOBAL_PREFIX = '__wrun_g';
96
96
  /** `strategyBars` stride: open, high, low, close per row. */
97
97
  const STRATEGY_BAR_STRIDE = 4;
98
98
  const STRATEGY_IMPORT_PREFIX = 'wrun_strategy_';
99
- /** The memory ceiling: the clamp's own limit, which compileModule also stamps on every module
100
- * as its memory maximum (wrun-memory-clamp.util), so the two can never drift. */
99
+ /** The memory ceiling: the clamp's own limit, which the engine worker's load (wrun-engine-handler.ts
100
+ * compileWrunModuleBytes) also stamps on every module as its memory maximum (wrun-memory-clamp.util), so the two can
101
+ * never drift. */
101
102
  const WRUN_DEFAULT_MEMORY_LIMIT_BYTES = WRUN_MEMORY_LIMIT_BYTES;
102
103
  const BYTES_PER_CELL = 8;
103
104
  const BYTES_PER_POINT = 16;
@@ -126,11 +127,24 @@ const MAX_ROW_STAMP = 0x3fff_ffff;
126
127
  * exported here for the worker and the ABI drive specs. */
127
128
  export { WrunLiveOrderError };
128
129
  const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
130
+ const importListByModule = new WeakMap();
131
+ /** A compiled module's imports as the shared readers take them (`WrunModuleImport`, in
132
+ * WebAssembly.Module.imports() order), listed once per module and frozen: the engine worker's load answers this list
133
+ * on the module's handle, and every session of the module reads its import checks off the same list (the shared
134
+ * predicates of wrun-bar-count.util among them), so the main thread's handle and the worker's module answer alike. */
135
+ export function wrunModuleImportList(module) {
136
+ let list = importListByModule.get(module);
137
+ if (list === undefined) {
138
+ list = Object.freeze(WebAssembly.Module.imports(module).map(({ module: from, name }) => Object.freeze({ module: from, name })));
139
+ importListByModule.set(module, list);
140
+ }
141
+ return list;
142
+ }
129
143
  /** A wrun-3 module whose sheet declares no `strategy` section must import
130
144
  * no strategy import: refused at instantiation by name, the same rule as a
131
145
  * draw call for a kind absent from `handles`, before anything links. */
132
146
  function refuseUndeclaredStrategyImports(module) {
133
- const names = WebAssembly.Module.imports(module)
147
+ const names = wrunModuleImportList(module)
134
148
  .filter((entry) => entry.module === 'wrun' && entry.name.startsWith(STRATEGY_IMPORT_PREFIX))
135
149
  .map((entry) => entry.name);
136
150
  if (names.length === 0)
@@ -187,7 +201,7 @@ export async function createWrunAbiSession(config) {
187
201
  throw new Error(`WRUN frames declares ${frameSlotCount} slots; the maximum is ${MAX_FRAME_SLOTS}`);
188
202
  }
189
203
  if (!abiAtLeast(config.abi, 'wrun-4')) {
190
- const importsFrame = WebAssembly.Module.imports(config.module).some((entry) => entry.module === 'wrun' && entry.name === 'wrun_output_frame');
204
+ const importsFrame = wrunModuleImportList(config.module).some((entry) => entry.module === 'wrun' && entry.name === 'wrun_output_frame');
191
205
  if (importsFrame) {
192
206
  throw new Error(`WRUN wrun_output_frame requires abi_version "wrun-4" or later (declared "${config.abi}")`);
193
207
  }
@@ -196,7 +210,7 @@ export async function createWrunAbiSession(config) {
196
210
  // module compiled from a param.text declaration never links under a host
197
211
  // or a sheet that has not reached wrun-5.
198
212
  if (!abiAtLeast(config.abi, 'wrun-5')) {
199
- const textImports = WebAssembly.Module.imports(config.module)
213
+ const textImports = wrunModuleImportList(config.module)
200
214
  .filter((entry) => entry.module === 'wrun' && TEXT_IMPORT_NAMES.has(entry.name))
201
215
  .map((entry) => entry.name);
202
216
  if (textImports.length > 0) {
@@ -206,7 +220,7 @@ export async function createWrunAbiSession(config) {
206
220
  }
207
221
  // The row count is wrun-6's (docs/WRUN6_ABI.md): an older ABI refuses the
208
222
  // import by name before anything links, the om hosts' way-in hint.
209
- const importsBarCount = wrunModuleImportsBarCount(config.module);
223
+ const importsBarCount = wrunImportsBarCount(wrunModuleImportList(config.module));
210
224
  if (importsBarCount && !abiAtLeast(config.abi, 'wrun-6')) {
211
225
  throw new Error(`WRUN wrun_bar_count: the row count requires abi_version "wrun-6" or later ` +
212
226
  `(declared "${config.abi}"); a bar.count() call derives it`);
@@ -663,6 +677,8 @@ export async function createWrunAbiSession(config) {
663
677
  else if (abiAtLeast(config.abi, 'wrun-3'))
664
678
  refuseUndeclaredStrategyImports(config.module);
665
679
  const instance = await WebAssembly.instantiate(config.module, importObject);
680
+ // Instantiated: the guest's first call (init) runs next, in this same turn.
681
+ config.onInstantiated?.();
666
682
  instanceRef.exports = instance.exports;
667
683
  const exports = instance.exports;
668
684
  const init = requireFunction(exports.init, 'init');
@@ -975,6 +991,8 @@ function strategyOutputOf(strategyHost, ledger, rowCount, events) {
975
991
  strategyReserved: strategyHost.reservedOutputs(rowCount),
976
992
  };
977
993
  }
994
+ /** One whole request against a fresh instance of the module the engine worker resolved for it (a resolved request:
995
+ * the wire request's module key and bytes already turned into the compiled module, never a wire request). */
978
996
  export async function runWrunPackedRequest(request, options = {}) {
979
997
  const session = await createWrunAbiSession({
980
998
  module: request.module,
@@ -987,6 +1005,7 @@ export async function runWrunPackedRequest(request, options = {}) {
987
1005
  handleDefaults: request.handleDefaults,
988
1006
  strategy: request.strategy,
989
1007
  memoryLimitBytes: options.memoryLimitBytes,
1008
+ onInstantiated: options.onInstantiated,
990
1009
  });
991
1010
  return session.runRows(request, request.mode);
992
1011
  }
@@ -1084,11 +1103,11 @@ function sliceRow(block, row) {
1084
1103
  };
1085
1104
  }
1086
1105
  /** Same-bar live restore semantics: copy linear memory plus the mutable
1087
- * globals exported under __wrun_g*. The host exports EVERY mutable global
1088
- * under that prefix when it compiles the module (WrunBrowserHost
1089
- * .compileModule), so a compiler's top-level scalars restore beside the
1090
- * heap they index; a module must still export its memory if it keeps state
1091
- * there (AssemblyScript does by default). */
1106
+ * globals exported under __wrun_g*. The engine worker exports EVERY mutable
1107
+ * global under that prefix when it compiles the module (wrun-engine-handler
1108
+ * compileWrunModuleBytes), so a compiler's top-level scalars restore beside
1109
+ * the heap they index; a module must still export its memory if it keeps
1110
+ * state there (AssemblyScript does by default). */
1092
1111
  function snapshot(exports, runStringBytes) {
1093
1112
  const memory = exportedMemory(exports);
1094
1113
  const view = memory ? new Uint8Array(memory.buffer) : null;