@gloom-sh/terminal 0.19.6 → 0.20.1

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 (209) hide show
  1. package/LICENSE +0 -4
  2. package/package.json +6 -5
  3. package/patches/electrobun-devkit@2.0.5.patch +408 -0
  4. package/src/api-client/bond-trades.ts +59 -0
  5. package/src/api-client/crypto-markets.ts +20 -2
  6. package/src/api-client/data.ts +21 -0
  7. package/src/api-client/fund-facts.ts +23 -1
  8. package/src/api-client/index.ts +2 -0
  9. package/src/api-client/types/account.ts +86 -0
  10. package/src/api-client/types/assist.ts +32 -0
  11. package/src/api-client/types/auth.ts +63 -0
  12. package/src/api-client/types/billing.ts +54 -0
  13. package/src/api-client/types/chat.ts +180 -0
  14. package/src/api-client/types/congress.ts +107 -0
  15. package/src/api-client/types/credit.ts +110 -0
  16. package/src/api-client/types/econ.ts +158 -0
  17. package/src/api-client/types/equity-diagnostic.ts +73 -0
  18. package/src/api-client/types/filings-and-calls.ts +356 -0
  19. package/src/api-client/types/index.ts +25 -0
  20. package/src/api-client/types/jobs.ts +147 -0
  21. package/src/api-client/types/market.ts +122 -0
  22. package/src/api-client/types/news.ts +91 -0
  23. package/src/api-client/types/notes-and-theses.ts +172 -0
  24. package/src/api-client/types/quotes.ts +28 -0
  25. package/src/api-client/types/scanners.ts +125 -0
  26. package/src/api-client/types/screener.ts +65 -0
  27. package/src/api-client/types/search.ts +107 -0
  28. package/src/api-client/types/sync.ts +14 -0
  29. package/src/api-client/types/team-collections.ts +43 -0
  30. package/src/api-client/types/team-views.ts +32 -0
  31. package/src/api-client/types/teams.ts +135 -0
  32. package/src/api-client/types/ticker-data.ts +57 -0
  33. package/src/api-client/types/tweets.ts +59 -0
  34. package/src/api-client/types/world-venues.ts +23 -0
  35. package/src/app/runtime/desktop-deeplink.ts +41 -6
  36. package/src/app/runtime/plugin-seed.ts +119 -0
  37. package/src/app/runtime/startup.ts +45 -9
  38. package/src/app/star-prompt/status-line.tsx +1 -1
  39. package/src/app.tsx +2 -7
  40. package/src/architecture/ui-tokens-allowlist.json +0 -8
  41. package/src/cli/board-coins.ts +38 -5
  42. package/src/cli/commands/crypto-hints.ts +8 -1
  43. package/src/cli/commands/market.ts +29 -26
  44. package/src/cli/commands/overview.ts +13 -6
  45. package/src/cli/commands/ticker.ts +78 -18
  46. package/src/cli/company-name-hint.ts +19 -0
  47. package/src/cli/desktop-pane-shot-browser.ts +69 -3
  48. package/src/cli/entry.ts +10 -4
  49. package/src/cli/glossary.ts +25 -0
  50. package/src/cli/helpers.ts +4 -2
  51. package/src/cli/not-a-ticker.ts +26 -1
  52. package/src/cli/pane-functions/catalog.ts +3 -1
  53. package/src/cli/pane-functions/freshness.ts +45 -29
  54. package/src/cli/pane-functions/market-session.ts +14 -5
  55. package/src/cli/restore-plugins.ts +164 -51
  56. package/src/components/chart/composite/use-composite-chart-keyboard.ts +11 -2
  57. package/src/components/chart-table/header.tsx +10 -1
  58. package/src/components/chart-table/layout.ts +14 -5
  59. package/src/components/command-bar/panel/index.tsx +13 -0
  60. package/src/components/command-bar/panel/layout.ts +7 -0
  61. package/src/components/command-bar/panel/runtime.ts +1 -0
  62. package/src/components/command-bar/panel/types.ts +2 -0
  63. package/src/components/data-table/export.ts +4 -1
  64. package/src/components/layout/detached-pane-shell.tsx +10 -37
  65. package/src/components/layout/double-escape-close.ts +90 -0
  66. package/src/components/layout/header.tsx +3 -2
  67. package/src/components/layout/market-summary.ts +6 -3
  68. package/src/components/layout/pane/footer/index.tsx +2 -6
  69. package/src/components/layout/pane/footer/model.ts +6 -12
  70. package/src/components/layout/shell/active-drag.ts +53 -11
  71. package/src/components/layout/shell/drag/magnets.ts +128 -19
  72. package/src/components/layout/shell/pane/actions.ts +6 -2
  73. package/src/components/layout/shell/pane/management-shortcuts.ts +13 -51
  74. package/src/components/layout/status-bar.tsx +4 -78
  75. package/src/components/layout/status-widget-space.ts +5 -5
  76. package/src/components/onboarding/portfolio-step/positions-panel.tsx +1 -1
  77. package/src/components/ui/data-table/index.tsx +5 -1
  78. package/src/components/ui/data-table/render-cell.ts +19 -0
  79. package/src/components/ui/delayed-mark.tsx +59 -7
  80. package/src/components/ui/icon.tsx +1 -8
  81. package/src/components/ui/menu.tsx +6 -1
  82. package/src/i18n/es.ts +6 -3
  83. package/src/i18n/ja.ts +6 -3
  84. package/src/i18n/ko.ts +6 -3
  85. package/src/i18n/zh-cn.ts +6 -3
  86. package/src/i18n/zh-tw.ts +6 -3
  87. package/src/market-data/fund-facts.ts +7 -1
  88. package/src/market-data/market/change-basis.ts +20 -0
  89. package/src/market-data/market/format.ts +62 -2
  90. package/src/market-data/market/futures-week.ts +3 -1
  91. package/src/plugins/builtin/chart-composer/headless.ts +57 -17
  92. package/src/plugins/builtin/chart-composer/session-range.ts +82 -3
  93. package/src/plugins/builtin/chat/content/composer.tsx +21 -27
  94. package/src/plugins/builtin/chat/content/index.tsx +31 -3
  95. package/src/plugins/builtin/chat/content/shortcuts.ts +4 -2
  96. package/src/plugins/builtin/chat/content/snapshot.ts +0 -3
  97. package/src/plugins/builtin/cloud/auth-actions.tsx +51 -23
  98. package/src/plugins/builtin/cloud/trial-offer-status-widget.tsx +3 -3
  99. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +32 -25
  100. package/src/plugins/builtin/congress-trades/model.ts +2 -1
  101. package/src/plugins/builtin/congress-trades/pane.tsx +3 -0
  102. package/src/plugins/builtin/correlation/compute.ts +8 -2
  103. package/src/plugins/builtin/correlation/headless.ts +10 -9
  104. package/src/plugins/builtin/correlation/history.ts +30 -0
  105. package/src/plugins/builtin/correlation/matrix/model.ts +10 -10
  106. package/src/plugins/builtin/correlation/relationship/model.ts +3 -6
  107. package/src/plugins/builtin/correlation/relationship/pane.tsx +1 -2
  108. package/src/plugins/builtin/crypto-board/client.ts +6 -1
  109. package/src/plugins/builtin/crypto-board/defi-view.tsx +12 -1
  110. package/src/plugins/builtin/crypto-board/defi.ts +44 -7
  111. package/src/plugins/builtin/crypto-board/headless.ts +83 -12
  112. package/src/plugins/builtin/crypto-board/model.ts +30 -6
  113. package/src/plugins/builtin/crypto-board/pane.tsx +13 -2
  114. package/src/plugins/builtin/custom-view/index.tsx +1 -1
  115. package/src/plugins/builtin/custom-view/loader.ts +85 -8
  116. package/src/plugins/builtin/custom-view/view-spec.ts +28 -0
  117. package/src/plugins/builtin/equity-screener/criterion-editor.tsx +13 -4
  118. package/src/plugins/builtin/equity-screener/headless.ts +33 -1
  119. package/src/plugins/builtin/equity-screener/model.ts +58 -15
  120. package/src/plugins/builtin/equity-screener/pane.tsx +36 -6
  121. package/src/plugins/builtin/executives/format.ts +5 -4
  122. package/src/plugins/builtin/executives/pane.tsx +1 -1
  123. package/src/plugins/builtin/help/index.tsx +55 -1
  124. package/src/plugins/builtin/insider/model.ts +30 -2
  125. package/src/plugins/builtin/jobs/model.ts +2 -2
  126. package/src/plugins/builtin/mna/model.ts +2 -2
  127. package/src/plugins/builtin/notes/files.ts +2 -0
  128. package/src/plugins/builtin/notes/owner.tsx +20 -1
  129. package/src/plugins/builtin/notes/quick-notes-pane.tsx +22 -4
  130. package/src/plugins/builtin/notes/store.ts +6 -1
  131. package/src/plugins/builtin/perps/headless.ts +8 -2
  132. package/src/plugins/builtin/portfolio-list/header.tsx +1 -1
  133. package/src/plugins/builtin/research/corporate-actions-pane.tsx +29 -25
  134. package/src/plugins/builtin/risk-factors/index.tsx +2 -28
  135. package/src/plugins/builtin/risk-factors/lock-note.ts +58 -0
  136. package/src/plugins/builtin/risk-factors/pane.tsx +10 -3
  137. package/src/plugins/builtin/scanner/hilo-model.ts +4 -3
  138. package/src/plugins/builtin/sec/fund-facts.ts +45 -11
  139. package/src/plugins/builtin/sec/headless.ts +30 -1
  140. package/src/plugins/builtin/sec/index.tsx +26 -5
  141. package/src/plugins/builtin/series-inventory.ts +1 -0
  142. package/src/plugins/builtin/shared/earnings-report.ts +7 -2
  143. package/src/plugins/builtin/shared/pro-lock-note.ts +5 -1
  144. package/src/plugins/builtin/shared/use-quote-board.ts +85 -46
  145. package/src/plugins/builtin/short-interest/headless.ts +1 -1
  146. package/src/plugins/builtin/short-interest/model.ts +15 -6
  147. package/src/plugins/builtin/short-interest/types.ts +2 -0
  148. package/src/plugins/builtin/thirteenf/overlap-pane.tsx +3 -0
  149. package/src/plugins/builtin/thirteenf/pane.tsx +3 -0
  150. package/src/plugins/builtin/ticker-detail/overview/model.ts +19 -9
  151. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +4 -4
  152. package/src/plugins/builtin/time-sales/headless.ts +23 -7
  153. package/src/plugins/builtin/time-sales/index.tsx +2 -2
  154. package/src/plugins/builtin/trace-bonds/detail.tsx +198 -0
  155. package/src/plugins/builtin/trace-bonds/headless.ts +62 -4
  156. package/src/plugins/builtin/trace-bonds/history.ts +155 -0
  157. package/src/plugins/builtin/trace-bonds/pane.tsx +64 -5
  158. package/src/plugins/extracted-plugins.ts +49 -24
  159. package/src/plugins/installer.ts +234 -32
  160. package/src/plugins/plugin-names.ts +11 -2
  161. package/src/plugins/running-installs.ts +34 -0
  162. package/src/plugins/seed-progress.ts +72 -0
  163. package/src/remote/controller.ts +9 -2
  164. package/src/remote/schema.ts +2 -1
  165. package/src/renderers/cloudflare/http-proxy.ts +67 -8
  166. package/src/renderers/cloudflare/proxy-session.ts +1 -1
  167. package/src/renderers/cloudflare/worker.ts +29 -2
  168. package/src/renderers/dom/desktop/icons.tsx +0 -2
  169. package/src/renderers/dom/styles.css +0 -3
  170. package/src/renderers/electrobun/bun/desktop/backend.ts +14 -0
  171. package/src/renderers/electrobun/bun/desktop/host-requests.ts +14 -7
  172. package/src/renderers/electrobun/bun/desktop/initialization.ts +24 -14
  173. package/src/renderers/electrobun/bun/desktop/install-records.ts +59 -0
  174. package/src/renderers/electrobun/bun/desktop/installer-folder.ts +208 -592
  175. package/src/renderers/electrobun/bun/desktop/macos-objc.ts +14 -0
  176. package/src/renderers/electrobun/bun/desktop/update.ts +1 -1
  177. package/src/renderers/electrobun/bun/index.ts +24 -13
  178. package/src/renderers/electrobun/bun/window/context-menu-thread.ts +84 -0
  179. package/src/renderers/electrobun/bun/window/create.ts +23 -3
  180. package/src/renderers/electrobun/bun/window/electrobun-window-host.ts +4 -4
  181. package/src/renderers/electrobun/bun/window/events.ts +4 -4
  182. package/src/renderers/electrobun/bun/window/frame.ts +2 -1
  183. package/src/renderers/electrobun/bun/window/native-call-thread.ts +224 -0
  184. package/src/renderers/electrobun/bun/window/native-min-size.ts +322 -0
  185. package/src/renderers/electrobun/bun/window/native-timing.ts +10 -0
  186. package/src/renderers/electrobun/bun/window/script-for-webview.ts +15 -0
  187. package/src/renderers/electrobun/bun/window/webview-script-thread.ts +82 -0
  188. package/src/renderers/electrobun/shared/protocol.ts +13 -2
  189. package/src/renderers/electrobun/view/backend-rpc.ts +8 -1
  190. package/src/renderers/electrobun/view/cli-pane-shot-frame.tsx +1 -1
  191. package/src/renderers/electrobun/view/main.tsx +4 -3
  192. package/src/renderers/opentui/start.tsx +3 -0
  193. package/src/sources/gloomberb-cloud/index.ts +5 -7
  194. package/src/sources/provider-router/batches.ts +18 -3
  195. package/src/sources/provider-router/financials.ts +18 -4
  196. package/src/telemetry/stall-reports.ts +21 -4
  197. package/src/types/data-provider.ts +14 -0
  198. package/src/types/financials.ts +15 -3
  199. package/src/types/headless.ts +2 -0
  200. package/src/utils/double-escape-close.ts +38 -16
  201. package/src/utils/format.ts +23 -3
  202. package/src/utils/main-thread-stall.ts +21 -5
  203. package/src/utils/perf-marks.ts +88 -9
  204. package/src/utils/price-earnings.ts +18 -0
  205. package/src/utils/reported-money.ts +9 -2
  206. package/src/utils/sec.ts +34 -3
  207. package/patches/electrobun@1.18.1.patch +0 -633
  208. package/src/api-client/types.ts +0 -2441
  209. package/src/plugins/seed-notice.ts +0 -20
@@ -443,7 +443,15 @@ function mergeDefinedObject<T extends object>(preferred: T | null | undefined, f
443
443
  return Object.fromEntries(mergedEntries) as T;
444
444
  }
445
445
 
446
- function setOrDelete<K extends "dividendRate" | "forwardEps">(target: Fundamentals, key: K, value: Fundamentals[K]): void {
446
+ /** Forward P/E, its consensus EPS and the year it is for: one observation, never pieced together from two. */
447
+ const FORWARD_FIELDS = ["forwardPE", "forwardEps", "forwardEpsCurrency", "forwardEpsPeriodEnd", "forwardEpsObservedAt"] as const;
448
+
449
+ /** A block that read next year's consensus says what it found, even none: its forward fields stand whole. */
450
+ function readsConsensus(fundamentals: Fundamentals | undefined): boolean {
451
+ return fundamentals?.forwardEpsPeriodEnd !== undefined;
452
+ }
453
+
454
+ function setOrDelete<K extends "dividendRate" | (typeof FORWARD_FIELDS)[number]>(target: Fundamentals, key: K, value: Fundamentals[K]): void {
447
455
  if (value === undefined) delete target[key];
448
456
  else target[key] = value;
449
457
  }
@@ -483,10 +491,14 @@ function mergeFundamentals(primary: Fundamentals | undefined, fallback: Fundamen
483
491
  merged.dividendYieldSource = dividend.dividendYieldSource;
484
492
  setOrDelete(merged, "dividendRate", dividend.dividendRate);
485
493
  }
486
- const forward = primary?.forwardPE != null ? primary : fallback;
494
+ const forward = primary?.forwardPE != null || readsConsensus(primary) ? primary : fallback;
487
495
  // Forward EPS reprices the forward multiple, so it pairs with that multiple's
488
- // observation; a withdrawn one never comes back from an older fallback.
489
- if (merged && forward) setOrDelete(merged, "forwardEps", forward.forwardEps);
496
+ // observation; a withdrawn one never comes back from an older fallback, and
497
+ // a consensus that is a loss or none never takes an older multiple.
498
+ if (merged && forward) {
499
+ if (readsConsensus(forward)) for (const key of FORWARD_FIELDS) setOrDelete(merged, key, forward[key]);
500
+ else setOrDelete(merged, "forwardEps", forward.forwardEps);
501
+ }
490
502
  if (merged && primary && !primary.financialCurrency && [
491
503
  primary.revenue, primary.netIncome, primary.operatingCashFlow, primary.freeCashFlow, primary.eps,
492
504
  ].some((value) => value != null)) {
@@ -576,6 +588,8 @@ export function mergeRefreshedFinancials(cached: TickerFinancials, fresh: Ticker
576
588
  if (!currencyConflict && typeof statistics[field] === "number" && Number.isFinite(statistics[field])) update[field] = statistics[field];
577
589
  }
578
590
  if (!currencyConflict && statistics.enterpriseValueCheck) update.enterpriseValueCheck = statistics.enterpriseValueCheck;
591
+ // Fresh statistics that read next year's consensus replace the forward figures whole, a loss or none included.
592
+ if (readsConsensus(statistics)) for (const key of FORWARD_FIELDS) if (statistics[key] !== undefined) update[key] = statistics[key] as never;
579
593
  let fundamentals = mergeFundamentals(update, merged.fundamentals);
580
594
  // The source serving a multiple or yield without its per-share base has
581
595
  // withdrawn that base, so an older one must not keep repricing the figure.
@@ -7,7 +7,8 @@ import { reportCrash } from "./crash-reports";
7
7
  * Freezes, made visible outside the app's own Debug Log.
8
8
  *
9
9
  * The stall monitor (utils/main-thread-stall.ts) notices when a process could
10
- * not answer the user for a while and names the last measured section, and
10
+ * not answer the user for a while and names the measured section that held
11
+ * it (or the last one before it), and
11
12
  * hands the stall to its sink. The terminal app and the desktop app's Bun
12
13
  * process record their own stalls here; the desktop window sends the stalls
13
14
  * it had in front of the user (stall-reports-dom.ts) to the Bun process,
@@ -24,7 +25,9 @@ import { reportCrash } from "./crash-reports";
24
25
  *
25
26
  * A report also says when in the process's life the stall came (still
26
27
  * starting or up, and an uptime bucket), how long before it the named section
27
- * ended (or that it ended inside it, which makes it the likely cause), and,
28
+ * ended (or that it ended inside it), what share of the stall that section
29
+ * itself ran (all of it: it froze the thread; little: it ran after a wait
30
+ * nothing measured), and,
28
31
  * for the desktop app's own process, whether the app was in front and had a
29
32
  * window on screen: a hidden app's slowed timers read like a freeze. A stall
30
33
  * after a SQLite statement names the statement (a fixed name), its tries and
@@ -62,6 +65,11 @@ export interface StallReport {
62
65
  uptime: UptimeBucket | "unknown";
63
66
  /** How long before the stall began the section ended; "in" when it ended inside it. */
64
67
  gap: GapBucket;
68
+ /**
69
+ * The share of the stall the section itself ran, in percent, by tens: 100
70
+ * when it froze the thread, near 0 when it only ran after an unmeasured wait.
71
+ */
72
+ heldPercent?: number;
65
73
  /** The desktop app's own process: whether the app was in front (null: not known yet). */
66
74
  active?: boolean | null;
67
75
  /** The desktop app's own process: whether a window was open and not minimized. */
@@ -184,13 +192,14 @@ function gapBucket(event: StallEvent): GapBucket {
184
192
  /** A stall another process sent over, kept only when it has the right shape. */
185
193
  export function parseStallEvent(value: unknown): StallEvent | null {
186
194
  if (!value || typeof value !== "object") return null;
187
- const { blockedMs, lastMeasured, lastMeasuredEndedMsAgo, sqlite, uptimeMs, phase } = value as Record<string, unknown>;
195
+ const { blockedMs, lastMeasured, lastMeasuredEndedMsAgo, lastMeasuredMs, sqlite, uptimeMs, phase } = value as Record<string, unknown>;
188
196
  if (typeof blockedMs !== "number" || !Number.isFinite(blockedMs) || blockedMs <= 0) return null;
189
197
  const detail = sqlite && typeof sqlite === "object" ? sqlite as Record<string, unknown> : null;
190
198
  return {
191
199
  blockedMs,
192
200
  ...(typeof lastMeasured === "string" && lastMeasured.length <= 200 ? { lastMeasured } : {}),
193
201
  ...(typeof lastMeasuredEndedMsAgo === "number" && Number.isFinite(lastMeasuredEndedMsAgo) ? { lastMeasuredEndedMsAgo } : {}),
202
+ ...(typeof lastMeasuredMs === "number" && Number.isFinite(lastMeasuredMs) && lastMeasuredMs >= 0 ? { lastMeasuredMs } : {}),
194
203
  ...(detail && typeof detail.operation === "string" && detail.operation.length <= 80
195
204
  && typeof detail.attempts === "number" && Number.isFinite(detail.attempts)
196
205
  ? { sqlite: { operation: detail.operation, attempts: detail.attempts, lockWait: detail.lockWait === true } }
@@ -219,6 +228,7 @@ interface StallContext {
219
228
  phase: StallReport["phase"];
220
229
  uptime: StallReport["uptime"];
221
230
  gap: GapBucket;
231
+ heldPercent?: number;
222
232
  attention: StallAttention | null;
223
233
  cpuPercent?: number;
224
234
  otherCpuPercent?: number;
@@ -227,10 +237,14 @@ interface StallContext {
227
237
  function stallContext(event: StallEvent, attention: StallAttention | null): StallContext {
228
238
  const cpuPercent = tens(event.threadCpu, 100);
229
239
  const otherCpuPercent = tens(event.otherCpu, MAX_OTHER_CPU_PERCENT);
240
+ const heldPercent = event.lastMeasured && event.lastMeasuredMs !== undefined
241
+ ? tens(Math.min(1, event.lastMeasuredMs / event.blockedMs), 100)
242
+ : undefined;
230
243
  return {
231
244
  phase: event.phase ?? "unknown",
232
245
  uptime: uptimeBucket(event.uptimeMs),
233
246
  gap: gapBucket(event),
247
+ ...(heldPercent === undefined ? {} : { heldPercent }),
234
248
  attention,
235
249
  ...(cpuPercent === undefined ? {} : { cpuPercent }),
236
250
  ...(otherCpuPercent === undefined ? {} : { otherCpuPercent }),
@@ -241,7 +255,7 @@ function stallContext(event: StallEvent, attention: StallAttention | null): Stal
241
255
  function formatStallLogLine(process: StallProcess, event: StallEvent, context: StallContext, at: number): string {
242
256
  const time = new Date(at).toISOString().replace(/\.\d{3}Z$/, "Z");
243
257
  const last = event.lastMeasured
244
- ? `last measured: ${event.lastMeasured}${event.lastMeasuredEndedMsAgo === undefined ? "" : `, ended ${Math.round(event.lastMeasuredEndedMsAgo)} ms before`}`
258
+ ? `last measured: ${event.lastMeasured}${event.lastMeasuredMs === undefined ? "" : `, ran ${Math.round(event.lastMeasuredMs)} ms`}${event.lastMeasuredEndedMsAgo === undefined ? "" : `, ended ${Math.round(event.lastMeasuredEndedMsAgo)} ms before`}`
245
259
  : "nothing measured before it";
246
260
  const sqlite = event.sqlite
247
261
  ? ` (${event.sqlite.operation}, ${event.sqlite.attempts} ${event.sqlite.attempts === 1 ? "try" : "tries"}${event.sqlite.lockWait ? ", waited on a lock" : ""})`
@@ -250,6 +264,7 @@ function formatStallLogLine(process: StallProcess, event: StallEvent, context: S
250
264
  `phase=${context.phase}`,
251
265
  `up=${context.uptime}`,
252
266
  `gap=${context.gap}`,
267
+ ...(context.heldPercent === undefined ? [] : [`held=${context.heldPercent}`]),
253
268
  ...(context.attention ? [`fg=${flag(context.attention.active)}`, `vis=${flag(context.attention.visible)}`] : []),
254
269
  ...(context.cpuPercent === undefined ? [] : [`cpu=${context.cpuPercent}`]),
255
270
  ...(context.otherCpuPercent === undefined ? [] : [`oth=${context.otherCpuPercent}`]),
@@ -281,6 +296,7 @@ export function formatStallReportDetails(report: StallReport): string {
281
296
  `phase=${report.phase}`,
282
297
  `up=${report.uptime}`,
283
298
  `gap=${report.gap}`,
299
+ ...(report.heldPercent === undefined ? [] : [`held=${report.heldPercent}`]),
284
300
  ...(report.active === undefined ? [] : [`fg=${flag(report.active)}`]),
285
301
  ...(report.visible === undefined ? [] : [`vis=${flag(report.visible)}`]),
286
302
  ...(report.cpuPercent === undefined ? [] : [`cpu=${report.cpuPercent}`]),
@@ -383,6 +399,7 @@ export function recordStall(process: StallProcess, event: StallEvent): void {
383
399
  phase: context.phase,
384
400
  uptime: context.uptime,
385
401
  gap: context.gap,
402
+ ...(context.heldPercent === undefined ? {} : { heldPercent: context.heldPercent }),
386
403
  ...(context.attention ? { active: context.attention.active, visible: context.attention.visible } : {}),
387
404
  ...(context.cpuPercent === undefined ? {} : { cpuPercent: context.cpuPercent }),
388
405
  ...(context.otherCpuPercent === undefined ? {} : { otherCpuPercent: context.otherCpuPercent }),
@@ -223,6 +223,13 @@ export interface QuoteBatchResult {
223
223
  target: QuoteSubscriptionTarget;
224
224
  quote: Quote | null;
225
225
  error?: unknown;
226
+ /**
227
+ * Set only with `deferFollowUps`: the batch left this target without a
228
+ * current quote, and `getQuote` with this cache mode is the read that
229
+ * settles it. `quote` meanwhile is the dated price the batch had, flagged
230
+ * stale, or none.
231
+ */
232
+ followUp?: "default" | "refresh";
226
233
  }
227
234
 
228
235
  export interface QuoteBatchOptions {
@@ -241,6 +248,13 @@ export interface QuoteBatchOptions {
241
248
  * each form's own copy from whenever it was last asked for.
242
249
  */
243
250
  revalidate?: boolean;
251
+ /**
252
+ * Answer from the cache and the batch read alone: a target they leave
253
+ * without a current quote comes back with `followUp` instead of being
254
+ * asked for on its own. A board paints the batch as soon as it answers and
255
+ * asks for those itself, so a slow one holds only its own row.
256
+ */
257
+ deferFollowUps?: boolean;
244
258
  /** The caller stopped waiting; a transport that can abandon the request does. */
245
259
  signal?: AbortSignal;
246
260
  /** The caller prints what each move is from (MarketDataRequestContext.datesChangeBasis). */
@@ -350,13 +350,25 @@ export interface Fundamentals extends DepositaryReceiptFacts {
350
350
  marketCap?: number;
351
351
  marketCapCurrency?: string;
352
352
  trailingPE?: number;
353
+ /** The price over next fiscal year's consensus EPS; absent when that EPS is not positive or there is none. */
353
354
  forwardPE?: number;
354
355
  /**
355
- * Forward EPS behind `forwardPE`, per share in the listing's major currency
356
- * unit. Served only when its basis matches the multiple, so the multiple can
357
- * be repriced from a live quote; absent otherwise.
356
+ * Next fiscal year's consensus EPS behind `forwardPE`, per share in the
357
+ * unit of the multiple's price, so the multiple can be repriced from a live
358
+ * quote. Served negative without a multiple (N/M); absent otherwise.
358
359
  */
359
360
  forwardEps?: number;
361
+ /** The currency `forwardEps` is in. */
362
+ forwardEpsCurrency?: string;
363
+ /**
364
+ * The end of the fiscal year the consensus is for (`2027-12-31` is FY27).
365
+ * Null when the source was asked and had no consensus for next year, or
366
+ * only one from before the listing's last split; absent from a block
367
+ * served before Gloom Cloud read consensus.
368
+ */
369
+ forwardEpsPeriodEnd?: string | null;
370
+ /** When the consensus was read. */
371
+ forwardEpsObservedAt?: string;
360
372
  pegRatio?: number;
361
373
  enterpriseValue?: number;
362
374
  enterpriseToRevenue?: number;
@@ -93,6 +93,8 @@ export interface HeadlessPaneOptionDef {
93
93
  list?: boolean;
94
94
  /** The option in use as typed after the function, such as `--expiration 2028-01-21`; the catalog shows it as an example. */
95
95
  example?: string;
96
+ /** Other uses the catalog shows after `example`: a form of the value the first does not show. */
97
+ examples?: readonly string[];
96
98
  /** The example runs without the function's optional argument, as an option that works only then does (`fn INS --side sell`). */
97
99
  exampleWithoutArgument?: boolean;
98
100
  /**
@@ -23,10 +23,11 @@ export function resetDoubleEscapeClose(state: DoubleEscapeCloseState) {
23
23
  }
24
24
 
25
25
  /**
26
- * Key handling for a double-Esc close: `take` runs before the pane and closes on the
27
- * second Esc of a pair, `arm` runs after it and only when nothing used the Esc.
28
- * So an Esc that backs out of a detail or closes a menu never counts as the
29
- * first half of a close.
26
+ * Key handling for a double-Esc close: `take` closes on the second Esc of a
27
+ * pair, before the pane sees it, and `arm` makes an Esc the first half. Every
28
+ * Esc arms, whatever the pane does with it (back out of a detail, clear a
29
+ * selection, leave a chart), except an Esc that leaves a draft or closes a
30
+ * menu: see `countEscapeTowardClose` and `keepEscapeFromClosing`.
30
31
  */
31
32
  export function takeDoubleEscapeClose(
32
33
  state: DoubleEscapeCloseState,
@@ -42,24 +43,45 @@ export function takeDoubleEscapeClose(
42
43
  return matched;
43
44
  }
44
45
 
45
- const escapeArmOffers = new WeakMap<object, () => void>();
46
+ interface EscapeOffer {
47
+ count(): void;
48
+ keep(): void;
49
+ kept: boolean;
50
+ }
51
+
52
+ const escapeOffers = new WeakMap<object, EscapeOffer>();
46
53
 
47
54
  /**
48
- * Leaving an empty text field is the one Esc a pane uses that still counts as
49
- * the first half of a close, so Esc Esc from an idle composer closes the pane.
50
- * The shell offers every Esc in its `before` phase, focused field or not; a
51
- * pane handler that runs later takes the offer with `countEscapeTowardClose`
52
- * and consumes the Esc as usual. Anything the Esc backs out of (a draft, a
53
- * reply, a menu) keeps it from counting.
55
+ * The shell offers every Esc to the pane before any handler runs, so a
56
+ * handler in any phase can say what its Esc did to the close.
54
57
  */
55
- export function offerEscapeTowardClose(event: object, arm: () => void) {
56
- escapeArmOffers.set(event, arm);
58
+ export function offerEscapeTowardClose(event: object, offer: { count(): void; keep(): void }) {
59
+ escapeOffers.set(event, { ...offer, kept: false });
57
60
  }
58
61
 
62
+ /**
63
+ * In a text field, or while a pane is editing, an Esc counts only when the
64
+ * pane says it left nothing typed behind: Esc Esc from an empty composer
65
+ * closes the pane, from a draft it never does.
66
+ */
59
67
  export function countEscapeTowardClose(event: object) {
60
- const arm = escapeArmOffers.get(event);
61
- escapeArmOffers.delete(event);
62
- arm?.();
68
+ const offer = escapeOffers.get(event);
69
+ if (offer && !offer.kept) offer.count();
70
+ }
71
+
72
+ /**
73
+ * An Esc that closes a menu or popover of the pane's own, or backs out of a
74
+ * draft, is not the first half of a close.
75
+ */
76
+ export function keepEscapeFromClosing(event: object) {
77
+ const offer = escapeOffers.get(event);
78
+ if (!offer) return;
79
+ offer.kept = true;
80
+ offer.keep();
81
+ }
82
+
83
+ export function isEscapeKeptFromClosing(event: object): boolean {
84
+ return escapeOffers.get(event)?.kept === true;
63
85
  }
64
86
 
65
87
  export function armDoubleEscapeClose(
@@ -132,11 +132,31 @@ export function formatPercentRaw(value: number | undefined): string {
132
132
  return `${signedFixed(value, 2)}%`;
133
133
  }
134
134
 
135
+ let figureColumnCells = 0;
136
+
137
+ /**
138
+ * Formats one cell of a right-aligned table column. Inside it `formatCompact`
139
+ * keeps its decimals unless the caller passes `fixedDecimals: false`, so a
140
+ * column of compact figures lines up: 12.00M over 10.73M, 10.0k over 12.5k.
141
+ * The table kit draws, reports and exports every right-aligned cell through
142
+ * this, so a pane's cell keeps the short 12M wherever else it says it (a
143
+ * figure, a sentence, a label).
144
+ */
145
+ export function inFigureColumn<T>(format: () => T): T {
146
+ figureColumnCells += 1;
147
+ try {
148
+ return format();
149
+ } finally {
150
+ figureColumnCells -= 1;
151
+ }
152
+ }
153
+
135
154
  /**
136
- * Format large numbers compactly (e.g., 1.5T, 234B, 12.3M, 5k). Table columns
137
- * pass `fixedDecimals` so 1.70T lines up with 1.33T.
155
+ * Format large numbers compactly (e.g., 1.5T, 234B, 12.3M, 5k). In a table
156
+ * column (`inFigureColumn`), or with `fixedDecimals`, the decimals stay so
157
+ * 1.70T lines up with 1.33T.
138
158
  */
139
- export function formatCompact(value: number | undefined, { fixedDecimals = false }: { fixedDecimals?: boolean } = {}): string {
159
+ export function formatCompact(value: number | undefined, { fixedDecimals = figureColumnCells > 0 }: { fixedDecimals?: boolean } = {}): string {
140
160
  if (value == null || !Number.isFinite(value)) return MISSING_VALUE;
141
161
  const { fixed, suffix } = compactParts(Math.abs(value));
142
162
  // Strip unnecessary trailing zeros after decimal point
@@ -1,4 +1,4 @@
1
- import { lastPerfSample, recordPerfSample, withoutLastStep } from "./perf-marks";
1
+ import { lastPerfSample, recordPerfSample, takeHeldPerfSample, takePersonWaitMs, withoutLastStep } from "./perf-marks";
2
2
 
3
3
  /** How often the monitor checks in. Short enough to date a stall precisely. */
4
4
  const SAMPLE_INTERVAL_MS = 250;
@@ -34,10 +34,19 @@ export interface StallClockReading {
34
34
  export interface StallEvent {
35
35
  /** How long the thread could not run while the computer was awake. */
36
36
  blockedMs: number;
37
- /** The last measured section before the stall (perf-marks), if any. */
37
+ /**
38
+ * The measured section that held the thread longest during the stall
39
+ * (perf-marks); the last one before it when none ended inside it.
40
+ */
38
41
  lastMeasured?: string;
39
42
  /** How long before the stall was noticed that section ended. */
40
43
  lastMeasuredEndedMsAgo?: number;
44
+ /**
45
+ * How long that section itself ran, when it ended inside the stall: near
46
+ * the stall's length it froze the thread, far below it ran in what queued
47
+ * up behind an unmeasured wait.
48
+ */
49
+ lastMeasuredMs?: number;
41
50
  /** When that section was a SQLite statement that held the thread. */
42
51
  sqlite?: StallSqliteDetail;
43
52
  /** How long the process had been running when the stall was noticed. */
@@ -147,7 +156,8 @@ function defaultNow(): number {
147
156
  * Names the freezes. A timer that should fire every quarter second is a
148
157
  * witness to everything that blocks the main thread, measured or not: when it
149
158
  * comes back late, the app was unresponsive for exactly that long. The report
150
- * carries the last measured section and how long before the stall it ended,
159
+ * carries the measured section that held the thread longest in that time (or
160
+ * the last one before it), how long it ran and how long before the stall it ended,
151
161
  * which is usually enough to tell "the cache read did it" from "the render
152
162
  * did it" in a report that only says the app hung for a few seconds, and how
153
163
  * long the process had been up, so a slow start reads apart from a hang
@@ -184,12 +194,17 @@ export function startMainThreadStallMonitor(
184
194
  const before = previousClocks;
185
195
  previous = current;
186
196
  previousClocks = currentClocks;
197
+ // Taken on every tick, so a stall weighs only the steps that ended inside it.
198
+ const held = takeHeldPerfSample();
199
+ const personWaitMs = takePersonWaitMs();
187
200
  const awakeMs = delta(currentClocks?.awakeMs, before?.awakeMs);
188
201
  // Asleep, the computer runs nothing; only the awake part of the gap was a freeze.
189
202
  const asleepMs = awakeMs == null ? 0 : Math.max(0, elapsedMs - awakeMs);
190
- const blockedMs = elapsedMs - asleepMs - intervalMs;
203
+ // A menu held open on the thread waited for the person, not the computer:
204
+ // only the rest of the gap was a freeze.
205
+ const blockedMs = elapsedMs - asleepMs - intervalMs - personWaitMs;
191
206
  if (blockedMs < thresholdMs) return;
192
- const sample = lastPerfSample();
207
+ const sample = held ?? lastPerfSample();
193
208
  const sqlite = sample?.name === "sqlite.blocked" ? sqliteDetail(sample.metadata) : undefined;
194
209
  const threadCpuMs = delta(currentClocks?.threadCpuMs, before?.threadCpuMs);
195
210
  const processCpuMs = delta(currentClocks?.processCpuMs, before?.processCpuMs);
@@ -197,6 +212,7 @@ export function startMainThreadStallMonitor(
197
212
  ...(sample
198
213
  ? { lastMeasured: sample.name, lastMeasuredEndedMsAgo: Math.round(current - sample.endedAt) }
199
214
  : {}),
215
+ ...(held ? { lastMeasuredMs: Math.round(held.durationMs) } : {}),
200
216
  ...(sqlite ? { sqlite } : {}),
201
217
  uptimeMs: Math.round(current),
202
218
  phase: startupComplete ? "steady" : "startup",
@@ -29,6 +29,15 @@ let lastSampleDurationMs = 0;
29
29
  let lastSampleMetadata: Record<string, unknown> | undefined;
30
30
  /** Inside `withoutLastStep`: samples are logged, and none becomes the last step. */
31
31
  let quietDepth = 0;
32
+ // The step that held the thread longest since the stall monitor last looked.
33
+ let heldName: string | null = null;
34
+ let heldEndedAt = 0;
35
+ let heldDurationMs = 0;
36
+ let heldMetadata: Record<string, unknown> | undefined;
37
+ // Time the thread spent waiting on a person (a menu held open on it): all
38
+ // told, and since the stall monitor last looked.
39
+ let personWaitTotalMs = 0;
40
+ let personWaitUntakenMs = 0;
32
41
 
33
42
  /**
34
43
  * The most recent measured section, when it ended and what it was measured
@@ -51,18 +60,78 @@ function lastStepAccountsForSection(startedAt: number, durationMs: number): bool
51
60
  return lastSampleName != null && lastSampleEndedAt >= startedAt && lastSampleDurationMs * 2 >= durationMs;
52
61
  }
53
62
 
63
+ /**
64
+ * Keeps the step that held the thread longest since the stall monitor last
65
+ * looked (`takeHeldPerfSample`). After a freeze the thread first runs what
66
+ * queued up behind it, so the last step before the monitor's late timer is
67
+ * rarely what froze it. A step inside a section that took at least half of
68
+ * it stands for the section, as it does for the last step.
69
+ */
70
+ function noteHeldStep(
71
+ name: string,
72
+ startedAt: number,
73
+ endedAt: number,
74
+ durationMs: number,
75
+ metadata: Record<string, unknown> | undefined,
76
+ ): void {
77
+ if (heldName != null) {
78
+ const inside = heldEndedAt >= startedAt;
79
+ if (inside ? heldDurationMs * 2 >= durationMs : heldDurationMs >= durationMs) return;
80
+ }
81
+ heldName = name;
82
+ heldEndedAt = endedAt;
83
+ heldDurationMs = durationMs;
84
+ heldMetadata = metadata;
85
+ }
86
+
87
+ /**
88
+ * The step that held the thread longest since the last call, and forgets it:
89
+ * the stall monitor asks on every tick, so a stall only weighs the steps that
90
+ * ended inside it. Only steps that ran on the thread throughout count, not an
91
+ * awaited one's time, and not the time a step waited on a person.
92
+ */
93
+ export function takeHeldPerfSample(): { name: string; endedAt: number; durationMs: number; metadata?: Record<string, unknown> } | null {
94
+ if (heldName == null) return null;
95
+ const held = { name: heldName, endedAt: heldEndedAt, durationMs: heldDurationMs, ...(heldMetadata ? { metadata: heldMetadata } : {}) };
96
+ heldName = null;
97
+ heldMetadata = undefined;
98
+ return held;
99
+ }
100
+
101
+ function notePersonWait(ms: number): void {
102
+ if (!(ms > 0)) return;
103
+ personWaitTotalMs += ms;
104
+ personWaitUntakenMs += ms;
105
+ }
106
+
107
+ /**
108
+ * How long the thread waited on a person (`waitedOnPerson`) since the last
109
+ * call, and forgets it: the stall monitor takes it out of a stall, which
110
+ * leaves only the freeze around it.
111
+ */
112
+ export function takePersonWaitMs(): number {
113
+ const ms = personWaitUntakenMs;
114
+ personWaitUntakenMs = 0;
115
+ return ms;
116
+ }
117
+
54
118
  function logSlowPerfSample(
55
119
  name: string,
56
120
  durationMs: number,
57
121
  metadata?: Record<string, unknown>,
58
122
  lastStep = true,
59
123
  startedAt?: number,
124
+ heldMs: number | null = null,
60
125
  ): void {
61
- if (lastStep && quietDepth === 0 && (startedAt === undefined || !lastStepAccountsForSection(startedAt, durationMs))) {
62
- lastSampleName = name;
63
- lastSampleEndedAt = now();
64
- lastSampleDurationMs = durationMs;
65
- lastSampleMetadata = metadata;
126
+ if (lastStep && quietDepth === 0) {
127
+ const endedAt = now();
128
+ if (startedAt === undefined || !lastStepAccountsForSection(startedAt, durationMs)) {
129
+ lastSampleName = name;
130
+ lastSampleEndedAt = endedAt;
131
+ lastSampleDurationMs = durationMs;
132
+ lastSampleMetadata = metadata;
133
+ }
134
+ if (heldMs != null && heldMs > 0) noteHeldStep(name, startedAt ?? endedAt - durationMs, endedAt, heldMs, metadata);
66
135
  }
67
136
  const payload = {
68
137
  durationMs: Math.round(durationMs * 10) / 10,
@@ -101,30 +170,40 @@ export function isPerfTraceEnabled(): boolean {
101
170
  * A sample measured elsewhere (a React Profiler callback, for instance).
102
171
  * `lastStep: false` logs it without making it the step a later stall names:
103
172
  * the stall monitor's own samples, which measure no work.
173
+ * `waitedOnPerson`: the time went to a person's choice (a menu held open),
174
+ * which the stall monitor does not count as a freeze.
104
175
  */
105
176
  export function recordPerfSample(
106
177
  name: string,
107
178
  durationMs: number,
108
179
  metadata?: Record<string, unknown>,
109
- options?: { lastStep?: boolean },
180
+ options?: { lastStep?: boolean; waitedOnPerson?: boolean },
110
181
  ): void {
111
- logSlowPerfSample(name, durationMs, metadata, options?.lastStep !== false);
182
+ if (options?.waitedOnPerson) notePersonWait(durationMs);
183
+ logSlowPerfSample(name, durationMs, metadata, options?.lastStep !== false, undefined, options?.waitedOnPerson ? null : durationMs);
112
184
  }
113
185
 
114
186
  /**
115
187
  * Measures `fn`. A step measured inside it that took most of its time stays
116
- * the step a stall names (`lastStepAccountsForSection`).
188
+ * the step a stall names (`lastStepAccountsForSection`). `waitedOnPerson` as
189
+ * for `recordPerfSample`.
117
190
  */
118
191
  export function measurePerf<T>(
119
192
  name: string,
120
193
  fn: () => T,
121
194
  metadata?: Record<string, unknown>,
195
+ options?: { waitedOnPerson?: boolean },
122
196
  ): T {
123
197
  const start = now();
198
+ const personWaitBefore = personWaitTotalMs;
124
199
  try {
125
200
  return fn();
126
201
  } finally {
127
- logSlowPerfSample(name, now() - start, metadata, true, start);
202
+ const durationMs = now() - start;
203
+ // A person's wait inside it is not the thread's work.
204
+ const ownMs = Math.max(0, durationMs - (personWaitTotalMs - personWaitBefore));
205
+ if (options?.waitedOnPerson) notePersonWait(ownMs);
206
+ logSlowPerfSample(name, durationMs, metadata, true, start, options?.waitedOnPerson ? null : ownMs);
128
207
  }
129
208
  }
130
209
 
@@ -39,6 +39,24 @@ export function formatPriceEarnings(value: PriceEarnings | null | undefined, pre
39
39
  return value <= 0 ? "N/M" : formatNumber(value, precision);
40
40
  }
41
41
 
42
+ /**
43
+ * The fiscal year a forward consensus is for, as a label names it: `FY27`
44
+ * for a year that ends in 2027, whichever month. Null for a block that does
45
+ * not say.
46
+ */
47
+ export function forwardFiscalYear(periodEnd: string | null | undefined): string | null {
48
+ return typeof periodEnd === "string" && /^\d{4}-\d{2}-\d{2}$/.test(periodEnd) ? `FY${periodEnd.slice(2, 4)}` : null;
49
+ }
50
+
51
+ /**
52
+ * Whether a forward P/E line is shown even with no figure: the block read
53
+ * next year's consensus for a company (one with a trailing EPS) and found
54
+ * none, or one from before the last split, which reads as a dash.
55
+ */
56
+ export function forwardPEAsked(fundamentals: Pick<Fundamentals, "forwardEpsPeriodEnd" | "eps"> | undefined): boolean {
57
+ return fundamentals?.forwardEpsPeriodEnd !== undefined && fundamentals.eps != null;
58
+ }
59
+
42
60
  type PriceEarningsField = "trailingPE" | "forwardPE" | "pegRatio";
43
61
 
44
62
  /**
@@ -17,16 +17,23 @@ export function formatPerShareNumber(value: number | undefined): string {
17
17
  return formatNumber(value === 0 ? 0 : value, perShareDecimals(value)).replace(/(\.\d{2}.*?)0+$/, "$1");
18
18
  }
19
19
 
20
+ /**
21
+ * What a report says once, beside or under amounts whose currency no source
22
+ * names (formatReportedMoney leaves them bare): never a guess at one.
23
+ */
24
+ export const REPORTING_CURRENCY_NOT_SOURCED = "reporting currency not sourced";
25
+
20
26
  /**
21
27
  * Keep reported monetary amounts in their own units, independently of a
22
28
  * quote. A per-share amount reads with its sign ($6.54), or with `code` its
23
- * code (6.54 USD) as every other amount does.
29
+ * code (6.54 USD) as every other amount does. With no currency the amount is
30
+ * bare, and the report says REPORTING_CURRENCY_NOT_SOURCED once for it.
24
31
  */
25
32
  export function formatReportedMoney(value: number | undefined, currency?: string, perShare = false, code = false): string {
26
33
  if (value == null || !Number.isFinite(value)) return "—";
27
34
  const amount = perShare ? formatPerShareNumber(value) : formatCompact(value);
28
35
  const unit = currency?.trim();
29
- if (!unit) return `${amount} (ccy?)`;
36
+ if (!unit) return amount;
30
37
  // Intl uppercases currency codes: GBp must not become GBP without scaling.
31
38
  if (perShare && !usesScientificNotation(value) && /^[a-z]{3}$/i.test(unit) && resolveCurrencyUnit(unit).divisor === 1) {
32
39
  return (code ? formatCurrencyCode : formatCurrency)(value === 0 ? 0 : value, unit, perShareDecimals(value));
package/src/utils/sec.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { TickerRecord } from "../types/ticker";
2
2
  import { tickerHasListingSuffix } from "../sources/listing-symbols";
3
- import { canonicalExchange, exchangeLabel, parsePublicTickerKey, resolveExchangeTimeZone, US_LISTING_EXCHANGES } from "./exchanges";
3
+ import { canonicalExchange, exchangeLabel, parsePublicTickerKey, publicTickerKey, resolveExchangeTimeZone, US_LISTING_EXCHANGES } from "./exchanges";
4
4
  import { shortListingTitle } from "../tickers/company-name";
5
5
 
6
6
  /** Canonical US equity venues: the listing exchanges plus other lit and OTC venues. */
@@ -69,6 +69,17 @@ export function mayBeUsEquityOrFundTicker(ticker: TickerRecord | null | undefine
69
69
  return mayBeUsListingOfType(ticker, (type) => isEquityType(type) || isFundType(type));
70
70
  }
71
71
 
72
+ /**
73
+ * Whether the fund view (ETF) can open on the ticker: `mayBeUsEquityOrFundTicker`,
74
+ * or an equity or fund known to be listed abroad (3046.HK), which the view
75
+ * gives its issuer's figures where Gloom reads them, and its issuer's page
76
+ * otherwise. Before this `ETF 3046.HK` opened nothing.
77
+ */
78
+ export function mayBeFundViewTicker(ticker: TickerRecord | null | undefined): boolean {
79
+ if (mayBeUsEquityOrFundTicker(ticker)) return true;
80
+ return isTickerOfType(ticker, (type) => isEquityType(type) || isFundType(type)) && isKnownNonUsListing(ticker);
81
+ }
82
+
72
83
  function isTickerOfType(ticker: TickerRecord | null | undefined, acceptsType: (type?: string) => boolean): boolean {
73
84
  if (!ticker) return false;
74
85
  const primaryContract = ticker.metadata.broker_contracts?.[0];
@@ -141,8 +152,28 @@ export function listingAbroadVenue(key: string): string | null {
141
152
  return venue && zone && zone !== "UTC" && !US_TIME_ZONES.has(zone) ? venue : null;
142
153
  }
143
154
 
144
- /** What `ticker` and ETF say of a fund listed abroad: the facts Gloom collects are the US-listed funds'. */
145
- export const US_FUND_FACTS_ONLY = "Fund facts (fee, NAV, premium) cover US-listed funds only.";
155
+ /** What `ticker` and ETF say of a fund listed abroad: the facts Gloom collects are the US-listed funds' and Hong Kong's spot coin funds'. */
156
+ export const US_FUND_FACTS_ONLY = "Fund facts (fee, NAV, premium) cover US-listed funds and Hong Kong's spot bitcoin and ether ETFs only.";
157
+
158
+ /**
159
+ * Whether a fund on this venue abroad can have facts: Hong Kong, whose spot
160
+ * bitcoin and ether ETFs Gloom reads from their issuers. The server says which
161
+ * of its funds are covered.
162
+ */
163
+ export function hasFundFactsAbroad(exchange?: string | null): boolean {
164
+ return canonicalExchange(exchange ?? undefined) === "HKEX";
165
+ }
166
+
167
+ /**
168
+ * What fund facts are asked for by, for a fund on a venue abroad: a bare
169
+ * code with its venue's key (3046 on HKEX as 3046:XHKG), so the server reads
170
+ * it as that listing and not as a US ticker; a key or suffix that already
171
+ * names its venue (3046:HKEX, 3046.HK) as it is.
172
+ */
173
+ export function fundFactsAbroadKey(symbol: string, exchange?: string | null): string {
174
+ if (parsePublicTickerKey(symbol).exchange || tickerHasListingSuffix(symbol)) return symbol;
175
+ return publicTickerKey(symbol, exchange ?? undefined);
176
+ }
146
177
 
147
178
  /**
148
179
  * The symbol data that covers US listings only reads a listing by: AAPL for