gloomberb 0.20.4 → 0.20.6

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 (316) hide show
  1. package/README.md +3 -1
  2. package/README.zh-CN.md +1 -1
  3. package/bin/gloom +9 -0
  4. package/bin/without-bun.cjs +98 -0
  5. package/package.json +4 -1
  6. package/src/api-client/data.ts +148 -37
  7. package/src/api-client/hk-tenders.ts +59 -0
  8. package/src/api-client/index.ts +1 -0
  9. package/src/api-client/types/econ.ts +30 -0
  10. package/src/api-client/yield-curves.ts +1 -1
  11. package/src/app/global-shortcuts.ts +4 -1
  12. package/src/app/keybindings/actions.ts +6 -0
  13. package/src/app/keybindings/config.ts +2 -1
  14. package/src/app/keybindings/index.ts +1 -0
  15. package/src/app/keybindings/labels.ts +6 -1
  16. package/src/app/keybindings/resolve.ts +23 -4
  17. package/src/app/keybindings/terminal-keys.ts +35 -0
  18. package/src/app/pane-runtime/index.tsx +2 -2
  19. package/src/app/pane-runtime/ticker-open-runtime.ts +68 -40
  20. package/src/app.tsx +18 -13
  21. package/src/architecture/floating-promise-allowlist.json +313 -0
  22. package/src/architecture/ui-literals-allowlist.json +1 -1
  23. package/src/capabilities/chart-series.ts +27 -1
  24. package/src/cli/commands/keybindings.ts +5 -5
  25. package/src/cli/commands/market.ts +238 -57
  26. package/src/cli/commands/news-search.ts +81 -14
  27. package/src/cli/commands/overview.ts +27 -6
  28. package/src/cli/commands/remote.ts +16 -17
  29. package/src/cli/commands/system.ts +1 -1
  30. package/src/cli/commands/ticker.ts +3 -1
  31. package/src/cli/early-command.ts +2 -0
  32. package/src/cli/errors.ts +10 -1
  33. package/src/cli/fx-forward.ts +89 -7
  34. package/src/cli/fx-pair.ts +1 -1
  35. package/src/cli/fx-quote-rate.ts +23 -0
  36. package/src/cli/glossary.ts +19 -5
  37. package/src/cli/help.ts +1 -0
  38. package/src/cli/history-rows.ts +5 -3
  39. package/src/cli/index-roots.ts +5 -4
  40. package/src/cli/index.ts +40 -3
  41. package/src/cli/known-gaps.ts +38 -9
  42. package/src/cli/listing-arg.ts +17 -5
  43. package/src/cli/name-entries.ts +5 -1
  44. package/src/cli/not-a-ticker.ts +4 -0
  45. package/src/cli/options.ts +52 -3
  46. package/src/cli/output-file.ts +5 -3
  47. package/src/cli/pane-functions/catalog.ts +15 -0
  48. package/src/cli/pane-functions/function-help.ts +4 -4
  49. package/src/cli/pane-functions/headless.ts +9 -4
  50. package/src/cli/pane-functions/index.ts +6 -4
  51. package/src/cli/pane-functions/resolver.ts +2 -2
  52. package/src/cli/result.ts +21 -2
  53. package/src/cli/spreadsheet-hint.ts +7 -3
  54. package/src/cli/treasury-yields.ts +5 -3
  55. package/src/components/chart/composite/legend.tsx +40 -2
  56. package/src/components/command-bar/pane-settings.ts +2 -2
  57. package/src/components/command-bar/routes/root/results.ts +6 -2
  58. package/src/components/command-bar/workflow/tickers.ts +2 -2
  59. package/src/components/data-table/view.tsx +9 -2
  60. package/src/components/input-search-bar.tsx +9 -2
  61. package/src/components/layout/pane/header.tsx +2 -0
  62. package/src/components/layout/shell/pane/capture.ts +4 -1
  63. package/src/components/layout/status-bar.tsx +6 -1
  64. package/src/components/onboarding/first-run-workspace.ts +44 -2
  65. package/src/components/onboarding/onboarding-frame.tsx +11 -2
  66. package/src/components/onboarding/onboarding-keyboard.ts +16 -0
  67. package/src/components/onboarding/onboarding-wizard.tsx +8 -8
  68. package/src/components/onboarding/portfolio-step/positions-panel.tsx +62 -1
  69. package/src/components/onboarding/use-onboarding-progress.ts +12 -4
  70. package/src/components/pane-settings-dialog/desktop.tsx +2 -2
  71. package/src/components/pane-settings-dialog/tui.tsx +2 -2
  72. package/src/components/pane-settings-dialog/value.ts +6 -0
  73. package/src/components/pane-settings-dialog.tsx +3 -3
  74. package/src/components/reader/detail-reader.tsx +4 -0
  75. package/src/components/ui/data-table/opentui/index.tsx +11 -4
  76. package/src/components/ui/data-table/opentui/model.ts +8 -6
  77. package/src/components/ui/data-table/types.ts +6 -1
  78. package/src/components/ui/index.ts +1 -1
  79. package/src/components/ui/page-stack-view.tsx +3 -0
  80. package/src/components/ui/pane-link-chip.tsx +269 -54
  81. package/src/components/ui/query-bar.tsx +2 -1
  82. package/src/components/ui/table-layout.ts +38 -1
  83. package/src/components/ui/tabs.tsx +97 -19
  84. package/src/core/state/app/layout-reducer.ts +7 -0
  85. package/src/core/state/app/layout.ts +44 -7
  86. package/src/core/state/app/state.ts +1 -1
  87. package/src/core/state/app/types.ts +22 -2
  88. package/src/docs/snapshot.json +30 -13
  89. package/src/market-data/depositary-pair.ts +5 -3
  90. package/src/market-data/market/change-basis.ts +9 -5
  91. package/src/market-data/market/dated-previous-close.ts +147 -17
  92. package/src/market-data/market/status.ts +17 -1
  93. package/src/market-data/quotes/contributions.ts +2 -0
  94. package/src/market-data/quotes/listing-enterprise-value.ts +50 -0
  95. package/src/plugins/builtin/alerts/metric-data.ts +15 -2
  96. package/src/plugins/builtin/analytics/risk-client.ts +10 -4
  97. package/src/plugins/builtin/analytics/risk-episodes.ts +5 -4
  98. package/src/plugins/builtin/analytics/risk-headless.ts +4 -2
  99. package/src/plugins/builtin/analytics/risk-sectors.ts +91 -0
  100. package/src/plugins/builtin/awards/index.tsx +1 -1
  101. package/src/plugins/builtin/backtest/headless.ts +1 -1
  102. package/src/plugins/builtin/buildout/index.tsx +1 -0
  103. package/src/plugins/builtin/catalysts/index.tsx +2 -2
  104. package/src/plugins/builtin/cds/headless.ts +4 -0
  105. package/src/plugins/builtin/cds/model.ts +0 -6
  106. package/src/plugins/builtin/chart-composer/formula.ts +16 -3
  107. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -0
  108. package/src/plugins/builtin/chart-composer/headless.ts +4 -2
  109. package/src/plugins/builtin/chart-composer/index.tsx +1 -0
  110. package/src/plugins/builtin/chart-composer/presets.ts +1 -0
  111. package/src/plugins/builtin/chat/content/composer.tsx +5 -4
  112. package/src/plugins/builtin/chat/content/index.tsx +12 -2
  113. package/src/plugins/builtin/chat/content/layout-metrics.ts +3 -3
  114. package/src/plugins/builtin/chat/content/open-targets.ts +3 -3
  115. package/src/plugins/builtin/chat/layout.ts +5 -2
  116. package/src/plugins/builtin/chat/message/pane-chip.tsx +61 -40
  117. package/src/plugins/builtin/chat/message/terminal.tsx +13 -15
  118. package/src/plugins/builtin/chat/pane-links/previews.ts +51 -5
  119. package/src/plugins/builtin/chat/pane-links/share-card.ts +36 -0
  120. package/src/plugins/builtin/cloud/askg/pane.tsx +55 -13
  121. package/src/plugins/builtin/cloud/askg/tool-display.ts +1 -0
  122. package/src/plugins/builtin/cloud/terminal-relay/redact.ts +5 -3
  123. package/src/plugins/builtin/commodity-balances/index.tsx +1 -0
  124. package/src/plugins/builtin/company-attention/index.tsx +1 -1
  125. package/src/plugins/builtin/company-kpis/headless.ts +3 -1
  126. package/src/plugins/builtin/company-kpis/index.tsx +2 -2
  127. package/src/plugins/builtin/cot/index.tsx +1 -1
  128. package/src/plugins/builtin/cpi/index.tsx +1 -1
  129. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +20 -7
  130. package/src/plugins/builtin/credit-boards/client.ts +8 -0
  131. package/src/plugins/builtin/credit-boards/headless.ts +4 -1
  132. package/src/plugins/builtin/credit-boards/model.ts +58 -4
  133. package/src/plugins/builtin/credit-boards/series.ts +63 -6
  134. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +3 -2
  135. package/src/plugins/builtin/credit-conditions/headless.ts +24 -6
  136. package/src/plugins/builtin/credit-conditions/index.tsx +1 -1
  137. package/src/plugins/builtin/credit-conditions/model.ts +12 -6
  138. package/src/plugins/builtin/credit-conditions/series.ts +2 -1
  139. package/src/plugins/builtin/crypto-board/index.tsx +1 -0
  140. package/src/plugins/builtin/dividend-yield/index.tsx +1 -0
  141. package/src/plugins/builtin/doe/index.tsx +1 -1
  142. package/src/plugins/builtin/earnings-calls/headless.ts +5 -1
  143. package/src/plugins/builtin/earnings-calls/index.tsx +1 -0
  144. package/src/plugins/builtin/econ/calendar-model.ts +115 -8
  145. package/src/plugins/builtin/econ/calendar-source.ts +7 -1
  146. package/src/plugins/builtin/econ/fred-catalog.ts +3 -1
  147. package/src/plugins/builtin/econ/index.tsx +42 -8
  148. package/src/plugins/builtin/econ/types.ts +3 -0
  149. package/src/plugins/builtin/econ-statistics/index.tsx +1 -0
  150. package/src/plugins/builtin/econ-statistics/pane.tsx +6 -0
  151. package/src/plugins/builtin/estimate-revisions/index.tsx +1 -0
  152. package/src/plugins/builtin/executives/index.tsx +1 -0
  153. package/src/plugins/builtin/filing-events/index.tsx +1 -0
  154. package/src/plugins/builtin/fixed-income/index.tsx +3 -0
  155. package/src/plugins/builtin/futures-curve/headless.ts +3 -3
  156. package/src/plugins/builtin/futures-curve/index.tsx +1 -1
  157. package/src/plugins/builtin/futures-curve/model.ts +18 -0
  158. package/src/plugins/builtin/fx-matrix/index.tsx +44 -14
  159. package/src/plugins/builtin/gpu/index.tsx +1 -1
  160. package/src/plugins/builtin/help/functions-table.tsx +1 -1
  161. package/src/plugins/builtin/help/index.tsx +11 -1
  162. package/src/plugins/builtin/help/keybindings-editor.tsx +7 -3
  163. package/src/plugins/builtin/holders/index.tsx +1 -0
  164. package/src/plugins/builtin/holders/report-header.ts +2 -2
  165. package/src/plugins/builtin/insider/index.tsx +1 -0
  166. package/src/plugins/builtin/iv-history/index.tsx +1 -1
  167. package/src/plugins/builtin/jobs/index.tsx +1 -0
  168. package/src/plugins/builtin/macro-day/headless.ts +27 -8
  169. package/src/plugins/builtin/macro-day/index.tsx +1 -1
  170. package/src/plugins/builtin/macro-day/model.ts +19 -3
  171. package/src/plugins/builtin/macro-day/pane.tsx +14 -9
  172. package/src/plugins/builtin/macro-day/releases.ts +25 -7
  173. package/src/plugins/builtin/market-valuation/index.tsx +1 -0
  174. package/src/plugins/builtin/market-valuation/pane.tsx +8 -0
  175. package/src/plugins/builtin/members/index.tsx +1 -1
  176. package/src/plugins/builtin/mna/index.tsx +1 -0
  177. package/src/plugins/builtin/news/index.tsx +1 -0
  178. package/src/plugins/builtin/news/wire/index.tsx +5 -1
  179. package/src/plugins/builtin/news/wire/news/detail-view.tsx +4 -0
  180. package/src/plugins/builtin/news/wire/news/list-search.ts +5 -2
  181. package/src/plugins/builtin/options/index.tsx +1 -0
  182. package/src/plugins/builtin/options-positioning/index.tsx +1 -0
  183. package/src/plugins/builtin/pe-band/index.tsx +1 -1
  184. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +25 -0
  185. package/src/plugins/builtin/portfolio-list/cli/render.ts +20 -3
  186. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -1
  187. package/src/plugins/builtin/portfolio-list/headless.ts +15 -6
  188. package/src/plugins/builtin/power/index.tsx +1 -1
  189. package/src/plugins/builtin/realized-vol/index.tsx +1 -1
  190. package/src/plugins/builtin/research/headless-schema.ts +4 -3
  191. package/src/plugins/builtin/research/headless.ts +10 -4
  192. package/src/plugins/builtin/research/index.tsx +4 -0
  193. package/src/plugins/builtin/research/relative-valuation-columns.ts +145 -47
  194. package/src/plugins/builtin/research/relative-valuation-currency.ts +31 -0
  195. package/src/plugins/builtin/research/relative-valuation-headless.ts +25 -8
  196. package/src/plugins/builtin/research/relative-valuation-model.ts +40 -9
  197. package/src/plugins/builtin/research/relative-valuation-pane.tsx +3 -2
  198. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -2
  199. package/src/plugins/builtin/research-search/index.tsx +1 -0
  200. package/src/plugins/builtin/research-search/pane.tsx +8 -0
  201. package/src/plugins/builtin/revenue-breakdown/index.tsx +1 -0
  202. package/src/plugins/builtin/reverse-dcf/index.tsx +1 -1
  203. package/src/plugins/builtin/risk-factors/index.tsx +1 -0
  204. package/src/plugins/builtin/scanner/headless.ts +52 -13
  205. package/src/plugins/builtin/seasonality/index.tsx +1 -1
  206. package/src/plugins/builtin/sec/index.tsx +1 -0
  207. package/src/plugins/builtin/series-inventory.ts +1 -1
  208. package/src/plugins/builtin/shared/scanner-capture.ts +11 -3
  209. package/src/plugins/builtin/shared/series-list-detail.tsx +5 -0
  210. package/src/plugins/builtin/short-interest/index.tsx +1 -0
  211. package/src/plugins/builtin/social-mentions/index.tsx +1 -1
  212. package/src/plugins/builtin/supply-chain/index.tsx +1 -0
  213. package/src/plugins/builtin/thirteenf/api.ts +47 -4
  214. package/src/plugins/builtin/thirteenf/data.ts +43 -10
  215. package/src/plugins/builtin/thirteenf/headless.ts +55 -11
  216. package/src/plugins/builtin/thirteenf/model.ts +25 -9
  217. package/src/plugins/builtin/thirteenf/report-notes.ts +27 -6
  218. package/src/plugins/builtin/thirteenf/types.ts +2 -0
  219. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +1 -1
  220. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +8 -7
  221. package/src/plugins/builtin/ticker-detail/data-panes/history-bars.ts +8 -5
  222. package/src/plugins/builtin/ticker-detail/financials/model.ts +18 -2
  223. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +3 -3
  224. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +6 -6
  225. package/src/plugins/builtin/ticker-detail/headless.ts +24 -17
  226. package/src/plugins/builtin/ticker-detail/index.tsx +4 -0
  227. package/src/plugins/builtin/ticker-detail/overview/model.ts +6 -4
  228. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +6 -4
  229. package/src/plugins/builtin/time-sales/client.ts +9 -11
  230. package/src/plugins/builtin/time-sales/index.tsx +1 -1
  231. package/src/plugins/builtin/treasury-auctions/after.ts +267 -0
  232. package/src/plugins/builtin/treasury-auctions/cache.ts +54 -5
  233. package/src/plugins/builtin/treasury-auctions/client.ts +33 -2
  234. package/src/plugins/builtin/treasury-auctions/headless.ts +150 -22
  235. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +126 -0
  236. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +347 -0
  237. package/src/plugins/builtin/treasury-auctions/hk.ts +363 -0
  238. package/src/plugins/builtin/treasury-auctions/index.tsx +27 -4
  239. package/src/plugins/builtin/treasury-auctions/model.ts +264 -28
  240. package/src/plugins/builtin/treasury-auctions/pane.tsx +176 -41
  241. package/src/plugins/builtin/treasury-auctions/treasury-direct.ts +5 -2
  242. package/src/plugins/builtin/treasury-auctions/types.ts +7 -1
  243. package/src/plugins/builtin/vol-surface/index.tsx +1 -1
  244. package/src/plugins/builtin/world-venue-map/index.ts +1 -0
  245. package/src/plugins/builtin/yield-curve/curves.ts +10 -4
  246. package/src/plugins/builtin/yield-curve/headless.ts +6 -2
  247. package/src/plugins/builtin/yield-curve/index.tsx +3 -3
  248. package/src/plugins/builtin/yield-curve/series.ts +10 -0
  249. package/src/plugins/builtin/yield-curve/world.ts +3 -1
  250. package/src/portfolio/collection-name.ts +22 -0
  251. package/src/portfolio/column-values.ts +2 -1
  252. package/src/public/__snapshots__/public-api.test.ts.snap +4 -0
  253. package/src/public/remote.ts +7 -1
  254. package/src/remote/client.ts +191 -11
  255. package/src/remote/controller-utils.ts +13 -1
  256. package/src/remote/controller.ts +88 -26
  257. package/src/remote/endpoint.ts +24 -0
  258. package/src/remote/form.ts +59 -4
  259. package/src/remote/resources.ts +44 -18
  260. package/src/remote/schema.ts +21 -9
  261. package/src/remote/secrets.ts +12 -0
  262. package/src/remote/semantic-tree.tsx +14 -2
  263. package/src/remote/server.ts +2 -1
  264. package/src/remote/surface.tsx +192 -0
  265. package/src/remote/types.ts +5 -0
  266. package/src/renderers/dom/data-table/frozen-column.ts +3 -1
  267. package/src/renderers/dom/data-table/index.tsx +27 -9
  268. package/src/renderers/dom/data-table/row.tsx +2 -0
  269. package/src/renderers/electrobun/bun/desktop/backend.ts +27 -24
  270. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +3 -3
  271. package/src/renderers/electrobun/bun/desktop/snapshot-commit.ts +77 -0
  272. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  273. package/src/renderers/electrobun/view/backend-rpc.ts +3 -0
  274. package/src/renderers/electrobun/view/desktop/window/bridge.ts +3 -0
  275. package/src/renderers/opentui/host.tsx +6 -0
  276. package/src/series/standalone.ts +2 -2
  277. package/src/shares/api.ts +21 -4
  278. package/src/shares/item.ts +73 -0
  279. package/src/shares/pane-item.ts +205 -0
  280. package/src/shares/pane.ts +4 -0
  281. package/src/shares/payload.ts +9 -5
  282. package/src/sources/gloomberb-cloud/news.ts +2 -0
  283. package/src/sources/gloomberb-cloud/normalizers.ts +9 -5
  284. package/src/sources/provider-router/cache.ts +3 -1
  285. package/src/sync/controller.ts +17 -2
  286. package/src/sync/other-window-tabs.ts +32 -1
  287. package/src/sync/react.ts +4 -4
  288. package/src/tickers/renamed-listings.ts +105 -0
  289. package/src/tickers/search/index.ts +103 -16
  290. package/src/time-series/bar-spacing.ts +33 -0
  291. package/src/time-series/base-series.ts +21 -3
  292. package/src/time-series/chart-bounds.ts +31 -0
  293. package/src/time-series/field-catalog.ts +17 -0
  294. package/src/time-series/fundamentals.ts +143 -11
  295. package/src/time-series/ice-credit.ts +32 -6
  296. package/src/time-series/resolve.ts +11 -7
  297. package/src/time-series/session-bar.ts +78 -9
  298. package/src/time-series/studies/formula.ts +53 -10
  299. package/src/time-series/studies/pair.ts +18 -7
  300. package/src/time-series/studies/units.ts +49 -2
  301. package/src/time-series/types.ts +12 -0
  302. package/src/types/desktop-window.ts +2 -0
  303. package/src/types/financials.ts +7 -0
  304. package/src/types/headless.ts +8 -0
  305. package/src/types/plugin-pane-settings.ts +2 -0
  306. package/src/types/plugin-panes.ts +22 -0
  307. package/src/utils/central-banks.ts +86 -1
  308. package/src/utils/cli-output.ts +6 -3
  309. package/src/utils/datetime-format.ts +12 -3
  310. package/src/utils/depositary-receipt.ts +28 -3
  311. package/src/utils/ebitda.ts +128 -0
  312. package/src/utils/format.ts +1 -1
  313. package/src/utils/fundamentals.ts +14 -0
  314. package/src/utils/max-drawdown.ts +97 -16
  315. package/src/utils/shell-word.ts +13 -0
  316. package/src/utils/untrusted-text.ts +29 -0
@@ -1,4 +1,5 @@
1
1
  import { indexRootFor, type IndexRoot } from "../tickers/index-roots";
2
+ import { commandWord } from "../utils/shell-word";
2
3
 
3
4
  /** A broker's code for an index: VIX.X and $VIX.X as thinkorswim writes it, $VIX as Schwab does. */
4
5
  export interface BrokerIndexCode extends IndexRoot {
@@ -26,12 +27,12 @@ export function brokerIndexReadAs(code: BrokerIndexCode): string {
26
27
  return `Read ${code.typed} as ${code.symbol} (${code.name}).`;
27
28
  }
28
29
 
29
- /** "^VIX Cboe Volatility Index (try: gloom quote ^VIX)", under a bare root that found nothing. */
30
+ /** `^VIX Cboe Volatility Index (try: gloom quote "^VIX")`, under a bare root that found nothing. */
30
31
  export function indexRootTryLine(root: IndexRoot, command = "quote"): string {
31
- return `${root.symbol} ${root.name} (try: gloom ${command} ${root.symbol})`;
32
+ return `${root.symbol} ${root.name} (try: gloom ${command} ${commandWord(root.symbol)})`;
32
33
  }
33
34
 
34
- /** "also ^MOVE ICE BofA MOVE Index (gloom quote ^MOVE)", under a bare root that quoted another instrument. */
35
+ /** `also ^MOVE ICE BofA MOVE Index (gloom quote "^MOVE")`, under a bare root that quoted another instrument. */
35
36
  export function indexRootAlsoLine(root: IndexRoot, command = "quote"): string {
36
- return `also ${root.symbol} ${root.name} (gloom ${command} ${root.symbol})`;
37
+ return `also ${root.symbol} ${root.name} (gloom ${command} ${commandWord(root.symbol)})`;
37
38
  }
package/src/cli/index.ts CHANGED
@@ -2,7 +2,9 @@ import { VERSION } from "../version";
2
2
  import type { CliCommandContext, CliCommandDef, CliDispatchResult, CliLaunchRequest } from "../types/plugin";
3
3
  import type { LoadedExternalPlugin } from "../plugins/loader";
4
4
  import { loadCliConfigIfAvailable } from "./context";
5
- import { parseCliGlobalArgs } from "./options";
5
+ import { checkCliOutputFormat, commandOwnsOutput, parseCliGlobalArgs, type CliGlobalOptions } from "./options";
6
+ import { checkOutputPath, resolveOutputPath, writeOutputFile } from "./output-file";
7
+ import { printCliResult, takeCliFileExport } from "./result";
6
8
  import {
7
9
  buildCliCommandRegistry,
8
10
  createCliCommandContext,
@@ -189,7 +191,7 @@ export function createCoreCliCommands(
189
191
  "fn HP AAPL",
190
192
  "fn ANR SAN:EPA",
191
193
  "fn CBR --json",
192
- "fn WEI --csv --section europe > europe.csv",
194
+ "fn WEI --csv --section europe --output europe.csv",
193
195
  "fn RV NEE,FSLR --csv --output rv.csv",
194
196
  "fn 13F AAPL --view=ticker-holdings",
195
197
  "fn OVME --spot 100 --strike 100 --days 30 --volatility 25",
@@ -413,7 +415,8 @@ export { buildSearchReport, searchCandidatesForCli };
413
415
  export async function dispatchCli(args: string[], options: DispatchCliOptions = {}): Promise<CliDispatchResult> {
414
416
  let parsed;
415
417
  try {
416
- parsed = parseCliGlobalArgs(args);
418
+ // --output without a format is refused once the command is known: a plugin's own --output is not the export's.
419
+ parsed = parseCliGlobalArgs(args, { deferOutputCheck: true });
417
420
  } catch (error) {
418
421
  printCliError(asUsageError(error), inferCliErrorOptions(args));
419
422
  process.exitCode = 1;
@@ -438,6 +441,15 @@ export async function dispatchCli(args: string[], options: DispatchCliOptions =
438
441
  if (!resolved) {
439
442
  return { kind: "unhandled" };
440
443
  }
444
+ try {
445
+ // A plugin command with its own --output keeps it: the global flag yields, as it does to `fn` and `shot`.
446
+ if (parsed.options.output !== undefined && commandOwnsOutput(resolved.command)) parsed = parseCliGlobalArgs(args, { ownsOutput: true });
447
+ checkCliOutputFormat(parsed);
448
+ } catch (error) {
449
+ printCliError(asUsageError(error), parsed.options);
450
+ process.exitCode = 1;
451
+ return { kind: "handled" };
452
+ }
441
453
 
442
454
  // The overview includes installed commands; one built-in command's help only
443
455
  // needs that command. An unknown help topic may belong to an installed plugin.
@@ -459,13 +471,19 @@ export async function dispatchCli(args: string[], options: DispatchCliOptions =
459
471
  : foldCommandArgs(resolved.command, parsed.args.slice(1), parsed.literalStart - 1);
460
472
  try {
461
473
  if (!helpOnly && resolved.builtin) checkCliCommandOptions(resolved.command, commandArgs, parsed.literalStart - 1);
474
+ // The file --output names, checked before the command runs so a path that cannot be written fails at once.
475
+ const outputPath = parsed.options.output !== undefined && !helpOnly ? resolveOutputPath(parsed.options.output) : null;
476
+ const replacing = outputPath ? await checkOutputPath(outputPath) : false;
477
+ takeCliFileExport();
462
478
  // What it answers from a saved copy, its refresh having failed, its closing line says.
463
479
  const result = await collectSavedCopies(() => Promise.resolve(target.command.execute(
464
480
  commandArgs,
465
481
  createCliCommandContext(target.ownerId, registry, parsed.options, commandArgs),
466
482
  )));
483
+ if (outputPath) await saveFileExport(outputPath, parsed.options, resolved.command.name, replacing);
467
484
  return normalizeCliDispatchResult(result);
468
485
  } catch (error) {
486
+ takeCliFileExport();
469
487
  // A coin typed without its quote currency (USDT) is named by its one symbol (USDT-USD) in the hint.
470
488
  if (parsed.options.format !== "json") await primeBoardCoins([error instanceof Error ? error.message : String(error)]);
471
489
  printCliError(error, parsed.options, { command: resolved.command.name, args: commandArgs,
@@ -475,6 +493,25 @@ export async function dispatchCli(args: string[], options: DispatchCliOptions =
475
493
  }
476
494
  }
477
495
 
496
+ /**
497
+ * Writes the export a command printed to the file `--output` named, in
498
+ * UTF-8 without a byte order mark, and says where it went: `Saved <path>`,
499
+ * `Replaced <path>` over a file that was there, or in JSON its envelope. A
500
+ * command that printed no export (its result failed, or it has no table to
501
+ * export) writes no file and says so.
502
+ */
503
+ async function saveFileExport(path: string, options: CliGlobalOptions, command: string, replacing: boolean): Promise<void> {
504
+ const written = takeCliFileExport();
505
+ if (written === null) {
506
+ if (process.exitCode) return;
507
+ throw new Error(`${command} printed no ${options.format.toUpperCase()} export; nothing was written to ${path}.`);
508
+ }
509
+ await writeOutputFile(path, `${written}\n`);
510
+ printCliResult({ data: { output: path, format: options.format, replaced: replacing } },
511
+ { ...options, output: undefined, format: options.format === "json" ? "json" : "text" },
512
+ { text: () => `${replacing ? "Replaced" : "Saved"} ${path}` });
513
+ }
514
+
478
515
  /** Explains why dispatch found no command in `args`, suggesting the closest one. */
479
516
  export async function failUnknownCliCommand(args: string[], options: DispatchCliOptions = {}): Promise<never> {
480
517
  let token = args[0] ?? "";
@@ -2,6 +2,7 @@ import { listingSuffixExchange } from "../sources/listing-symbols";
2
2
  import { kindFromListingSyntax } from "../tickers/instrument-kind";
3
3
  import { macroReleaseTopic } from "../plugins/builtin/shared/macro-releases";
4
4
  import { parsePublicTickerKey } from "../utils/exchanges";
5
+ import { commandWord } from "../utils/shell-word";
5
6
  import { listingAbroadVenue } from "../utils/sec";
6
7
  import { nimCommand } from "./bank-section";
7
8
  import { treasuryYieldLine, treasuryYieldTenor } from "./treasury-yields";
@@ -98,7 +99,14 @@ export const MUNI_LINE = "Municipal bonds: no AAA muni curve (MMD and BVAL are l
98
99
  * carriers"). An entry without `words` matches the whole query alone, since
99
100
  * its terms are words of company names too ("carbon", "second").
100
101
  */
101
- const KNOWN_GAPS: ReadonlyArray<{ terms: readonly string[]; words?: readonly string[]; tickers?: readonly string[]; message: string }> = [
102
+ const KNOWN_GAPS: ReadonlyArray<{
103
+ terms: readonly string[];
104
+ words?: readonly string[];
105
+ tickers?: readonly string[];
106
+ /** A price the terminal has none of: where a ticker goes, the query answers this line rather than a company's name holding its words. */
107
+ unquoted?: boolean;
108
+ message: string;
109
+ }> = [
102
110
  {
103
111
  terms: ["EUA", "EUAs", "EU ETS", "EU allowance", "EU allowances", "EU carbon", "carbon", "carbon allowance", "carbon allowances",
104
112
  "carbon price", "carbon prices", "carbon credits", "emission allowances", "emissions allowances"],
@@ -127,6 +135,17 @@ const KNOWN_GAPS: ReadonlyArray<{ terms: readonly string[]; words?: readonly str
127
135
  message: "Baltic indices (BDI, Capesize, Panamax, Supramax) and freight forwards (FFA) are not covered. Traded proxies: BDRY (freight futures ETF), "
128
136
  + "SBLK, GNK, DSX (dry-bulk shipowners); chokepoint transits: fn CHOKE; news \"dry bulk\".",
129
137
  },
138
+ {
139
+ // Live iron ore futures (SGX, DCE, CME) are licensed; the IMF's monthly world price is the one the terminal has.
140
+ // "iron ore" typed for a quote was Kumba Iron Ore's stock, which its own name still finds.
141
+ terms: ["iron ore", "iron ore price", "iron ore prices", "iron ore futures", "iron ore 62", "62% Fe", "iron ore 62% Fe",
142
+ "iron ore fines", "SGX iron ore", "DCE iron ore", "iron ore spot"],
143
+ words: ["price", "prices", "futures", "future", "spot", "62", "fe", "cfr", "china", "fines", "monthly", "chart", "today",
144
+ "current", "latest", "live", "quote", "the", "of"],
145
+ unquoted: true,
146
+ message: "Iron ore: no live price (SGX, DCE and CME iron ore futures are licensed). The IMF's monthly world price: gloom fred PIORECRUSDM. "
147
+ + "Producers: VALE, RIO, BHP, KIO:JSE (Kumba Iron Ore).",
148
+ },
130
149
  {
131
150
  // What the terminal has for munis, and what it does not: the AAA curve every muni ratio quotes is licensed.
132
151
  terms: ["muni", "munis", "municipal", "municipals", "municipal bond", "municipal bonds", "muni bond", "muni bonds", "muni fund", "muni funds",
@@ -156,8 +175,8 @@ const BANK_FIGURES_TOPIC = {
156
175
  * command or a function. One example, writing a file.
157
176
  */
158
177
  function exportLine(symbol = "LMT"): string {
159
- return `Export: add --csv or --json to any command to print its result as CSV or JSON, e.g. gloom history ${symbol} --csv > ${
160
- symbol.toLowerCase().replace(/[^a-z0-9]+/g, "-")}.csv`;
178
+ return `Export: add --csv or --json to any command to print its result as CSV or JSON, and --output <file> to write it to a file in UTF-8, e.g. gloom history ${
179
+ commandWord(symbol)} --csv --output ${symbol.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")}.csv`;
161
180
  }
162
181
 
163
182
  const EXPORT_POINTER = {
@@ -334,13 +353,15 @@ const COMMAND_POINTERS: ReadonlyArray<{
334
353
  },
335
354
  {
336
355
  // A currency forward, not a forward rate on a yield curve, forward guidance, a forward P/E or the forward
337
- // inflation series: a query that says more than "forward" has to name FX.
338
- names: ["forward", "forwards", "fwd", "fwds"],
339
- words: ["rate", "rates", "implied", "hedge", "hedging", "cost", "costs", "premium", "interest", "1w", "2w", "30d", "1m", "3m",
356
+ // inflation series: a query that says more than "forward" has to name FX. A hedge or a carry alone is the
357
+ // forward's too (a hedge fund or a carry cost is not).
358
+ names: ["forward", "forwards", "fwd", "fwds", "hedge", "hedging", "carry"],
359
+ words: ["rate", "rates", "implied", "cost", "costs", "premium", "interest", "1w", "2w", "30d", "1m", "3m",
340
360
  "6m", "1y"],
341
- qualifiers: ["fx", "currency", "currencies", "point", "points", "pips", "cip", "covered", "parity", "outright",
342
- "usd", "mxn", "eur", "gbp", "usdmxn", "eurusd", "gbpusd", "eurmxn", "peso", "dollar", "euro", "sterling"],
343
- line: "FX forwards implied by both currencies' short rates (covered interest parity), with forward points and the hedge cost: gloom fx USD/MXN --forward 30d",
361
+ qualifiers: ["fx", "currency", "currencies", "point", "points", "pips", "cip", "covered", "parity", "outright", "trade",
362
+ "usd", "mxn", "eur", "gbp", "zar", "try", "usdmxn", "eurusd", "gbpusd", "eurmxn", "usdzar", "usdtry", "peso", "dollar", "euro",
363
+ "sterling", "rand", "lira"],
364
+ line: "FX forwards implied by both currencies' short rates (covered interest parity), with forward points, the hedge cost and, for an amount, the carry and who earns it: gloom fx 5000000 USD/MXN --forward 30d",
344
365
  },
345
366
  {
346
367
  names: ["defi", "tvl", "tvls", "total value locked", "on-chain", "onchain", "aave", "lido", "eigenlayer", "morpho"],
@@ -497,6 +518,14 @@ function namesKnownGap(gap: (typeof KNOWN_GAPS)[number], query: string): boolean
497
518
  return named.size > 0 && asked.every((word) => named.has(word) || gap.words!.includes(word));
498
519
  }
499
520
 
521
+ /**
522
+ * The line for a price the terminal has none of, typed where a ticker goes ("iron ore"), so it is never read as the
523
+ * company whose name holds its words (Kumba Iron Ore); null for anything else.
524
+ */
525
+ export function unquotedGapMessage(query: string): string | null {
526
+ return KNOWN_GAPS.find((gap) => gap.unquoted && namesKnownGap(gap, query))?.message ?? null;
527
+ }
528
+
500
529
  /**
501
530
  * The line for a query that names a known subject ("carbon allowances", "EUA", "panamax rates"), a Treasury yield
502
531
  * typed as a ticker (US10Y), a topic with no function ("defense budget"), or a macro release no series carries
@@ -42,7 +42,8 @@ import { stripStrayEdges } from "./symbol-args";
42
42
  import { isNoProviderMessage, isNoSourceAnswer, isProviderBusy } from "../sources/provider-errors";
43
43
  import { dashedCoinPair, exchangeLineCoinListing, isSpotCommodityOrCurrencyPair, MAJOR_COIN_NAMES, TOP_COIN_NAMES } from "../utils/crypto-pair";
44
44
  import { boardCoinFor, primeBoardCoins } from "./board-coins";
45
- import { knownGapMessage } from "./known-gaps";
45
+ import { knownGapMessage, unquotedGapMessage } from "./known-gaps";
46
+ import { renamedListingFor, renamedListingReadAs, renamedListingSymbol } from "../tickers/renamed-listings";
46
47
  import { currencyPairSpelling } from "../utils/currency-pair";
47
48
  import { bareFuturesCode, futuresContractByCode, futuresContractByWord, listedFuturesSymbol } from "../market-data/futures-board";
48
49
  import { classifyInstrumentType, kindFromListingSyntax } from "../tickers/instrument-kind";
@@ -69,6 +70,7 @@ import { listingSuffixCandidate, listingSuffixVenue, tickerHasListingSuffix } fr
69
70
  import { isCurrencyPairListing } from "../utils/fx-market-hours";
70
71
  import { coinElsewhereNote, notTheCoinNote } from "./commands/crypto-hints";
71
72
  import { fredSeriesArgument, fredSeriesNotListing } from "../series/fred-argument";
73
+ import { commandWord } from "../utils/shell-word";
72
74
 
73
75
  /** The `--exchange` option of every command that takes a ticker. */
74
76
  export const EXCHANGE_OPTION = {
@@ -653,9 +655,9 @@ interface OtherListingsMessage {
653
655
  * --range 5Y` keeps the options. Null where the request names listings alone.
654
656
  */
655
657
  function retryCommand(request: Pick<ListingDataRequest, "command" | "retry">, key: string): string | null {
656
- if (request.retry !== undefined) return request.retry?.(key) ?? null;
658
+ if (request.retry !== undefined) return request.retry?.(commandWord(key)) ?? null;
657
659
  const [command, ...options] = request.command.split(" ");
658
- return ["gloom", command, key, ...options].join(" ");
660
+ return ["gloom", command, commandWord(key), ...options].join(" ");
659
661
  }
660
662
 
661
663
  /**
@@ -1288,6 +1290,15 @@ export async function resolveCliListing(
1288
1290
  const { message, details } = fredSeriesNotListing(fred);
1289
1291
  throw new ListingArgError(message, details);
1290
1292
  }
1293
+ // "iron ore" has no live price: it says so and where the monthly one is, never Kumba Iron Ore's stock.
1294
+ const unquoted = exchangeOption?.trim() ? null : unquotedGapMessage(typed);
1295
+ if (unquoted) throw new ListingArgError(unquoted);
1296
+ // A listing that moved to a new symbol (ELET3, "eletrobras") is the one it trades as now, saying so.
1297
+ const renamed = exchangeOption?.trim() ? null : renamedListingFor(typed);
1298
+ if (renamed) {
1299
+ const now = await resolveCliListing(renamedListingSymbol(renamed), null, deps, options);
1300
+ return { ...now, readAs: [renamedListingReadAs(typed, renamed), now.readAs].filter(Boolean).join(" "), readFromName: true };
1301
+ }
1291
1302
  const read = await readTerminalCodeArg(deps.dataProvider, typed);
1292
1303
  // A company's name, an entry of a comma list (`WHR, Whirlpool Corporation`), is the listing search names for it.
1293
1304
  // A name before a legal form ("SAP SE", "SIEMENS AG") is looked up first: SE is also SIX Swiss's market code.
@@ -1735,8 +1746,9 @@ export function listingFields(saved: Pick<SavedListingName, "key" | "symbol" | "
1735
1746
 
1736
1747
  /** The listing a saved ticker row is, as a collection command names it after adding or removing it. */
1737
1748
  export function savedListingName(ticker: TickerRecord): SavedListingName {
1738
- const { symbol } = parsePublicTickerKey(ticker.metadata.ticker);
1739
- const exchange = canonicalExchange(ticker.metadata.exchange);
1749
+ const { symbol, exchange: stored } = parsePublicTickerKey(ticker.metadata.ticker);
1750
+ // A row stored under its venue (ASML:XAMS) with none beside it is that venue's listing.
1751
+ const exchange = canonicalExchange(ticker.metadata.exchange) || stored || "";
1740
1752
  const key = exchange ? `${symbol}:${exchange}` : symbol;
1741
1753
  // A row saved without a company carries its symbol as the name.
1742
1754
  const typed = ticker.metadata.name?.trim();
@@ -8,6 +8,7 @@ import { splitSymbolWords } from "./symbol-args";
8
8
  import { isNumberCell } from "./symbol-cells";
9
9
  import { isProviderBusy, type ProviderBusyError } from "../sources/provider-errors";
10
10
  import { unknownBloombergMarket } from "../tickers/terminal-codes";
11
+ import { renamedListingFor } from "../tickers/renamed-listings";
11
12
 
12
13
  /**
13
14
  * The entries of a list (`splitSymbolArgs`, or a file's lines) as the symbols
@@ -110,7 +111,8 @@ export type PhraseReading =
110
111
 
111
112
  /**
112
113
  * One quoted argument with spaces: a company's name when search finds the
113
- * company (`"Whirlpool Corporation"`), else a pasted line of symbols when no
114
+ * company (`"Whirlpool Corporation"`) or it is a renamed company's former
115
+ * name (renamed-listings.ts), else a pasted line of symbols when no
114
116
  * word is one the source says is not a ticker (`"AAPL MSFT"`), else a phrase
115
117
  * (`"10 year yield"`), which is never split into symbols such as YEAR and
116
118
  * YIELD. The words are asked in one batch beside the name search, not a
@@ -125,6 +127,8 @@ export async function readPhraseArgument(
125
127
  dataProvider: Pick<DataProvider, "search" | "getQuotesBatch">,
126
128
  ): Promise<PhraseReading> {
127
129
  if (unknownBloombergMarket(phrase) || await readTerminalCodeArg(dataProvider, phrase)) return { kind: "symbols", symbols: [phrase] };
130
+ // A renamed company's former name ("Centrais Elétricas Brasileiras") is the listing it trades as now.
131
+ if (renamedListingFor(phrase)) return { kind: "name", name: phrase };
128
132
  const words = splitSymbolWords([phrase]);
129
133
  const numbered = words.some(isNumberCell);
130
134
  const asked = words.filter((word) => !word.includes(":") && !isNumberCell(word)).map((word) => word.replace(/^\$/, "").toUpperCase());
@@ -1,5 +1,6 @@
1
1
  import { futuresContractByWord } from "../market-data/futures-board";
2
2
  import { notATickerSymbol } from "../sources/provider-errors";
3
+ import { renamedListingFor, renamedListingHint } from "../tickers/renamed-listings";
3
4
  import { boardCoinFor } from "./board-coins";
4
5
  import { currencyNameHint } from "./currency-name-hint";
5
6
  import { splitSymbolArgs, splitSymbolWords } from "./symbol-args";
@@ -52,6 +53,9 @@ export function withSearchHints(text: string, args: readonly string[], isFredSer
52
53
  const typed = typedSymbol(symbol, args);
53
54
  const id = typed.toUpperCase();
54
55
  if (/^[A-Z0-9]+$/.test(id) && isFredSeries(id)) return `${sentence} Try \`gloom fred ${id}\`.`;
56
+ // A listing that moved to a new symbol (ELET3 is AXIA3) points to it, never to a search for the dead one.
57
+ const renamed = renamedListingFor(typed);
58
+ if (renamed) return `${sentence} ${renamedListingHint(renamed)}`;
55
59
  const coin = boardCoinFor(id);
56
60
  if (coin) return `${sentence} Did you mean ${coin.symbol}${coin.name && coin.name.toUpperCase() !== coin.symbol ? ` (${coin.name})` : ""}?`;
57
61
  const tenor = treasuryYieldTenor(typed);
@@ -19,6 +19,14 @@ export interface CliGlobalOptions {
19
19
  refresh: boolean;
20
20
  dryRun: boolean;
21
21
  yes: boolean;
22
+ /**
23
+ * `--output <path>` (or `--out`): the file a `--csv`, `--json` or
24
+ * `--ndjson` export is written to, in UTF-8, in place of stdout. A shell's
25
+ * redirect is not always UTF-8: Windows PowerShell 5.1 writes `>` as
26
+ * UTF-16. `fn`, `shot` and a plugin command that declares its own
27
+ * `--output` read the flag themselves.
28
+ */
29
+ output?: string;
22
30
  }
23
31
 
24
32
  export interface ParsedCliArgs {
@@ -55,6 +63,8 @@ function parseRowCount(flag: "--limit" | "--tail", value: string | undefined): n
55
63
 
56
64
  /** Commands whose own `--width` is a size in pixels, so it is not the table width. */
57
65
  const PIXEL_WIDTH_COMMANDS = new Set(["shot", "screenshot"]);
66
+ /** Commands whose own `--output` names their file: a function's report, a capture's PNG. */
67
+ const OWN_OUTPUT_COMMANDS = new Set(["fn", "function", "shot", "screenshot"]);
58
68
  const MIN_TABLE_WIDTH = 20;
59
69
 
60
70
  function parseColumnCount(value: string | undefined): number {
@@ -65,23 +75,44 @@ function parseColumnCount(value: string | undefined): number {
65
75
  return parsed;
66
76
  }
67
77
 
78
+ function parseOutputFile(value: string | undefined): string {
79
+ if (!value?.trim() || value.startsWith("--")) throw new Error("--output needs a file to write, such as --csv --output report.csv.");
80
+ return value;
81
+ }
82
+
68
83
  /** The first word that is not an option or the value of one: the command the arguments are for. */
69
84
  function commandWord(rawArgs: readonly string[]): string | undefined {
70
85
  for (let index = 0; index < rawArgs.length; index += 1) {
71
86
  const arg = rawArgs[index]!;
72
87
  if (arg === "--") return rawArgs[index + 1];
73
- if (arg === "--limit" || arg === "--tail" || arg === "--width") index += 1;
88
+ if (arg === "--limit" || arg === "--tail" || arg === "--width" || arg === "--output" || arg === "--out") index += 1;
74
89
  else if (!arg.startsWith("-")) return arg;
75
90
  }
76
91
  return undefined;
77
92
  }
78
93
 
79
- export function parseCliGlobalArgs(rawArgs: string[]): ParsedCliArgs {
94
+ /**
95
+ * Whether a command reads `--output` itself: `fn` and `shot`, and a plugin
96
+ * command whose options declare one. The global flag yields to it.
97
+ */
98
+ export function commandOwnsOutput(command: { name: string; help?: { options?: readonly { flags: string }[] } }): boolean {
99
+ return OWN_OUTPUT_COMMANDS.has(command.name.toLowerCase())
100
+ || (command.help?.options ?? []).some((option) => /(^|[\s,])--(output|out)\b/.test(option.flags));
101
+ }
102
+
103
+ /**
104
+ * The global flags out of `rawArgs`. `ownsOutput` says the command reads
105
+ * `--output` itself (commandOwnsOutput), which a built-in's name tells
106
+ * before its plugin is loaded; `deferOutputCheck` leaves refusing `--output`
107
+ * without an export format to `checkCliOutputFormat`, once that is known.
108
+ */
109
+ export function parseCliGlobalArgs(rawArgs: string[], settings: { ownsOutput?: boolean; deferOutputCheck?: boolean } = {}): ParsedCliArgs {
80
110
  const options: CliGlobalOptions = { ...DEFAULT_CLI_OPTIONS };
81
111
  const args: string[] = [];
82
112
  let help = false;
83
113
  let literalStart: number | null = null;
84
114
  const ownsWidth = PIXEL_WIDTH_COMMANDS.has(commandWord(rawArgs)?.toLowerCase() ?? "");
115
+ const ownsOutput = settings.ownsOutput ?? OWN_OUTPUT_COMMANDS.has(commandWord(rawArgs)?.toLowerCase() ?? "");
85
116
 
86
117
  for (let index = 0; index < rawArgs.length; index += 1) {
87
118
  const arg = rawArgs[index]!;
@@ -143,6 +174,15 @@ export function parseCliGlobalArgs(rawArgs: string[]): ParsedCliArgs {
143
174
  options.width = parseColumnCount(arg.slice("--width=".length));
144
175
  continue;
145
176
  }
177
+ if (!ownsOutput && (arg === "--output" || arg === "--out")) {
178
+ index += 1;
179
+ options.output = parseOutputFile(rawArgs[index]);
180
+ continue;
181
+ }
182
+ if (!ownsOutput && (arg.startsWith("--output=") || arg.startsWith("--out="))) {
183
+ options.output = parseOutputFile(arg.slice(arg.indexOf("=") + 1));
184
+ continue;
185
+ }
146
186
  if (arg === "--limit" || arg === "--tail") {
147
187
  index += 1;
148
188
  options[arg === "--limit" ? "limit" : "tail"] = parseRowCount(arg, rawArgs[index]);
@@ -162,5 +202,14 @@ export function parseCliGlobalArgs(rawArgs: string[]): ParsedCliArgs {
162
202
  throw new Error("Use --limit or --tail, not both: --limit keeps the first rows, --tail the newest.");
163
203
  }
164
204
 
165
- return { args, options, help, literalStart: literalStart ?? args.length };
205
+ const parsed = { args, options, help, literalStart: literalStart ?? args.length };
206
+ if (!settings.deferOutputCheck) checkCliOutputFormat(parsed);
207
+ return parsed;
208
+ }
209
+
210
+ /** `--output` writes an export: refused without --csv, --json or --ndjson. */
211
+ export function checkCliOutputFormat(parsed: Pick<ParsedCliArgs, "options" | "help">): void {
212
+ if (parsed.options.output !== undefined && parsed.options.format === "text" && !parsed.help) {
213
+ throw new Error("--output writes an export: add --csv, --json or --ndjson, such as --csv --output report.csv.");
214
+ }
166
215
  }
@@ -52,17 +52,19 @@ function isNotAFile(path: string): Error {
52
52
  /**
53
53
  * Fails when `path` names a folder, a link or anything else that is not a
54
54
  * plain file (a device, a pipe): checked before a report loads, so it stops
55
- * at once, and again as the file is opened.
55
+ * at once, and again as the file is opened. True when a file is there to be
56
+ * replaced.
56
57
  */
57
- export async function checkOutputPath(path: string, platform: NodeJS.Platform = process.platform): Promise<void> {
58
+ export async function checkOutputPath(path: string, platform: NodeJS.Platform = process.platform): Promise<boolean> {
58
59
  const existing = await lstat(path).catch(() => {
59
60
  // Intentional ignore: a path that does not exist yet is the usual case, and writing reports any real failure.
60
61
  return null;
61
62
  });
62
- if (!existing) return;
63
+ if (!existing) return false;
63
64
  if (existing.isDirectory()) throw isFolder(path, platform === "win32" ? win32 : posix);
64
65
  if (existing.isSymbolicLink()) throw isLink(path);
65
66
  if (!existing.isFile()) throw isNotAFile(path);
67
+ return true;
66
68
  }
67
69
 
68
70
  /**
@@ -665,10 +665,25 @@ function optionDescription(option: PaneFunctionOptionDef): string {
665
665
  const parts = [option.description.replace(/\.$/, "")];
666
666
  // An enum that also reads other values (a bar size of any length) lists its values as examples.
667
667
  if (choices.join("|").length > MAX_INLINE_CHOICES) parts.push(`${option.list ? "Each one of" : option.normalize ? "Such as" : "One of"} ${choices.join(", ")}`);
668
+ const bounds = optionBounds(option);
669
+ if (bounds) parts.push(bounds);
668
670
  if (option.defaultValue !== undefined && option.defaultValue !== "") parts.push(`Default ${String(option.defaultValue)}`);
669
671
  return `${parts.join(". ")}.`;
670
672
  }
671
673
 
674
+ /**
675
+ * The range a number option takes (`From 30 to 1,100`), so its limits are read
676
+ * before a value is refused, unless its description already names them.
677
+ */
678
+ function optionBounds(option: PaneFunctionOptionDef): string | null {
679
+ if (option.type !== "integer") return null;
680
+ const named = (value: number) => [String(value), value.toLocaleString("en-US")].some((text) => new RegExp(`(^|[^\\d,.])${text.replace(/[.,]/g, "\\$&")}(?!\\d|[,.]\\d)`).test(option.description));
681
+ const min = option.minimum != null && !named(option.minimum) ? option.minimum.toLocaleString("en-US") : null;
682
+ const max = option.maximum != null && !named(option.maximum) ? option.maximum.toLocaleString("en-US") : null;
683
+ if (min && max) return `From ${min} to ${max}`;
684
+ return min ? `At least ${min}` : max ? `At most ${max}` : null;
685
+ }
686
+
672
687
  /** A limitation as a sentence, so one does not run into the next: with a full stop unless it ends in one. */
673
688
  export function limitationSentence(text: string): string {
674
689
  const trimmed = text.trim();
@@ -993,15 +993,15 @@ export const FUNCTION_HELP: Readonly<Record<string, FunctionHelp>> = {
993
993
  bloomberg: ["WIRP", "FFIP"],
994
994
  },
995
995
  CRD: {
996
- summary: "ICE BofA option-adjusted spreads: US investment grade and high yield by rating, and euro high yield, with the day's change.",
997
- usage: ["CRD", "CRD --region euro"],
996
+ summary: "ICE BofA option-adjusted spreads: US investment grade and high yield by rating, euro high yield, and emerging markets and Asia corporates, with the day's change.",
997
+ usage: ["CRD", "CRD --region euro", "CRD --region asia,em"],
998
998
  keys: [OPEN],
999
999
  data: same("Daily close, published the next day"),
1000
1000
  bloomberg: ["CRD"],
1001
1001
  },
1002
1002
  AUCT: {
1003
- summary: "Bill, note, bond and TIPS auction results: high rate, stop-out versus average, bid-to-cover, indirect, direct and dealer takedown and size, with the auctions announced next. Searchable by benchmark (10Y) or CUSIP; history reaches back 10 years.",
1004
- usage: ["AUCT", "AUCT 10Y", "AUCT 91282CRF0"],
1003
+ summary: "Bill, note, bond and TIPS auction results: high rate (a bill's investment rate, with its discount rate), the stop-out's spread against the published average (the median from Nov 1998), bid-to-cover, indirect, direct and dealer takedown and size, with the auctions announced next. The after view ranks each auction's B/C, indirect and dealer share against its tenor's last 24 and gives the Treasury yield's move 1, 5 and 20 sessions later. Searchable by benchmark (10Y) or CUSIP; history reaches back to 1979 (--history-days all). --market hk lists Hong Kong's EF Bills, EF Notes and Government Bond tenders from HKMA's Open API (Source: HKMA; published monthly): issue date, tenor, average accepted yield, B/C and size.",
1004
+ usage: ["AUCT", "AUCT 10Y", "AUCT 91282CRF0", "AUCT 7Y --history-days 3650 --view after --sort btc-pctl", "AUCT --market hk", "AUCT HKGB 10Y"],
1005
1005
  keys: [SEARCH, key("f", "ilter"), OPEN],
1006
1006
  data: same("Daily, after each auction"),
1007
1007
  bloomberg: ["AUCT"],
@@ -598,11 +598,12 @@ function renderSeries(result: HeadlessSeriesResult): string[] {
598
598
  const latest = [...series.points].reverse().find((point) => (
599
599
  point.value != null || point.close != null
600
600
  ));
601
+ // N/M stands for the period the series would end on, not an older value before it.
601
602
  return {
602
603
  series: series.label,
603
604
  name: series.name?.trim() || null,
604
- latest: latest ? seriesLatestDate(series, latest.date) : "-",
605
- value: seriesValue(series, latest?.value ?? latest?.close ?? null),
605
+ latest: series.notMeaningful ? series.notMeaningful.asOf : latest ? seriesLatestDate(series, latest.date) : "-",
606
+ value: series.notMeaningful ? "N/M" : seriesValue(series, latest?.value ?? latest?.close ?? null),
606
607
  unit: series.unit?.trim() ? currencyRateUnitText(series.unit.trim()) : null,
607
608
  points: observationCount(series),
608
609
  };
@@ -617,6 +618,9 @@ function renderSeries(result: HeadlessSeriesResult): string[] {
617
618
  { key: "points", header: "Points", align: "right" },
618
619
  ];
619
620
  const lines = [renderRows(rows, columns, undefined)];
621
+ const notMeaningful = result.series.flatMap((series) => series.notMeaningful
622
+ ? [`${series.label}: N/M, ${series.notMeaningful.reason.charAt(0).toLowerCase()}${series.notMeaningful.reason.slice(1)}.`] : []);
623
+ if (notMeaningful.length) lines.push("", ...notMeaningful.map((line) => wrapToTerminal(line)));
620
624
  if (result.stats) {
621
625
  lines.push("", renderSection("Statistics"), renderEntries(statisticsEntries(result.stats)));
622
626
  }
@@ -963,7 +967,8 @@ function resultRowCount(definition: HeadlessPaneDefinition, result: HeadlessPane
963
967
  count + ("rows" in section && section.rows ? section.rows.length : section.entries.length)
964
968
  ), 0);
965
969
  case "series":
966
- return (result as HeadlessSeriesResult).series.reduce((count, series) => count + observationCount(series), 0);
970
+ // An N/M is a reading: the report has something to say for the series.
971
+ return (result as HeadlessSeriesResult).series.reduce((count, series) => count + Math.max(observationCount(series), series.notMeaningful ? 1 : 0), 0);
967
972
  case "snapshot":
968
973
  return (result as HeadlessSnapshotResult).items.length;
969
974
  default: {
@@ -1049,7 +1054,7 @@ export async function buildHeadlessFunctionReport(
1049
1054
  target: resolved.token,
1050
1055
  capabilityId: resolved.capability.id,
1051
1056
  symbols,
1052
- options: resolved.options,
1057
+ options: { ...resolved.options, ...loaded.result.appliedOptions },
1053
1058
  rowCount,
1054
1059
  empty: rowCount === 0,
1055
1060
  complete,
@@ -36,7 +36,7 @@ import {
36
36
  ListingArgError, listingFateLoader, listingReadNotes, loadForListing, loadListingQuoteAnswer, quotedListingChoiceNotes, refuseMovedListing,
37
37
  } from "../listing-arg";
38
38
  import { notATickerStop } from "../company-name-hint";
39
- import { CLI_ERROR_CODE, failUnreachable, failWithError, isCliFailure, unreachableError } from "../errors";
39
+ import { CLI_ERROR_CODE, failUnreachable, failWithError, isCliFailure, isSourceUnavailableAnswer, unreachableError } from "../errors";
40
40
  import { DATA_SERVICE_UNREACHABLE_MESSAGE, isNetworkFailure } from "../../utils/network-failure";
41
41
  import { isTickerLinkPeer } from "../../layout/ticker-navigation";
42
42
  import { knownGapMessage, commandPointer, commandPointerLeads, topicPointer } from "../known-gaps";
@@ -287,7 +287,7 @@ export async function runPaneFunction(args: string[], ctx: CliCommandContext) {
287
287
  }
288
288
  // The file --output names, checked before the report loads so a path that cannot be written fails at once.
289
289
  const outputPath = parsed.outputPath === null ? null : resolveOutputPath(parsed.outputPath);
290
- if (outputPath) await checkOutputPath(outputPath);
290
+ const replacing = outputPath ? await checkOutputPath(outputPath) : false;
291
291
  if (parsed.requireBotSafe && (
292
292
  !resolved.capability.botSafe || resolved.capability.reportReadiness !== "ready"
293
293
  )) {
@@ -382,10 +382,10 @@ export async function runPaneFunction(args: string[], ctx: CliCommandContext) {
382
382
  await writeOutputFile(outputPath, `${csv}\n`);
383
383
  if (!ctx.cliOptions.quiet) for (const line of footer) console.error(line);
384
384
  // What was written and where; warnings go to stderr as they would beside printed rows, and JSON keeps its envelope.
385
- const saved = { output: outputPath, format: ctx.cliOptions.format, rows: report.data.rowCount };
385
+ const saved = { output: outputPath, format: ctx.cliOptions.format, rows: report.data.rowCount, replaced: replacing };
386
386
  printCliResult({ data: saved, ...(warnings.length > 0 ? { warnings } : {}) },
387
387
  { ...ctx.cliOptions, format: ctx.cliOptions.format === "json" ? "json" : "text" },
388
- { text: () => `Saved ${outputPath}` });
388
+ { text: () => `${replacing ? "Replaced" : "Saved"} ${outputPath}` });
389
389
  return;
390
390
  }
391
391
  ctx.printResult(result, render);
@@ -650,6 +650,8 @@ async function runPaneCliCommand(ctx: CliCommandContext, run: () => Promise<void
650
650
  // A failure with fields for --json (`ticker_moved`, its change and retry), or a code of its own (`no_data`,
651
651
  // `service_unreachable` and whether to retry), keeps them.
652
652
  if (isCliFailure(error) && (error.fields || error.code !== CLI_ERROR_CODE)) throw error;
653
+ // A source the data service reads was unavailable: retryable `source_unavailable`, in its own words.
654
+ if (isSourceUnavailableAnswer(error)) throw error;
653
655
  // A listing it cannot use says what to type instead; a name that opens nothing, what is close to it.
654
656
  if (error instanceof ListingArgError || error instanceof UnknownPaneFunctionError) ctx.fail(error.message, error.details || undefined);
655
657
  const message = error instanceof Error ? error.message : String(error);
@@ -24,7 +24,7 @@ import { unknownBloombergMarket } from "../../tickers/terminal-codes";
24
24
  import { notATickerWords } from "../company-name-hint";
25
25
  import type { MarketContext } from "../types";
26
26
  import { findWatchlist } from "../helpers";
27
- import { readWatchlistArgument } from "../../portfolio/collection-name";
27
+ import { readWatchlistArgument, watchlistMemberSymbol } from "../../portfolio/collection-name";
28
28
  import {
29
29
  buildPaneFunctionLookup,
30
30
  buildTemplateContext,
@@ -340,7 +340,7 @@ async function watchlistArgument(
340
340
  if (!watchlist) return null;
341
341
  const symbols = (await context.store.loadAllTickers())
342
342
  .filter((ticker) => ticker.metadata.watchlists.includes(watchlist.id))
343
- .map((ticker) => ticker.metadata.ticker);
343
+ .map((ticker) => watchlistMemberSymbol(ticker.metadata));
344
344
  if (symbols.length === 0) return null;
345
345
  const read = readWatchlistArgument(arg, watchlist, symbols, maximum);
346
346
  return { symbols: read.symbols, notes: [read.note] };