@gloom-sh/terminal 0.20.16 → 0.20.18

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 (345) hide show
  1. package/package.json +3 -1
  2. package/src/account/auth-dialog.tsx +19 -1
  3. package/src/account/billing.ts +2 -1
  4. package/src/account/heard-from-question.tsx +235 -0
  5. package/src/account/heard-from.ts +97 -0
  6. package/src/api-client/data.ts +16 -5
  7. package/src/api-client/heard-from.ts +72 -0
  8. package/src/api-client/index.ts +63 -6
  9. package/src/api-client/mna.ts +18 -0
  10. package/src/api-client/supply-chain.ts +9 -0
  11. package/src/api-client/types/billing.ts +35 -1
  12. package/src/api-client/types/econ.ts +3 -0
  13. package/src/app/global-shortcuts.ts +5 -3
  14. package/src/app/pro-welcome/keys.ts +27 -0
  15. package/src/app/pro-welcome/model.ts +158 -0
  16. package/src/app/pro-welcome/row.tsx +176 -0
  17. package/src/app/pro-welcome/use-pro-welcome.ts +156 -0
  18. package/src/app/runtime/external-profile-changes.ts +135 -0
  19. package/src/app.tsx +33 -2
  20. package/src/architecture/core-builtin-allowlist.json +1 -1
  21. package/src/architecture/floating-promise-allowlist.json +0 -1
  22. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  23. package/src/cli/alert-listing.ts +98 -0
  24. package/src/cli/commands/fred-series.ts +3 -1
  25. package/src/cli/commands/market.ts +138 -22
  26. package/src/cli/commands/overview.ts +72 -14
  27. package/src/cli/commands/plugins.ts +3 -2
  28. package/src/cli/commands/search.ts +30 -6
  29. package/src/cli/context.ts +16 -5
  30. package/src/cli/csv-export.ts +74 -0
  31. package/src/cli/desktop-pane-shot.ts +75 -11
  32. package/src/cli/glossary.ts +64 -10
  33. package/src/cli/help.ts +4 -2
  34. package/src/cli/history-demergers.ts +117 -0
  35. package/src/cli/history-rows.ts +6 -2
  36. package/src/cli/index.ts +1 -0
  37. package/src/cli/known-gaps.ts +16 -0
  38. package/src/cli/known-us-stocks.ts +18 -0
  39. package/src/cli/listing-arg.ts +105 -15
  40. package/src/cli/pane-functions/catalog-snapshot-build.ts +83 -0
  41. package/src/cli/pane-functions/catalog-snapshot.json +866 -0
  42. package/src/cli/pane-functions/catalog-snapshot.ts +62 -0
  43. package/src/cli/pane-functions/catalog.ts +50 -16
  44. package/src/cli/pane-functions/data.ts +16 -4
  45. package/src/cli/pane-functions/dom.ts +24 -6
  46. package/src/cli/pane-functions/freshness.ts +17 -1
  47. package/src/cli/pane-functions/headless.ts +7 -2
  48. package/src/cli/pane-functions/index.ts +102 -44
  49. package/src/cli/pane-functions/resolver.ts +8 -5
  50. package/src/cli/pane-functions/screenshot-assessment.ts +30 -7
  51. package/src/cli/pane-functions/screenshot-bridge.ts +4 -2
  52. package/src/cli/pane-functions/screenshot-payload.ts +21 -0
  53. package/src/cli/pane-functions/screenshot-render.ts +3 -1
  54. package/src/cli/quote-answer.ts +32 -16
  55. package/src/cli/registry.ts +22 -2
  56. package/src/cli/report-tables.ts +17 -3
  57. package/src/cli/result.ts +8 -10
  58. package/src/cli/series-search.ts +45 -6
  59. package/src/cli/shot-temp-dir.ts +4 -9
  60. package/src/components/chart/composite/legend.tsx +80 -25
  61. package/src/components/chart/composite/panel-surface/panel-cursor.tsx +3 -3
  62. package/src/components/chart/composite/price-axis-labels.tsx +7 -5
  63. package/src/components/chart-table/header.tsx +9 -0
  64. package/src/components/chart-table/layout.ts +11 -11
  65. package/src/components/command-bar/pane-templates/items.ts +17 -1
  66. package/src/components/command-bar/routes/root/provider-search.ts +10 -1
  67. package/src/components/command-bar/routes/root/results.ts +34 -2
  68. package/src/components/command-bar/routes/root/runtime.ts +8 -1
  69. package/src/components/command-bar/routes/ticker-search/route.ts +5 -0
  70. package/src/components/command-bar/workflow/alert.ts +19 -8
  71. package/src/components/data-table/view.tsx +15 -2
  72. package/src/components/form-modal/content.tsx +9 -4
  73. package/src/components/index.ts +1 -1
  74. package/src/components/layout/header.tsx +9 -5
  75. package/src/components/layout/pane/capture-status.ts +6 -0
  76. package/src/components/layout/pane/footer/index.tsx +2 -0
  77. package/src/components/layout/pane/footer/model.ts +113 -15
  78. package/src/components/layout/pane/header.tsx +16 -2
  79. package/src/components/market-board/index.tsx +4 -2
  80. package/src/components/onboarding/onboarding-frame.tsx +6 -2
  81. package/src/components/onboarding/onboarding-keyboard.ts +7 -1
  82. package/src/components/onboarding/onboarding-wizard.tsx +3 -1
  83. package/src/components/onboarding/portfolio-step/positions-panel.tsx +24 -15
  84. package/src/components/onboarding/setup-cards.ts +36 -0
  85. package/src/components/onboarding/use-onboarding-progress.ts +22 -1
  86. package/src/components/onboarding/wizard-account.ts +6 -1
  87. package/src/components/onboarding/wizard-model.ts +32 -6
  88. package/src/components/onboarding/wizard-positions.ts +1 -1
  89. package/src/components/sign-in-gate.tsx +3 -1
  90. package/src/components/toggle-list.tsx +6 -8
  91. package/src/components/ui/confirm-dialog.tsx +47 -7
  92. package/src/components/ui/data-table/display-columns.ts +4 -1
  93. package/src/components/ui/data-table/hooks.ts +2 -3
  94. package/src/components/ui/data-table/index.tsx +4 -1
  95. package/src/components/ui/data-table/types.ts +19 -4
  96. package/src/components/ui/data-table/visible-range.ts +11 -1
  97. package/src/components/ui/display.tsx +17 -2
  98. package/src/components/ui/index.ts +1 -1
  99. package/src/components/ui/stat-grid.tsx +4 -0
  100. package/src/components/ui/status.tsx +13 -1
  101. package/src/components/ui/table-layout.ts +2 -1
  102. package/src/components/use-pane-notice-footer.tsx +16 -3
  103. package/src/data/config/store/index.ts +31 -0
  104. package/src/data/config/store/node.ts +61 -11
  105. package/src/data/config/store/normalize.ts +4 -6
  106. package/src/data/config/store/shared-file.ts +309 -0
  107. package/src/data/profile-merge.ts +299 -0
  108. package/src/data/sqlite/checkpointer.ts +11 -1
  109. package/src/data/sqlite/database.ts +1 -1
  110. package/src/data/ticker-repository.ts +134 -10
  111. package/src/data/ticker-store.ts +67 -0
  112. package/src/data/ticker-writes.ts +5 -0
  113. package/src/i18n/es.ts +27 -0
  114. package/src/i18n/ja.ts +27 -0
  115. package/src/i18n/ko.ts +27 -0
  116. package/src/i18n/zh-cn.ts +27 -0
  117. package/src/i18n/zh-tw.ts +27 -0
  118. package/src/layout-marketplace/gallery-desktop.tsx +2 -2
  119. package/src/market-data/ah-pair.ts +103 -0
  120. package/src/market-data/depositary-pair.ts +6 -2
  121. package/src/market-data/hooks.tsx +33 -2
  122. package/src/market-data/market/change-basis.ts +2 -1
  123. package/src/market-data/market/header-market.ts +11 -0
  124. package/src/market-data/split-terms.ts +28 -0
  125. package/src/plugins/builtin/account-management/footer.ts +1 -1
  126. package/src/plugins/builtin/account-management/keyboard.ts +4 -0
  127. package/src/plugins/builtin/account-management/model.ts +1 -0
  128. package/src/plugins/builtin/account-management/pane.tsx +75 -7
  129. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +12 -5
  130. package/src/plugins/builtin/account-management/pro-cancel.tsx +197 -0
  131. package/src/plugins/builtin/account-management/trial-cancel.ts +1 -1
  132. package/src/plugins/builtin/alerts/cli-move.ts +2 -2
  133. package/src/plugins/builtin/alerts/cli.ts +36 -30
  134. package/src/plugins/builtin/alerts/constants.ts +10 -0
  135. package/src/plugins/builtin/alerts/earnings-listing.ts +20 -0
  136. package/src/plugins/builtin/alerts/format.ts +24 -8
  137. package/src/plugins/builtin/alerts/index.tsx +38 -9
  138. package/src/plugins/builtin/alerts/move-checks.ts +7 -0
  139. package/src/plugins/builtin/alerts/pane.tsx +1 -1
  140. package/src/plugins/builtin/alerts/quotes.ts +26 -2
  141. package/src/plugins/builtin/alerts/scheduled.ts +6 -1
  142. package/src/plugins/builtin/alerts/types.ts +7 -0
  143. package/src/plugins/builtin/analytics/manual-value.ts +61 -0
  144. package/src/plugins/builtin/analytics/risk-book.ts +7 -7
  145. package/src/plugins/builtin/analytics/risk-client.ts +26 -13
  146. package/src/plugins/builtin/analytics/risk-headless.ts +13 -8
  147. package/src/plugins/builtin/analytics/risk-model.ts +92 -4
  148. package/src/plugins/builtin/analytics/risk-pane.tsx +85 -38
  149. package/src/plugins/builtin/awards/pane.tsx +7 -3
  150. package/src/plugins/builtin/broker-trading/orders.tsx +2 -2
  151. package/src/plugins/builtin/central-bank-rates/model.ts +8 -2
  152. package/src/plugins/builtin/central-bank-rates/pane.tsx +5 -3
  153. package/src/plugins/builtin/chart-composer/cli-options.ts +4 -2
  154. package/src/plugins/builtin/chart-composer/data-catalog-pane.tsx +2 -6
  155. package/src/plugins/builtin/chart-composer/pane.tsx +9 -3
  156. package/src/plugins/builtin/cloud/auth-actions.tsx +11 -6
  157. package/src/plugins/builtin/cloud/company-picker.tsx +5 -3
  158. package/src/plugins/builtin/cloud/upgrade-command.ts +1 -1
  159. package/src/plugins/builtin/company-kpis/headless.ts +9 -4
  160. package/src/plugins/builtin/company-kpis/latest.ts +45 -0
  161. package/src/plugins/builtin/company-kpis/model.ts +38 -8
  162. package/src/plugins/builtin/company-kpis/pane.tsx +22 -8
  163. package/src/plugins/builtin/composite/alt-data.ts +20 -0
  164. package/src/plugins/builtin/composite/application.ts +14 -0
  165. package/src/plugins/builtin/composite/broker.ts +12 -0
  166. package/src/plugins/builtin/composite/credit.ts +33 -0
  167. package/src/plugins/builtin/composite/crypto.ts +10 -0
  168. package/src/plugins/builtin/composite/earnings.ts +12 -0
  169. package/src/plugins/builtin/composite/filings.ts +13 -0
  170. package/src/plugins/builtin/composite/futures-commodities.ts +23 -0
  171. package/src/plugins/builtin/composite/global-markets.ts +12 -0
  172. package/src/plugins/builtin/composite/options-volatility.ts +23 -0
  173. package/src/plugins/builtin/composite/ownership.ts +23 -0
  174. package/src/plugins/builtin/composite/portfolio.ts +10 -0
  175. package/src/plugins/builtin/composite/quant.ts +15 -0
  176. package/src/plugins/builtin/composite/rates-macro.ts +30 -0
  177. package/src/plugins/builtin/composite/screeners.ts +11 -0
  178. package/src/plugins/builtin/composite/shared.ts +11 -0
  179. package/src/plugins/builtin/composite/ticker-core.ts +36 -0
  180. package/src/plugins/builtin/congress-trades/headless.ts +31 -3
  181. package/src/plugins/builtin/correlation/index.tsx +13 -17
  182. package/src/plugins/builtin/correlation/matrix/model.ts +18 -0
  183. package/src/plugins/builtin/credit-conditions/series.ts +2 -2
  184. package/src/plugins/builtin/dividend-yield/client.ts +57 -16
  185. package/src/plugins/builtin/dividend-yield/headless.ts +17 -11
  186. package/src/plugins/builtin/dividend-yield/model.ts +4 -3
  187. package/src/plugins/builtin/dividend-yield/pane.tsx +22 -18
  188. package/src/plugins/builtin/dividend-yield/ranking.ts +1 -1
  189. package/src/plugins/builtin/dividend-yield/types.ts +4 -0
  190. package/src/plugins/builtin/dividend-yield/view.ts +23 -12
  191. package/src/plugins/builtin/earnings/board-model.ts +12 -0
  192. package/src/plugins/builtin/earnings/board-table.ts +7 -4
  193. package/src/plugins/builtin/earnings/board.tsx +2 -2
  194. package/src/plugins/builtin/earnings/fiscal-quarter.ts +39 -0
  195. package/src/plugins/builtin/earnings/headless.ts +7 -4
  196. package/src/plugins/builtin/earnings/highlight.ts +1 -1
  197. package/src/plugins/builtin/earnings/history-model.ts +6 -4
  198. package/src/plugins/builtin/earnings/history-table.ts +4 -3
  199. package/src/plugins/builtin/earnings-calls/pane.tsx +8 -2
  200. package/src/plugins/builtin/econ/calendar-model.ts +18 -0
  201. package/src/plugins/builtin/econ/fred-catalog.ts +1 -256
  202. package/src/plugins/builtin/econ/index.tsx +3 -0
  203. package/src/plugins/builtin/econ-statistics/cache.ts +1 -1
  204. package/src/plugins/builtin/econ-statistics/client.ts +11 -10
  205. package/src/plugins/builtin/econ-statistics/detail.tsx +1 -0
  206. package/src/plugins/builtin/econ-statistics/headless.ts +42 -6
  207. package/src/plugins/builtin/econ-statistics/index.tsx +1 -0
  208. package/src/plugins/builtin/econ-statistics/pane.tsx +7 -2
  209. package/src/plugins/builtin/econ-statistics/stats.ts +2 -1
  210. package/src/plugins/builtin/econ-statistics/view.ts +9 -3
  211. package/src/plugins/builtin/equity-screener/headless.ts +4 -1
  212. package/src/plugins/builtin/equity-screener/model.ts +7 -6
  213. package/src/plugins/builtin/estimate-revisions/headless.ts +1 -1
  214. package/src/plugins/builtin/exposure/model.ts +10 -0
  215. package/src/plugins/builtin/exposure/pane.tsx +10 -3
  216. package/src/plugins/builtin/fx-matrix/amount.ts +15 -1
  217. package/src/plugins/builtin/fx-matrix/headless.ts +12 -6
  218. package/src/plugins/builtin/fx-matrix/index.tsx +23 -5
  219. package/src/plugins/builtin/fx-matrix/settings.ts +9 -4
  220. package/src/plugins/builtin/kelly-sizer/pane.tsx +9 -4
  221. package/src/plugins/builtin/market-valuation/pane.tsx +22 -10
  222. package/src/plugins/builtin/mna/detail.tsx +67 -6
  223. package/src/plugins/builtin/mna/headless.ts +128 -13
  224. package/src/plugins/builtin/mna/model.ts +219 -16
  225. package/src/plugins/builtin/mna/pane.tsx +34 -6
  226. package/src/plugins/builtin/money-markets/model.ts +14 -5
  227. package/src/plugins/builtin/money-markets/pane.tsx +4 -3
  228. package/src/plugins/builtin/news/wire/news/footer.ts +3 -8
  229. package/src/plugins/builtin/options-scenario/csp-screen-pane.tsx +22 -6
  230. package/src/plugins/builtin/options-scenario/csp-screen.ts +39 -12
  231. package/src/plugins/builtin/options-scenario/strategy-screen.ts +7 -5
  232. package/src/plugins/builtin/pe-band/client.ts +13 -1
  233. package/src/plugins/builtin/pe-band/headless.ts +2 -2
  234. package/src/plugins/builtin/pe-band/model.ts +63 -10
  235. package/src/plugins/builtin/pe-band/pane.tsx +5 -5
  236. package/src/plugins/builtin/portfolio-list/allocation-rows.ts +26 -7
  237. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +66 -13
  238. package/src/plugins/builtin/portfolio-list/cli/render.ts +76 -33
  239. package/src/plugins/builtin/portfolio-list/headless.ts +69 -22
  240. package/src/plugins/builtin/portfolio-list/pane/data.ts +3 -3
  241. package/src/plugins/builtin/portfolio-list/pane/index.tsx +29 -14
  242. package/src/plugins/builtin/portfolio-list/summary/index.tsx +2 -2
  243. package/src/plugins/builtin/relative-rotation/pane.tsx +2 -3
  244. package/src/plugins/builtin/research/corporate-actions-pane.tsx +5 -1
  245. package/src/plugins/builtin/research/event-model.ts +31 -13
  246. package/src/plugins/builtin/research/headless.ts +8 -1
  247. package/src/plugins/builtin/research/relative-valuation-pane.tsx +19 -17
  248. package/src/plugins/builtin/sectors/index.tsx +6 -9
  249. package/src/plugins/builtin/shared/cloud-upgrade.ts +1 -1
  250. package/src/plugins/builtin/shared/earnings-report.ts +19 -4
  251. package/src/plugins/builtin/shared/fred-catalog.ts +256 -0
  252. package/src/plugins/builtin/shared/report-freshness.ts +2 -3
  253. package/src/plugins/builtin/shared/series-cache.ts +3 -0
  254. package/src/plugins/builtin/shared/series-detail-chart.tsx +3 -0
  255. package/src/plugins/builtin/short-interest/watch-pane.tsx +7 -7
  256. package/src/plugins/builtin/supply-chain/client.ts +34 -9
  257. package/src/plugins/builtin/supply-chain/evidence.ts +3 -2
  258. package/src/plugins/builtin/supply-chain/flow.tsx +4 -3
  259. package/src/plugins/builtin/supply-chain/graph-model.ts +14 -7
  260. package/src/plugins/builtin/supply-chain/graph-pane.tsx +3 -1
  261. package/src/plugins/builtin/supply-chain/graph.tsx +6 -3
  262. package/src/plugins/builtin/supply-chain/headless.ts +19 -4
  263. package/src/plugins/builtin/supply-chain/model.ts +50 -6
  264. package/src/plugins/builtin/supply-chain/pane.tsx +76 -16
  265. package/src/plugins/builtin/ticker-detail/adr-pair/ah.ts +62 -0
  266. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +119 -20
  267. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +67 -1
  268. package/src/plugins/builtin/ticker-detail/adr-pair/tab.tsx +31 -16
  269. package/src/plugins/builtin/ticker-detail/overview/model.ts +17 -1
  270. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +4 -0
  271. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +9 -2
  272. package/src/plugins/builtin/ticker-detail/quote-monitor/card.tsx +9 -2
  273. package/src/plugins/builtin/ticker-detail/quote-monitor/index.tsx +5 -2
  274. package/src/plugins/builtin/time-sales/headless.ts +4 -1
  275. package/src/plugins/builtin/time-sales/pane.tsx +2 -0
  276. package/src/plugins/builtin/time-sales/window.ts +12 -0
  277. package/src/plugins/builtin/treasury-auctions/client.ts +4 -0
  278. package/src/plugins/builtin/treasury-auctions/treasury-direct.ts +2 -0
  279. package/src/plugins/builtin/treasury-daily/client.ts +23 -11
  280. package/src/plugins/builtin/volatility/model.ts +17 -0
  281. package/src/plugins/builtin/volatility/pane.tsx +13 -4
  282. package/src/plugins/builtin/world-indices/index.tsx +2 -0
  283. package/src/plugins/builtin/world-indices/table.tsx +15 -0
  284. package/src/plugins/builtin/world-venue-map/evidence.ts +3 -2
  285. package/src/plugins/builtin/world-venue-map/headless.ts +28 -16
  286. package/src/plugins/builtin/world-venue-map/index.ts +19 -6
  287. package/src/plugins/builtin/world-venue-map/layered-pane.tsx +9 -5
  288. package/src/plugins/builtin/world-venue-map/layers.ts +33 -11
  289. package/src/plugins/builtin/world-venue-map/map.tsx +12 -0
  290. package/src/plugins/builtin/world-venue-map/pane.tsx +35 -6
  291. package/src/plugins/builtin/world-venue-map/place.ts +119 -0
  292. package/src/plugins/catalog-data.ts +20 -0
  293. package/src/plugins/catalog-lazy.ts +51 -0
  294. package/src/plugins/catalog-ui.ts +16 -18
  295. package/src/plugins/host-smoke.ts +5 -2
  296. package/src/portfolio/allocation.ts +79 -19
  297. package/src/portfolio/cash-balances.ts +76 -0
  298. package/src/portfolio/mutations.ts +43 -8
  299. package/src/public/__snapshots__/public-api.test.ts.snap +1 -0
  300. package/src/renderers/desktop/window-layouts.ts +14 -0
  301. package/src/renderers/dom/data-table/row.tsx +2 -0
  302. package/src/renderers/dom/host/tabs.tsx +57 -8
  303. package/src/renderers/dom/styles.css +13 -5
  304. package/src/renderers/electrobun/bun/desktop/backend-requests.ts +4 -0
  305. package/src/renderers/electrobun/bun/desktop/backend.ts +22 -1
  306. package/src/renderers/electrobun/bun/window/native-min-size.ts +6 -1
  307. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  308. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +2 -0
  309. package/src/renderers/electrobun/view/cli-pane-shot-frame.tsx +50 -12
  310. package/src/renderers/electrobun/view/remote/ticker-repository.ts +10 -0
  311. package/src/series/standalone-catalog.ts +5 -4
  312. package/src/series/standalone.ts +13 -7
  313. package/src/sources/gloomberb-cloud/fred-publisher.ts +25 -0
  314. package/src/sources/gloomberb-cloud/fred-series.ts +1 -1
  315. package/src/sources/gloomberb-cloud/index.ts +14 -3
  316. package/src/sources/gloomberb-cloud/perpetuals.ts +60 -3
  317. package/src/sources/provider-router/financials.ts +20 -13
  318. package/src/sources/provider-router/index.ts +4 -0
  319. package/src/sources/provider-router/search.ts +1 -0
  320. package/src/sync/collections-contributor.ts +3 -1
  321. package/src/sync/config-merge.ts +10 -1
  322. package/src/sync/sanitize.ts +26 -2
  323. package/src/tickers/company-name-listing.ts +16 -2
  324. package/src/tickers/listing-fate.ts +12 -8
  325. package/src/tickers/renamed-listings.ts +43 -10
  326. package/src/tickers/search/home-listing.ts +28 -0
  327. package/src/tickers/search/index.ts +19 -7
  328. package/src/tickers/terminal-codes.ts +11 -1
  329. package/src/time-series/base-series.ts +3 -0
  330. package/src/time-series/ice-credit.ts +1 -0
  331. package/src/time-series/resolve.ts +3 -1
  332. package/src/time-series/spec.ts +2 -2
  333. package/src/time-series/types.ts +2 -1
  334. package/src/types/data-provider.ts +11 -0
  335. package/src/types/financials.ts +39 -3
  336. package/src/types/headless.ts +4 -2
  337. package/src/types/ticker.ts +10 -2
  338. package/src/utils/cli-output.ts +1 -1
  339. package/src/utils/declared-dividends.ts +13 -1
  340. package/src/utils/dividend-cash.ts +5 -1
  341. package/src/utils/forward-dividend.ts +4 -3
  342. package/src/utils/remove-folder.ts +37 -0
  343. package/src/utils/throttled-fetch.ts +15 -1
  344. package/src/utils/trailing-dividend.ts +1 -1
  345. package/src/plugins/builtin/composite-plugins.ts +0 -285
@@ -22,7 +22,7 @@ import {
22
22
  type TickerSearchCandidate,
23
23
  } from "../../tickers/search";
24
24
  import { initMarketData, withMarketData } from "../context";
25
- import { listingChangeLine, loadListingFate, loadNoQuoteEnding, noLongerListedNote, noQuoteLastTradeNote, type NoQuoteEnding } from "../../tickers/listing-fate";
25
+ import { listingChangeLine, loadListingFate, loadNoQuoteEnding, noLongerListedNote, noQuoteLastTradeNote, tradingListing, type NoQuoteEnding } from "../../tickers/listing-fate";
26
26
  import { formatMarketPriceWithCurrency, quoteFormatOptions, withCurrencyMinorDigits } from "../../market-data/market/format";
27
27
  import { formerIssuerLine, startTickerChangeLookup, type TickerChangeLookup } from "../../tickers/ticker-changes";
28
28
  import { fail, failRetryable, failWithError, isCliFailure, unreachableError } from "../errors";
@@ -48,6 +48,7 @@ import { hasNonLatinLetters } from "../../utils/typed-text";
48
48
  import { isKanjiOnlyName, japaneseNameReadAs, readExactJapaneseName, readJapaneseName, type JapaneseNameListing } from "../../tickers/search/japanese-names";
49
49
 
50
50
  interface SearchCommandDependencies {
51
+ limit?: number;
51
52
  initMarketData?: () => Promise<MarketContext>;
52
53
  fail?: (message: string, details?: string) => never;
53
54
  printResult?: CliCommandContext["printResult"];
@@ -128,7 +129,7 @@ export async function searchCandidatesForCli({
128
129
  localLimit,
129
130
  // Every company's listing of a symbol several use (CAR's ASX line is past the first ten), cut after ordering.
130
131
  totalLimit: Math.max(totalLimit, LISTING_SEARCH_LIMIT),
131
- searchContext: { limit: LISTING_SEARCH_LIMIT },
132
+ searchContext: { limit: Math.max(totalLimit, LISTING_SEARCH_LIMIT), perpetuals: "always" },
132
133
  });
133
134
  const symbol = trimmedQuery.toUpperCase();
134
135
  // A bare symbol search lists asks for the quote `quote SYM` reads, once, for its venue and its name:
@@ -139,7 +140,9 @@ export async function searchCandidatesForCli({
139
140
  : null;
140
141
  // A word written as a name (`Aeon`) whose company search leads with keeps it first, as `quote Aeon` reads it.
141
142
  const named = leadsWithNamedCompany(trimmedQuery, candidates, quote);
142
- const ordered = withQuotedNames(symbol, withUsLineOfPrimary(withHomeListingPrimary(trimmedQuery, withPrimaryListingFirst(symbol, candidates, named ? null : quote))), quote);
143
+ const ordered = withLiveCompanyPrimary(symbol,
144
+ withQuotedNames(symbol, withUsLineOfPrimary(withHomeListingPrimary(trimmedQuery, withPrimaryListingFirst(symbol, candidates, named ? null : quote))), quote),
145
+ quote);
143
146
  return cutKeepingCompanies(withOtherCompaniesApart(ordered, named ? trimmedQuery : null), totalLimit, symbol);
144
147
  } catch (error) {
145
148
  // Not "No matches found": a script or a reader would take that for a name nothing lists.
@@ -350,6 +353,26 @@ function withPrimaryListingFirst(
350
353
  ));
351
354
  }
352
355
 
356
+ /**
357
+ * A symbol whose own line stopped trading (DBS, the silver fund delisted in
358
+ * 2023) leads with the company the service marks by it that still trades
359
+ * (DBS Group Holdings' home line, D05 on SGX), as `quote DBS` asks after it;
360
+ * the stopped line is another match. A saved row is the user's choice and
361
+ * stays.
362
+ */
363
+ function withLiveCompanyPrimary(symbol: string, candidates: TickerSearchCandidate[], quote: Quote | null, now = Date.now()): TickerSearchCandidate[] {
364
+ const primary = candidates.find((candidate) => candidate.category === "Primary Listing");
365
+ if (!primary || primary.saved || primary.kind !== "search" || primary.symbol.toUpperCase() !== symbol) return candidates;
366
+ if (!primary.delisted && (!quote || tradingListing(quote, now))) return candidates;
367
+ const marked = (candidate: TickerSearchCandidate) => candidate !== primary && candidate.kind === "search" && !candidate.delisted
368
+ && candidate.symbol.toUpperCase() !== symbol && !!candidate.searchAliases?.some((alias) => alias.toUpperCase() === symbol);
369
+ const live = candidates.find((candidate) => marked(candidate) && candidate.homeListing === true) ?? candidates.find(marked);
370
+ if (!live) return candidates;
371
+ const rest = candidates.filter((candidate) => candidate !== live && candidate !== primary);
372
+ const at = Math.min(candidates.indexOf(primary), rest.length);
373
+ return [...rest.slice(0, at), { ...live, category: "Primary Listing" as const }, ...rest.slice(at), { ...primary, category: "Other Matches" as const }];
374
+ }
375
+
353
376
  /**
354
377
  * One company's lines of a symbol lead with the one the service marks as its
355
378
  * home, never a thin secondary line search ranked first: DHL is DHL Group's
@@ -426,11 +449,10 @@ function withHomeListingPrimary(query: string, candidates: TickerSearchCandidate
426
449
  function withUsLineOfPrimary(candidates: TickerSearchCandidate[]): TickerSearchCandidate[] {
427
450
  const primary = candidates.find((candidate) => candidate.category === "Primary Listing");
428
451
  if (!primary || primary.kind !== "search" || isUsListingExchange(candidateExchange(primary))) return candidates;
429
- const symbol = primary.symbol.toUpperCase();
430
452
  const company = resolveSearchName(primary);
431
453
  const us = candidates.find((candidate) => candidate !== primary && candidate.kind === "search" && !candidate.contractKey
432
- && candidate.category !== "Funds & Derivatives" && candidate.symbol.toUpperCase() === symbol
433
- && isUsListingExchange(candidateExchange(candidate)) && sameCompany(resolveSearchName(candidate), company));
454
+ && candidate.category !== "Funds & Derivatives"
455
+ && isUsListingExchange(candidateExchange(candidate)) && sameCompanyName(resolveSearchName(candidate), company));
434
456
  if (!us) return candidates;
435
457
  const rest = candidates.filter((candidate) => candidate !== us);
436
458
  const at = rest.indexOf(primary) + 1;
@@ -882,6 +904,7 @@ export async function search(query: string, dependencies: SearchCommandDependenc
882
904
  query: index?.symbol ?? trimmedQuery,
883
905
  tickers,
884
906
  dataProvider,
907
+ totalLimit: dependencies.limit,
885
908
  ...quote ? { quote } : {},
886
909
  }).catch((error: unknown) => failTickerLookup(error, trimmedQuery, !dependencies.printResult));
887
910
  // A name in kanji alone is the service's to read first (中電 is CLP in Hong Kong); a Tokyo company's whole name it
@@ -898,6 +921,7 @@ export async function search(query: string, dependencies: SearchCommandDependenc
898
921
  const bank = searchedCentralBank(trimmedQuery);
899
922
  // A query that names no ticker may name what a function does.
900
923
  const functions = await searchedFunctions(trimmedQuery, candidates, fate, dependencies.plugins, context);
924
+ if (!candidates.length && !fate.stopped && !series.length && !functions.length && !bank && !commandPointer(trimmedQuery)) process.exitCode = 1;
901
925
  if (dependencies.printResult) {
902
926
  const warnings = searchNotes(trimmedQuery, candidates, functions, fate);
903
927
  dependencies.printResult({
@@ -9,12 +9,13 @@ import { createAppServices } from "../core/app-services";
9
9
  import type { PluginCapability } from "../capabilities";
10
10
  import type { AppConfig } from "../types/config";
11
11
  import type { GloomPlugin } from "../types/plugin";
12
- import { standaloneSeriesCatalog, standaloneSeriesInvoker, standaloneSeriesNamed } from "../series/standalone";
12
+ import { standaloneSeriesCatalog, standaloneSeriesInvoker, standaloneSeriesNamed, type SeriesPlugins } from "../series/standalone";
13
13
  import { setStandaloneSeriesCatalog } from "../series/standalone-catalog";
14
14
  import type { PluginRegistry } from "../plugins/registry";
15
15
  import type { LoadedExternalPlugin } from "../plugins/loader";
16
16
  import { apiClient } from "../api-client";
17
17
  import { fail } from "./errors";
18
+ import { isKnownUsStock } from "./known-us-stocks";
18
19
  import { resolvePersistedCloudSessionToken } from "./pane-functions/cloud-session";
19
20
  import { cloudStatementReportSources } from "./statement-filings";
20
21
  import type { ConfigContext, MarketContext } from "./types";
@@ -22,7 +23,10 @@ import type { ConfigContext, MarketContext } from "./types";
22
23
  export { withCliServices, withConfigData, withMarketData } from "./scoped-context";
23
24
 
24
25
  interface CliContextOptions {
25
- plugins?: GloomPlugin[];
26
+ /** Every plugin that runs here. Read only once a series is looked up, so a command that never charts one loads none of them. */
27
+ plugins?: SeriesPlugins;
28
+ /** The plugins whose asset-data and news capabilities feed the data provider; every plugin when not given. */
29
+ dataPlugins?: GloomPlugin[];
26
30
  }
27
31
 
28
32
  interface CliServicesOptions {
@@ -41,7 +45,7 @@ export async function ensureCliServicesReady<T extends { ready: Promise<unknown>
41
45
  }
42
46
  }
43
47
 
44
- function resolveCliCapabilities(config: AppConfig, plugins: GloomPlugin[]): PluginCapability[] {
48
+ function resolveCliCapabilities(config: AppConfig, plugins: readonly GloomPlugin[]): PluginCapability[] {
45
49
  const disabledPlugins = new Set(config.disabledPlugins ?? []);
46
50
  const disabledSources = new Set(config.disabledSources ?? []);
47
51
  return plugins
@@ -115,8 +119,15 @@ function applyPersistedCloudSession(context: Pick<MarketContext, "persistence">)
115
119
  export async function initMarketData(options: CliContextOptions = {}): Promise<MarketContext> {
116
120
  const context = await initConfigData();
117
121
  applyPersistedCloudSession(context);
118
- const plugins = options.plugins ?? (require("../plugins/catalog") as typeof import("../plugins/catalog")).getLoadablePlugins();
119
- const capabilities = resolveCliCapabilities(context.config, plugins);
122
+ const plugins: SeriesPlugins = options.plugins ?? (() => (require("../plugins/catalog") as typeof import("../plugins/catalog")).getLoadablePlugins());
123
+ const capabilities = resolveCliCapabilities(context.config, options.dataPlugins ?? (typeof plugins === "function" ? plugins() : plugins));
124
+ // A lookup of a symbol the shipped listings show to be a US stock asks for no perpetual contracts.
125
+ const { GloomberbCloudProvider } = require("../sources/gloomberb-cloud") as typeof import("../sources/gloomberb-cloud");
126
+ for (const capability of capabilities) {
127
+ if (capability.kind === "asset-data" && "provider" in capability && capability.provider instanceof GloomberbCloudProvider) {
128
+ capability.provider.knownUsStock = isKnownUsStock;
129
+ }
130
+ }
120
131
  const dataProvider = new AssetDataRouter(null, [], context.persistence.resources);
121
132
  const registryAdapter: Pick<PluginRegistry, "brokers" | "getEnabledCapabilities"> = {
122
133
  brokers: new Map(),
@@ -0,0 +1,74 @@
1
+ import { cliText } from "../utils/cli-output";
2
+ import { csvDecimal, serializeCsv } from "../utils/csv";
3
+ import { splitCsvFooter } from "./report-tables";
4
+
5
+ function csvRows(text: string, separator: string): string[][] {
6
+ const rows: string[][] = [];
7
+ let row: string[] = [], cell = "", quoted = false;
8
+ for (let index = 0; index < text.length; index++) {
9
+ const character = text[index];
10
+ if (character === '"') {
11
+ if (quoted && text[index + 1] === '"') { cell += '"'; index++; }
12
+ else quoted = !quoted;
13
+ } else if (!quoted && character === separator) {
14
+ row.push(cell); cell = "";
15
+ } else if (!quoted && (character === "\n" || character === "\r")) {
16
+ if (character === "\r" && text[index + 1] === "\n") index++;
17
+ rows.push([...row, cell]); row = []; cell = "";
18
+ } else cell += character;
19
+ }
20
+ if (row.length || cell) rows.push([...row, cell]);
21
+ return rows;
22
+ }
23
+
24
+ export function portableCsv(text: string, warnings: readonly string[] = [], extraNotes: readonly string[] = []): string {
25
+ const decimal = csvDecimal();
26
+ const separator = decimal === "comma" ? ";" : ",";
27
+ const { csv, footer } = splitCsvFooter(text);
28
+ const tables: Array<{ section: string; columns: string[]; rows: string[][] }> = [];
29
+ let section = "", current: (typeof tables)[number] | null = null;
30
+ for (const row of csvRows(csv, separator)) {
31
+ if (row.length === 1 && row[0] === "") { current = null; continue; }
32
+ if (!current && row[0]?.startsWith("# section: ")) {
33
+ section = row.join(separator).slice("# section: ".length); current = null; continue;
34
+ }
35
+ if (!current) {
36
+ current = { section, columns: row.map((name) => name.replace(/\r\n?|\n/g, "\\n")), rows: [] }; tables.push(current);
37
+ } else current.rows.push(row);
38
+ }
39
+ const usedNames = new Set(tables.flatMap((table) => table.columns));
40
+ const variants = new Map<string, string[]>();
41
+ for (const table of tables) {
42
+ const occurrences = new Map<string, number>();
43
+ table.columns = table.columns.map((name) => {
44
+ const occurrence = occurrences.get(name) ?? 0;
45
+ occurrences.set(name, occurrence + 1);
46
+ const names = variants.get(name) ?? [name];
47
+ if (names[occurrence] === undefined) {
48
+ let suffix = occurrence + 1;
49
+ while (usedNames.has(`${name}_${suffix}`)) suffix++;
50
+ names[occurrence] = `${name}_${suffix}`;
51
+ usedNames.add(names[occurrence]!);
52
+ }
53
+ variants.set(name, names);
54
+ return names[occurrence]!;
55
+ });
56
+ }
57
+ const columns = [...new Set(tables.flatMap((table) => table.columns))];
58
+ const tagged = tables.length > 1 || tables.some((table) => table.section);
59
+ let sectionKey = "section", notesKey = "export_notes";
60
+ while (usedNames.has(sectionKey)) sectionKey = `_${sectionKey}`;
61
+ while (usedNames.has(notesKey)) notesKey = `_${notesKey}`;
62
+ const notes = [...new Set([...footer, ...extraNotes.flatMap((note) => note.split(/\r\n?|\n/).filter(Boolean).map((line) => `note: ${line}`)), ...warnings.map((warning) => `warning: ${warning}`)].map((note) => cliText(note.replace(/\r\n?|\n/g, " | "))))].join(" | ");
63
+ const header = [...columns, ...tagged ? [sectionKey] : [], notesKey];
64
+ const rows = tables.flatMap((table) => {
65
+ const indices = columns.map((column) => table.columns.indexOf(column));
66
+ return table.rows.map((row) => [...indices.map((index) => index < 0 ? "" : row[index] ?? ""), ...tagged ? [table.section] : [], notes]);
67
+ });
68
+ if (!rows.length && notes) rows.push([...header.slice(0, -1).map(() => ""), notes]);
69
+ const records = [header, ...rows];
70
+ const normalized = decimal === "comma"
71
+ ? records.map((row) => row.map((cell) => /^[+-]?(?:\d+(?:,\d+)?|,\d+)(?:e[+-]?\d+)?%?$/i.test(cell) ? cell.replace(",", ".") : cell))
72
+ : records;
73
+ return serializeCsv(normalized);
74
+ }
@@ -122,11 +122,16 @@ export interface DesktopPaneShotApiProxy {
122
122
  */
123
123
  export interface DesktopPaneShotBridge {
124
124
  marketData(operation: string, args: unknown[]): Promise<unknown>;
125
- httpFetch(request: HttpProxyRequestEnvelope): Promise<HttpProxyResponseEnvelope>;
125
+ /** `signal` ends the read when the page gives up on it (its own deadline), so it holds nothing past that. */
126
+ httpFetch(request: HttpProxyRequestEnvelope, signal?: AbortSignal): Promise<HttpProxyResponseEnvelope>;
126
127
  }
127
128
 
128
129
  interface DesktopPaneShotRenderedCell {
129
- /** The column can be blank in every row with nothing missing (DataTableColumn.mayBeBlank). */
130
+ /**
131
+ * The cell can be blank with nothing missing: its whole column can
132
+ * (DataTableColumn.mayBeBlank), or its row is still waiting on the value
133
+ * (DataTableCell.mayBeBlank).
134
+ */
130
135
  mayBeBlank?: true;
131
136
  columnId?: string;
132
137
  columnLabel: string;
@@ -220,6 +225,7 @@ export interface DesktopPaneShotRenderResult {
220
225
  semanticUi: RemoteUiNodeSnapshot[];
221
226
  /** The status line drawn in the capture's footer, as it fit the width. */
222
227
  statusLine?: string | null;
228
+ statusLineClipped?: boolean;
223
229
  }
224
230
 
225
231
  /**
@@ -232,9 +238,17 @@ export interface DesktopPaneShotRenderResult {
232
238
  interface ShotStatusLineVariants {
233
239
  variants: readonly string[];
234
240
  dates?: "data" | "quotes" | null;
241
+ dateEvidence?: readonly (readonly string[])[];
235
242
  }
236
243
  type ShotStatusLine = (rendered: DesktopPaneShotRenderResult) => ShotStatusLineVariants | null | Promise<ShotStatusLineVariants | null>;
237
244
 
245
+ export function shotStatusDateClipped(line: ShotStatusLineVariants | null, statusText: string | null): boolean {
246
+ if (line?.dates == null || line.variants.includes(statusText ?? "")) return false;
247
+ const normalize = (text: string) => text.toLowerCase().replace(/\s+/g, " ").trim();
248
+ const shown = normalize(statusText ?? "");
249
+ return !line.dateEvidence?.some((parts) => parts.length > 0 && parts.every((part) => shown.includes(normalize(part))));
250
+ }
251
+
238
252
  const SHOT_MODE_CSS = [
239
253
  "[data-gloom-role='composite-chart-toolbar']",
240
254
  "[data-gloom-role='chart-series-quick-add']",
@@ -494,7 +508,7 @@ async function runShotHttpBridge(
494
508
  if (!bridge) return Response.json({ ok: false, error: "No HTTP bridge" }, { status: 404 });
495
509
  try {
496
510
  const payload = await request.json() as HttpProxyRequestEnvelope;
497
- const data = await bridge.httpFetch(payload);
511
+ const data = await bridge.httpFetch(payload, request.signal);
498
512
  return Response.json({ ok: true, data });
499
513
  } catch (error) {
500
514
  return Response.json({ ok: false, error: errorMessage(error) });
@@ -665,10 +679,14 @@ async function capturePageScreenshot({
665
679
  await waitForShotReady(session);
666
680
  if (fitRows) await growToFitRows(session, { widthPx, heightPx, deviceScaleFactor, ...fitRows });
667
681
  if (captureImage) await hideCutRows(session);
668
- const rendered = await readRenderedPaneState(session);
682
+ let rendered = await readRenderedPaneState(session);
669
683
  if (captureImage && statusLine) {
670
684
  const line = await statusLine(rendered);
671
- rendered.statusLine = (await fitShotStatusLine(session, line ?? { variants: [] })) || null;
685
+ const statusText = (await fitShotStatusLine(session, line ?? { variants: [] })) || null;
686
+ await hideCutRows(session);
687
+ rendered = await readRenderedPaneState(session);
688
+ rendered.statusLine = statusText;
689
+ rendered.statusLineClipped = shotStatusDateClipped(line, statusText);
672
690
  }
673
691
  if (captureImage) {
674
692
  const screenshot = await session.send("Page.captureScreenshot", {
@@ -815,6 +833,32 @@ const EMPTY_STATE_PATTERNS = [
815
833
  /\bNo (?:option contracts returned for )?expiry \d{4}-\d{2}-\d{2}(?:; (?:available|nearest others): \d{4}-\d{2}-\d{2}(?:, \d{4}-\d{2}-\d{2})*(?: \(\+\d+ more\))?|; the chain lists no expiries)?/gi,
816
834
  ];
817
835
 
836
+ /**
837
+ * The text a capture reads the pane's state from: what it shows, less its
838
+ * footer's note line. A note says what the data shown leaves out ("Grossing
839
+ * and genre ranks are unavailable."), never that the pane failed: a full
840
+ * table under it is a usable pane, and an empty state under it is that state.
841
+ * Both texts come whitespace-collapsed, as the page reads them.
842
+ */
843
+ function paneStateText(visibleText: string, footerNotes: readonly string[]): string {
844
+ return footerNotes.reduce((text, note) => {
845
+ const at = note ? text.lastIndexOf(note) : -1;
846
+ return at < 0 ? text : `${text.slice(0, at)} ${text.slice(at + note.length)}`;
847
+ }, visibleText).replace(/\s+/g, " ").trim();
848
+ }
849
+
850
+ /** The words that mark a capture's loading, error, empty and gated states, read from its text less its note line (paneStateText). */
851
+ export function paneStateMarkers(visibleText: string, footerNotes: readonly string[] = []) {
852
+ const text = paneStateText(visibleText, footerNotes);
853
+ return {
854
+ loading: stateMarkers(text, LOADING_STATE_PATTERNS),
855
+ error: stateMarkers(text, ERROR_STATE_PATTERNS),
856
+ empty: stateMarkers(text, EMPTY_STATE_PATTERNS),
857
+ signIn: stateMarkers(text, SIGN_IN_WALL_PATTERNS).length > 0,
858
+ pro: stateMarkers(text, PRO_WALL_PATTERNS).length > 0,
859
+ };
860
+ }
861
+
818
862
  function stateMarkers(text: string, patterns: RegExp[]): string[] {
819
863
  return [...new Set(patterns.flatMap((pattern) => (
820
864
  [...text.matchAll(pattern)].map((match) => match[0])
@@ -837,6 +881,20 @@ async function readRenderedPaneState(session: CdpPage): Promise<DesktopPaneShotR
837
881
  && rect.left < window.innerWidth && rect.top < window.innerHeight;
838
882
  };
839
883
  const semanticTables = semanticUi.filter((node) => node && node.role === "table");
884
+ const clippedFigures = [...root.querySelectorAll('[data-gloom-essential="true"]')].flatMap((cell) => {
885
+ const bounds = cell.getBoundingClientRect();
886
+ const parts = [...cell.querySelectorAll('[data-gloom-role="stat-grid-label"], [data-gloom-role="stat-grid-value"]')];
887
+ const clipped = !isVisible(cell) || parts.some((part) => {
888
+ const rect = part.getBoundingClientRect();
889
+ return !isVisible(part) || part.scrollWidth > part.clientWidth + 1
890
+ || rect.left < bounds.left - 1 || rect.right > bounds.right + 1
891
+ || rect.top < bounds.top - 1 || rect.bottom > bounds.bottom + 1;
892
+ });
893
+ return clipped ? [cell.querySelector('[data-gloom-role="stat-grid-label"]')?.textContent?.trim()].filter(Boolean) : [];
894
+ });
895
+ for (const node of semanticUi.filter((node) => node.role === "figure-layout" && node.metadata)) {
896
+ node.metadata.omitted = [...(node.metadata.omitted ?? []), ...clippedFigures];
897
+ }
840
898
  const rows = [];
841
899
  const truncationReasons = new Set();
842
900
  const scrollReasons = (${scrollTruncationReasons.toString()});
@@ -921,7 +979,7 @@ async function readRenderedPaneState(session: CdpPage): Promise<DesktopPaneShotR
921
979
  const exact = Number(cell.getAttribute("data-gloom-cell-value") || "NaN");
922
980
  return {
923
981
  ...(typeof semanticColumn.id === "string" ? { columnId: semanticColumn.id } : {}),
924
- ...(semanticColumn.mayBeBlank === true ? { mayBeBlank: true } : {}),
982
+ ...(semanticColumn.mayBeBlank === true || cell.getAttribute("data-gloom-cell-may-be-blank") === "true" ? { mayBeBlank: true } : {}),
925
983
  columnLabel: typeof semanticColumn.label === "string"
926
984
  ? semanticColumn.label
927
985
  : headers[cellIndex] || (values.length === 1 ? "Row" : String(cellIndex + 1)),
@@ -978,6 +1036,9 @@ async function readRenderedPaneState(session: CdpPage): Promise<DesktopPaneShotR
978
1036
  .map((footer) => normalize(footer.innerText || footer.textContent))
979
1037
  .filter(Boolean)
980
1038
  .join(" "),
1039
+ footerNotes: [...root.querySelectorAll('[data-gloom-role="pane-footer-notes"]')]
1040
+ .map((note) => normalize(note.innerText || note.textContent))
1041
+ .filter(Boolean),
981
1042
  visibleKeyValues: (${readVisibleKeyValues.toString()})(root),
982
1043
  surfaces: [...root.querySelectorAll('[data-gloom-surface-renderer]')].filter(isVisible).map((element) => ({
983
1044
  renderer: element.getAttribute("data-gloom-surface-renderer") || "",
@@ -1048,6 +1109,7 @@ async function readRenderedPaneState(session: CdpPage): Promise<DesktopPaneShotR
1048
1109
  value?: {
1049
1110
  visibleText?: string;
1050
1111
  footerText?: string;
1112
+ footerNotes?: unknown;
1051
1113
  visibleKeyValues?: Array<{ label: string; text: string }>;
1052
1114
  surfaces?: DesktopPaneShotSurface[];
1053
1115
  error?: string;
@@ -1072,11 +1134,13 @@ async function readRenderedPaneState(session: CdpPage): Promise<DesktopPaneShotR
1072
1134
  const value = result.result?.value;
1073
1135
  if (value?.error) throw new Error(value.error);
1074
1136
  const visibleText = (value?.visibleText ?? "").replace(/\s+/g, " ").trim();
1075
- const loadingStateMarkers = stateMarkers(visibleText, LOADING_STATE_PATTERNS);
1076
- const errorStateMarkers = stateMarkers(visibleText, ERROR_STATE_PATTERNS);
1077
- const emptyStateMarkers = stateMarkers(visibleText, EMPTY_STATE_PATTERNS);
1078
- const accessGate: PaneAccessGate | null = value?.accessGate === "sign-in" || stateMarkers(visibleText, SIGN_IN_WALL_PATTERNS).length > 0 ? "sign-in"
1079
- : value?.accessGate === "pro" || stateMarkers(visibleText, PRO_WALL_PATTERNS).length > 0 ? "pro" : null;
1137
+ const footerNotes = Array.isArray(value?.footerNotes) ? value.footerNotes.filter((note): note is string => typeof note === "string") : [];
1138
+ const markers = paneStateMarkers(visibleText, footerNotes);
1139
+ const loadingStateMarkers = markers.loading;
1140
+ const errorStateMarkers = markers.error;
1141
+ const emptyStateMarkers = markers.empty;
1142
+ const accessGate: PaneAccessGate | null = value?.accessGate === "sign-in" || markers.signIn ? "sign-in"
1143
+ : value?.accessGate === "pro" || markers.pro ? "pro" : null;
1080
1144
  const rows = Array.isArray(value?.rows) ? value.rows : [];
1081
1145
  const textShowsEllipsis = rows.some((row) => row.cells.some((cell) => /\u2026|\.\.\./.test(cell.text)));
1082
1146
  const truncationReasons = Array.isArray(value?.truncationReasons)
@@ -14,6 +14,12 @@ export interface GlossaryEntry {
14
14
  short?: string;
15
15
  /** Other names a reader may look it up by: `stop-out` for the high yield. */
16
16
  aliases: readonly string[];
17
+ /**
18
+ * Other names for what the functions that show it cover, which find those
19
+ * functions as the term and its abbreviation do (`expected shortfall` for
20
+ * MARS and PORT); the aliases only look the term up. Looked up as aliases are.
21
+ */
22
+ finds?: readonly string[];
17
23
  /** The functions that show it, by the token `fn` takes. */
18
24
  functions: readonly string[];
19
25
  /**
@@ -454,26 +460,42 @@ export const GLOSSARY: readonly GlossaryEntry[] = [
454
460
  definition: "The plain difference between two percentages. A 22% weight against a 20% target is 2pp over it, not 10%, "
455
461
  + "and gas storage going from 74.31% to 74.46% full is up 0.15pp.",
456
462
  },
457
- // Portfolio risk (PORT): the factor table's betas and fits, the tail loss, concentration.
463
+ // Portfolio risk (PORT, and MARS, which opens it on its risk view): the factor table's betas and fits, the tail loss,
464
+ // the drawdown, the stress scenarios, concentration.
458
465
  {
459
- term: "Beta", aliases: ["betas", "factor beta", "market beta", "beta to spy", "exposure", "factor exposure"], functions: ["PORT"],
466
+ term: "Beta", aliases: ["betas", "factor beta", "market beta", "beta to spy", "exposure", "factor exposure"], functions: ["PORT", "MARS"],
460
467
  shown: ["beta", "Beta"],
461
468
  definition: "How far a basket moves with a factor: a beta of 0.54 to SPY means it rose 0.54% on average for each 1% SPY rose. "
462
469
  + "PORT estimates it from the last 60 daily returns; read it with its R², since a beta from a weak fit says little about an exposure.",
463
470
  },
464
471
  {
465
- term: "R²", aliases: ["r-squared", "r squared", "r2", "coefficient of determination", "goodness of fit", "weak fit"], functions: ["PORT"],
472
+ term: "R²", aliases: ["r-squared", "r squared", "r2", "coefficient of determination", "goodness of fit", "weak fit"], functions: ["PORT", "MARS"],
466
473
  definition: "R-squared: the share of a basket's daily moves a factor explains, from 0 (none) to 1 (all), over the same 60 sessions as its beta. "
467
474
  + "Under 0.1 PORT marks the factor a weak fit: the beta beside it is mostly noise, not an exposure.",
468
475
  },
469
476
  {
470
- term: "Value at risk", short: "VaR", aliases: ["value-at-risk", "var 95%", "1d var", "historical var", "expected shortfall", "cvar", "tail loss"],
471
- functions: ["PORT"], shown: ["VaR", "expected shortfall"],
477
+ term: "Value at risk", short: "VaR", aliases: ["var 95%", "1d var", "historical var", "tail loss"],
478
+ finds: ["value-at-risk", "expected shortfall", "cvar", "conditional var"],
479
+ functions: ["PORT", "MARS"], shown: ["VaR", "expected shortfall"],
472
480
  definition: "The loss a basket went beyond on only 5% of its last 60 trading days, as a share of its value and in money: a 1-day VaR 95% of 1.19% means "
473
481
  + "about one day in twenty lost more than that. Expected shortfall is the average loss on those worst days. Both read the past, not a limit on the next loss.",
474
482
  },
475
483
  {
476
- term: "HHI", aliases: ["herfindahl", "herfindahl index", "herfindahl-hirschman index", "concentration index", "effective holdings"], functions: ["PORT"],
484
+ term: "Max drawdown", aliases: ["drawdowns", "mdd", "peak to trough", "peak-to-trough decline"], finds: ["drawdown", "maximum drawdown"],
485
+ functions: ["PORT", "MARS"], shown: ["max drawdown"],
486
+ definition: "The largest fall from a high to a later low over the window, as a share of the high: a 60D max drawdown of -7.2% is the basket's "
487
+ + "worst drop from any of its last 60 closes to a later one.",
488
+ },
489
+ {
490
+ term: "Stress test", aliases: ["stress", "scenario", "scenarios", "shock", "shocks", "what if", "historical scenarios", "crash replay"],
491
+ finds: ["stress tests", "stress testing", "scenario analysis"],
492
+ functions: ["PORT", "MARS"], shown: ["stress", "Stress"],
493
+ definition: "What the book would move by in a given shock: an index fall, a 10Y yield rise or a VIX jump read through the basket's past moves "
494
+ + "with each, a currency or holding move repricing the lines it touches, and four past selloffs replayed on today's holdings at today's weights. "
495
+ + "A measure of exposure, not a forecast.",
496
+ },
497
+ {
498
+ term: "HHI", aliases: ["herfindahl", "herfindahl index", "herfindahl-hirschman index", "concentration index", "effective holdings"], functions: ["PORT", "MARS"],
477
499
  definition: "Herfindahl-Hirschman index: each holding's weight squared and added up, from near 0 for a book spread thin to 1 for a single holding. "
478
500
  + "One over it is the effective number of holdings: 0.20 reads as a book of five equal positions.",
479
501
  },
@@ -508,9 +530,10 @@ export const GLOSSARY: readonly GlossaryEntry[] = [
508
530
  + "It is usually a fraction of a percent, and widens when the fund's holdings are hard to trade or their market is shut.",
509
531
  },
510
532
  {
511
- term: "Tracking error", aliases: ["index tracking error"], functions: ["ETF"], shown: ["Tracking error", "tracking error"],
533
+ term: "Tracking error", aliases: ["index tracking error", "active risk"], functions: ["ETF", "PORT", "MARS"],
534
+ shown: ["Tracking error", "tracking error"],
512
535
  definition: "How loosely a fund follows its index: how much the gap between the fund's return and the index's swings, usually over a year. "
513
- + "Fees, cash and holdings that differ from the index widen it.",
536
+ + "Fees, cash and holdings that differ from the index widen it. PORT measures a basket's against SPY from 60 daily returns, annualized.",
514
537
  },
515
538
  {
516
539
  term: "Leveraged and inverse ETFs", aliases: ["leveraged", "inverse", "decay", "daily reset", "3x", "2x", "-1x", "-3x",
@@ -1057,7 +1080,38 @@ function words(text: string): string[] {
1057
1080
  }
1058
1081
 
1059
1082
  function names(entry: GlossaryEntry): string[] {
1060
- return [entry.term, ...(entry.short ? [entry.short] : []), ...entry.aliases];
1083
+ return [entry.term, ...(entry.short ? [entry.short] : []), ...entry.finds ?? [], ...entry.aliases];
1084
+ }
1085
+
1086
+ /** The names that find the functions showing a term: the term, its abbreviation and its `finds`, never a loose alias. */
1087
+ function findingNames(entry: GlossaryEntry): string[] {
1088
+ return [entry.term, ...(entry.short ? [entry.short] : []), ...entry.finds ?? []];
1089
+ }
1090
+
1091
+ let keysByFunction: ReadonlyMap<string, ReadonlySet<string>> | null = null;
1092
+
1093
+ /**
1094
+ * Whether a query is, whole, the name of a term a function shows (its term,
1095
+ * abbreviation or `finds`, in any case and punctuation), by the function's
1096
+ * code: `VaR`, `value at risk` and `expected shortfall` name MARS and PORT
1097
+ * in `catalog`, `fn`'s hint and the command bar. A word of a longer query, or
1098
+ * a loose alias (`close`, `exposure`), names nothing, so common searches list
1099
+ * what they did.
1100
+ */
1101
+ export function glossaryNamesFunction(code: string, query: string): boolean {
1102
+ keysByFunction ??= GLOSSARY.reduce((map, entry) => {
1103
+ for (const fn of entry.functions) map.set(fn, new Set([...map.get(fn) ?? [], ...findingNames(entry).map(lookupKey)]));
1104
+ return map;
1105
+ }, new Map<string, Set<string>>());
1106
+ const key = lookupKey(query);
1107
+ return !!key && !!keysByFunction.get(code.toUpperCase())?.has(key);
1108
+ }
1109
+
1110
+ /** The functions that show the term a query names whole (`VaR`, `value-at-risk`: PORT and MARS), in glossary order. */
1111
+ export function glossaryFunctionsNamed(query: string): string[] {
1112
+ const key = lookupKey(query);
1113
+ if (!key) return [];
1114
+ return [...new Set(GLOSSARY.filter((entry) => findingNames(entry).some((name) => lookupKey(name) === key)).flatMap((entry) => entry.functions))];
1061
1115
  }
1062
1116
 
1063
1117
  export interface GlossaryLookup {
@@ -1181,7 +1235,7 @@ export function glossaryRecord(entry: GlossaryEntry): Record<string, unknown> {
1181
1235
  return {
1182
1236
  term: entry.term,
1183
1237
  ...(entry.short ? { short: entry.short } : {}),
1184
- aliases: entry.aliases,
1238
+ aliases: [...entry.finds ?? [], ...entry.aliases],
1185
1239
  functions: entry.functions,
1186
1240
  definition: entry.definition,
1187
1241
  };
package/src/cli/help.ts CHANGED
@@ -45,11 +45,11 @@ const START_HERE: Array<[string, string]> = [
45
45
 
46
46
  const GLOBAL_OPTIONS: Array<[string, string]> = [
47
47
  ["--json", "Print the full result as JSON"],
48
- ["--csv", "Print rows as CSV under the columns the text shows; each row ends with what it is, its source, as_of and retrieved_at (when it was read), then any columns a report adds (a formula's leg contracts, a board's Group), and fn reports and fundamentals put each table under # section:. The closing source and note lines go to stderr, not into the rows or an --output file"],
48
+ ["--csv", "Print one rectangular CSV with a single header, readable by pandas.read_csv with no options. Existing columns stay in order; duplicate headers gain unique numeric suffixes, and extra tables add columns and a section column. Header line breaks are escaped as \\n; data cells preserve quoted newlines. The final export_notes column stays single-line and repeats source details, caveats, warnings and truncation notes joined with |, including in files and pipes"],
49
49
  ["--ndjson", "Print one JSON object per table row"],
50
50
  ["--output <path>, --out <path>", "Write a --csv, --json or --ndjson export to this file in UTF-8, and print where it went (a redirect is UTF-16 in Windows PowerShell 5.1)"],
51
51
  ["--decimal comma|dot", "Write a --csv export's numbers with a decimal comma (17,2), cells split by ;, for a spreadsheet in a decimal-comma locale; or a dot. gloom config set csvDecimal comma makes the comma the default. Text and JSON keep the dot"],
52
- ["--limit <n>", "Show at most n rows, the first n as printed"],
52
+ ["--limit <n>", "For row/table reports, keep the first n rows in printed order, not the newest n (use --tail). Applies to text, JSON, CSV and NDJSON, not shot or scalar results. Pane reports may set a per-table limit or a source cap; see help fn <function>. It does not request all available source rows"],
53
53
  ["--tail <n>", "Show the newest n rows of a dated series (history, fred, econ) in their printed order, or the last n of another list"],
54
54
  ["--refresh", "Fetch fresh data instead of reading the cache"],
55
55
  ["--dry-run", "Preview config, cache, notes, alerts, plugin on/off, and remote changes without saving"],
@@ -173,6 +173,8 @@ export function renderCommandHelp(command: CliCommandDef): string {
173
173
  { width, termStyle: cliStyles.command },
174
174
  ));
175
175
  }
176
+ lines.push("", renderSection("Output And Row Limits"));
177
+ lines.push(...renderDefinitions(GLOBAL_OPTIONS.filter(([flag]) => ["--csv", "--limit <n>", "--tail <n>"].includes(flag)), { width, termStyle: cliStyles.command }));
176
178
 
177
179
  for (const section of help.sections ?? []) {
178
180
  lines.push("", renderSection(section.title));