gloomberb 0.20.5 → 0.20.7

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 (185) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/package.json +2 -1
  4. package/src/api-client/data.ts +10 -2
  5. package/src/api-client/fund-facts.ts +20 -4
  6. package/src/api-client/hk-tenders.ts +59 -0
  7. package/src/api-client/index.ts +1 -0
  8. package/src/api-client/socket.ts +4 -4
  9. package/src/api-client/types/econ.ts +20 -2
  10. package/src/app.tsx +18 -13
  11. package/src/architecture/floating-promise-allowlist.json +313 -0
  12. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  13. package/src/cli/commands/market.ts +197 -57
  14. package/src/cli/commands/news-search.ts +22 -7
  15. package/src/cli/commands/overview.ts +12 -6
  16. package/src/cli/commands/search.ts +19 -3
  17. package/src/cli/commands/ticker.ts +3 -1
  18. package/src/cli/desktop-pane-shot.ts +61 -0
  19. package/src/cli/early-command.ts +2 -0
  20. package/src/cli/errors.ts +10 -1
  21. package/src/cli/fx-forward.ts +76 -12
  22. package/src/cli/fx-pair.ts +1 -1
  23. package/src/cli/fx-quote-rate.ts +23 -0
  24. package/src/cli/help.ts +1 -0
  25. package/src/cli/index-roots.ts +5 -4
  26. package/src/cli/index.ts +40 -3
  27. package/src/cli/known-gaps.ts +11 -8
  28. package/src/cli/listing-arg.ts +6 -4
  29. package/src/cli/options.ts +52 -3
  30. package/src/cli/output-file.ts +5 -3
  31. package/src/cli/pane-functions/catalog.ts +15 -0
  32. package/src/cli/pane-functions/dom.ts +4 -4
  33. package/src/cli/pane-functions/freshness.ts +38 -5
  34. package/src/cli/pane-functions/function-help.ts +4 -4
  35. package/src/cli/pane-functions/headless.ts +9 -4
  36. package/src/cli/pane-functions/index.ts +6 -4
  37. package/src/cli/pane-functions/resolver.ts +2 -2
  38. package/src/cli/pane-functions/screenshot-assessment.ts +16 -4
  39. package/src/cli/quote-answer.ts +57 -1
  40. package/src/cli/result.ts +38 -2
  41. package/src/cli/spreadsheet-hint.ts +7 -3
  42. package/src/cli/treasury-yields.ts +5 -3
  43. package/src/components/chart/composite/legend.tsx +40 -2
  44. package/src/components/command-bar/workflow/tickers.ts +2 -2
  45. package/src/components/data-table/view.tsx +9 -2
  46. package/src/components/ui/data-table/opentui/index.tsx +11 -4
  47. package/src/components/ui/data-table/opentui/model.ts +8 -6
  48. package/src/components/ui/data-table/types.ts +6 -1
  49. package/src/components/ui/table-layout.ts +38 -1
  50. package/src/docs/snapshot.json +58 -19
  51. package/src/i18n/es.ts +2 -0
  52. package/src/i18n/ja.ts +2 -0
  53. package/src/i18n/ko.ts +2 -0
  54. package/src/i18n/zh-cn.ts +2 -0
  55. package/src/i18n/zh-tw.ts +2 -0
  56. package/src/market-data/market/change-basis.ts +57 -12
  57. package/src/market-data/market/dated-previous-close.ts +184 -10
  58. package/src/market-data/market/freshness.ts +18 -6
  59. package/src/market-data/market/status.ts +9 -1
  60. package/src/market-data/published-nse-sessions.ts +16 -1
  61. package/src/market-data/quotes/contributions.ts +2 -0
  62. package/src/market-data/quotes/freshness.ts +15 -0
  63. package/src/market-data/quotes/listing-enterprise-value.ts +50 -0
  64. package/src/plugins/builtin/alerts/alert-engine.ts +15 -0
  65. package/src/plugins/builtin/alerts/cli.ts +22 -9
  66. package/src/plugins/builtin/alerts/headless.ts +1 -1
  67. package/src/plugins/builtin/alerts/index.tsx +5 -1
  68. package/src/plugins/builtin/alerts/metric-command.ts +1 -1
  69. package/src/plugins/builtin/alerts/metric-data.ts +15 -2
  70. package/src/plugins/builtin/backtest/headless.ts +1 -1
  71. package/src/plugins/builtin/cds/model.ts +0 -6
  72. package/src/plugins/builtin/chart-composer/formula.ts +16 -3
  73. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -0
  74. package/src/plugins/builtin/chart-composer/headless.ts +2 -1
  75. package/src/plugins/builtin/chart-composer/presets.ts +1 -0
  76. package/src/plugins/builtin/cloud/askg/pane.tsx +55 -13
  77. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +20 -7
  78. package/src/plugins/builtin/credit-boards/client.ts +8 -0
  79. package/src/plugins/builtin/credit-boards/headless.ts +4 -1
  80. package/src/plugins/builtin/credit-boards/model.ts +58 -4
  81. package/src/plugins/builtin/credit-boards/series.ts +63 -6
  82. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +3 -2
  83. package/src/plugins/builtin/credit-conditions/headless.ts +24 -6
  84. package/src/plugins/builtin/credit-conditions/index.tsx +1 -1
  85. package/src/plugins/builtin/credit-conditions/model.ts +12 -6
  86. package/src/plugins/builtin/credit-conditions/series.ts +2 -1
  87. package/src/plugins/builtin/econ/calendar-model.ts +41 -7
  88. package/src/plugins/builtin/econ/calendar-source.ts +7 -1
  89. package/src/plugins/builtin/econ/index.tsx +41 -8
  90. package/src/plugins/builtin/econ/types.ts +3 -0
  91. package/src/plugins/builtin/fixed-income/index.tsx +2 -0
  92. package/src/plugins/builtin/fx-matrix/index.tsx +44 -14
  93. package/src/plugins/builtin/help/keybindings-editor.tsx +6 -2
  94. package/src/plugins/builtin/holders/fund-holders.ts +22 -1
  95. package/src/plugins/builtin/holders/headless.ts +5 -4
  96. package/src/plugins/builtin/holders/pane.tsx +7 -3
  97. package/src/plugins/builtin/holders/report-header.ts +23 -0
  98. package/src/plugins/builtin/members/client.ts +1 -1
  99. package/src/plugins/builtin/members/headless.ts +2 -0
  100. package/src/plugins/builtin/members/model.ts +10 -8
  101. package/src/plugins/builtin/members/pane.tsx +4 -1
  102. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +5 -2
  103. package/src/plugins/builtin/portfolio-list/cli/render.ts +86 -26
  104. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -1
  105. package/src/plugins/builtin/portfolio-list/headless.ts +2 -1
  106. package/src/plugins/builtin/portfolio-list/income.ts +46 -22
  107. package/src/plugins/builtin/portfolio-list/pane/data.ts +16 -6
  108. package/src/plugins/builtin/portfolio-list/pane/index.tsx +5 -4
  109. package/src/plugins/builtin/portfolio-list/use-throttled-ticker-order.ts +40 -3
  110. package/src/plugins/builtin/research/headless-schema.ts +4 -3
  111. package/src/plugins/builtin/research/relative-valuation-columns.ts +145 -47
  112. package/src/plugins/builtin/research/relative-valuation-currency.ts +31 -0
  113. package/src/plugins/builtin/research/relative-valuation-headless.ts +25 -8
  114. package/src/plugins/builtin/research/relative-valuation-model.ts +40 -9
  115. package/src/plugins/builtin/research/relative-valuation-pane.tsx +3 -2
  116. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -2
  117. package/src/plugins/builtin/sec/fund-facts.ts +25 -5
  118. package/src/plugins/builtin/shared/report-freshness.ts +15 -6
  119. package/src/plugins/builtin/supply-chain/model.ts +18 -6
  120. package/src/plugins/builtin/thirteenf/api.ts +47 -4
  121. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +8 -7
  122. package/src/plugins/builtin/ticker-detail/data-panes/history-bars.ts +8 -5
  123. package/src/plugins/builtin/ticker-detail/financials/model.ts +6 -2
  124. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +1 -1
  125. package/src/plugins/builtin/ticker-detail/headless.ts +6 -4
  126. package/src/plugins/builtin/treasury-auctions/cache.ts +36 -2
  127. package/src/plugins/builtin/treasury-auctions/headless.ts +42 -4
  128. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +126 -0
  129. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +347 -0
  130. package/src/plugins/builtin/treasury-auctions/hk.ts +363 -0
  131. package/src/plugins/builtin/treasury-auctions/index.tsx +14 -1
  132. package/src/plugins/builtin/treasury-auctions/model.ts +16 -8
  133. package/src/plugins/builtin/treasury-auctions/pane.tsx +45 -21
  134. package/src/portfolio/collection-name.ts +22 -0
  135. package/src/portfolio/column-values.ts +3 -0
  136. package/src/portfolio/valuation-basis.ts +23 -1
  137. package/src/renderers/dom/data-table/frozen-column.ts +3 -1
  138. package/src/renderers/dom/data-table/index.tsx +27 -9
  139. package/src/renderers/dom/data-table/row.tsx +2 -0
  140. package/src/renderers/electrobun/bun/desktop/backend.ts +27 -24
  141. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +3 -3
  142. package/src/renderers/electrobun/bun/desktop/snapshot-commit.ts +77 -0
  143. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  144. package/src/renderers/electrobun/view/backend-rpc.ts +3 -0
  145. package/src/renderers/electrobun/view/desktop/window/bridge.ts +3 -0
  146. package/src/sources/gloomberb-cloud/normalizers.ts +9 -5
  147. package/src/sources/provider-router/cache.ts +3 -1
  148. package/src/state/hooks/quote-streaming.ts +14 -6
  149. package/src/sync/controller.ts +17 -2
  150. package/src/sync/other-window-tabs.ts +32 -1
  151. package/src/sync/react.ts +4 -4
  152. package/src/tickers/instrument-kind.ts +22 -1
  153. package/src/tickers/search/index.ts +5 -0
  154. package/src/tickers/terminal-codes.ts +17 -5
  155. package/src/time-series/bar-spacing.ts +33 -0
  156. package/src/time-series/base-series.ts +21 -3
  157. package/src/time-series/chart-bounds.ts +31 -0
  158. package/src/time-series/field-catalog.ts +17 -0
  159. package/src/time-series/fundamentals/current-valuation.ts +244 -0
  160. package/src/time-series/fundamentals/historical-valuation.ts +99 -0
  161. package/src/time-series/fundamentals/metric-ids.ts +61 -0
  162. package/src/time-series/fundamentals/period-points.ts +104 -0
  163. package/src/time-series/fundamentals/quarterly-ttm.ts +220 -0
  164. package/src/time-series/fundamentals/series.ts +164 -0
  165. package/src/time-series/fundamentals/source-statements.ts +177 -0
  166. package/src/time-series/fundamentals/statement-fields.ts +154 -0
  167. package/src/time-series/fundamentals/statement-merge.ts +124 -0
  168. package/src/time-series/fundamentals/statement.ts +114 -0
  169. package/src/time-series/fundamentals/valuation-multiples.ts +50 -0
  170. package/src/time-series/fundamentals.ts +18 -1275
  171. package/src/time-series/ice-credit.ts +32 -6
  172. package/src/time-series/resolve.ts +9 -5
  173. package/src/time-series/session-bar.ts +78 -9
  174. package/src/time-series/studies/formula.ts +53 -10
  175. package/src/time-series/studies/pair.ts +18 -7
  176. package/src/time-series/studies/units.ts +49 -2
  177. package/src/time-series/types.ts +12 -0
  178. package/src/types/desktop-window.ts +2 -0
  179. package/src/types/financials.ts +15 -0
  180. package/src/types/headless.ts +8 -0
  181. package/src/utils/cli-output.ts +6 -3
  182. package/src/utils/debug-log.ts +29 -0
  183. package/src/utils/ebitda.ts +128 -0
  184. package/src/utils/format.ts +1 -1
  185. package/src/utils/shell-word.ts +13 -0
@@ -70,6 +70,7 @@ import { listingSuffixCandidate, listingSuffixVenue, tickerHasListingSuffix } fr
70
70
  import { isCurrencyPairListing } from "../utils/fx-market-hours";
71
71
  import { coinElsewhereNote, notTheCoinNote } from "./commands/crypto-hints";
72
72
  import { fredSeriesArgument, fredSeriesNotListing } from "../series/fred-argument";
73
+ import { commandWord } from "../utils/shell-word";
73
74
 
74
75
  /** The `--exchange` option of every command that takes a ticker. */
75
76
  export const EXCHANGE_OPTION = {
@@ -654,9 +655,9 @@ interface OtherListingsMessage {
654
655
  * --range 5Y` keeps the options. Null where the request names listings alone.
655
656
  */
656
657
  function retryCommand(request: Pick<ListingDataRequest, "command" | "retry">, key: string): string | null {
657
- if (request.retry !== undefined) return request.retry?.(key) ?? null;
658
+ if (request.retry !== undefined) return request.retry?.(commandWord(key)) ?? null;
658
659
  const [command, ...options] = request.command.split(" ");
659
- return ["gloom", command, key, ...options].join(" ");
660
+ return ["gloom", command, commandWord(key), ...options].join(" ");
660
661
  }
661
662
 
662
663
  /**
@@ -1745,8 +1746,9 @@ export function listingFields(saved: Pick<SavedListingName, "key" | "symbol" | "
1745
1746
 
1746
1747
  /** The listing a saved ticker row is, as a collection command names it after adding or removing it. */
1747
1748
  export function savedListingName(ticker: TickerRecord): SavedListingName {
1748
- const { symbol } = parsePublicTickerKey(ticker.metadata.ticker);
1749
- 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 || "";
1750
1752
  const key = exchange ? `${symbol}:${exchange}` : symbol;
1751
1753
  // A row saved without a company carries its symbol as the name.
1752
1754
  const typed = ticker.metadata.name?.trim();
@@ -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();
@@ -27,8 +27,8 @@ const DOM_EVERY_ROW =
27
27
  const DOM_WHOLE_PANE =
28
28
  "The pane was grown to fit the page it has open, so all of its text is returned.";
29
29
 
30
- /** The sign-in wall's buttons, which a rendered view reads as words: `Log in ↵ Sign up free`. */
31
- const SIGN_IN_WALL_BUTTONS = /\s*\b(?:Log in|Sign up free|Resend Verification Email)(?:\s*\u21B5)?(?=\s|$)/g;
30
+ /** The sign-in wall's buttons, which a rendered view reads as words, with the key that presses one: `Log in ↩ Sign up free`. */
31
+ const SIGN_IN_WALL_BUTTONS = /\s*\b(?:Log in|Sign up free|Resend Verification Email)(?:\s*[\u21A9\u21B5])?(?=\s|$)/g;
32
32
 
33
33
  /** Whether the wall asks for the account's email to be verified, not for a sign-in. */
34
34
  function asksToVerifyEmail(visibleText: string): boolean {
@@ -42,8 +42,8 @@ function asksToVerifyEmail(visibleText: string): boolean {
42
42
  function signInWallText(visibleText: string): string {
43
43
  const headline = visibleText.replace(SIGN_IN_WALL_BUTTONS, "").trim();
44
44
  const needs = asksToVerifyEmail(visibleText)
45
- ? "Requires a verified email on your Gloom account; resend the verification email in the app."
46
- : "Requires a free Gloom sign-in: log in or sign up in the app.";
45
+ ? "Requires a verified email on your Gloom account: open the app (gloom) and resend the verification email from the command bar (Ctrl+P, Resend Verification Email)."
46
+ : "Requires a free Gloom sign-in: open the app (gloom) and log in or sign up free from the command bar (Ctrl+P, Log In or Sign Up); this command then reads with that session.";
47
47
  return headline ? `${headline} ${needs}` : needs;
48
48
  }
49
49
 
@@ -66,6 +66,13 @@ export interface ReportFreshness {
66
66
  /** When only some rows are stale: how many, of the rows that say whether they are... */
67
67
  staleCount?: number;
68
68
  observationCount?: number;
69
+ /**
70
+ * How many of those rows are at a nominal price, nothing having traded
71
+ * (`nominal`): the venue's price for its latest session, counted apart
72
+ * from stale rows. The status line reads `1 of 3 nominal`, or `nominal`
73
+ * when every row is.
74
+ */
75
+ nominalCount?: number;
69
76
  /** ...and what the rest are. */
70
77
  feed?: "live" | "delayed";
71
78
  basis?: string;
@@ -195,9 +202,11 @@ interface FeedSignals {
195
202
  minDelayMinutes?: number;
196
203
  /** A record-wide stale flag (metadata), read only when no row says whether it is stale. */
197
204
  stale: boolean;
198
- /** Rows and series that carry a `stale` flag, and the times of those that are stale. */
205
+ /** Rows and series that carry a `stale` flag, and the times of those that are stale... */
199
206
  flagged: number;
200
207
  staleTimes: Array<ReportTime | null>;
208
+ /** ...and how many of them are at a nominal price instead (`nominal`). */
209
+ nominal: number;
201
210
  /** Rows that name the venue whose sessions they follow (`sessionExchange`), with their time. */
202
211
  sessions: SessionObservation[];
203
212
  }
@@ -244,7 +253,7 @@ function newestUnitRelease(observations: Observations, asOf: ReportTime): UnitRe
244
253
  }
245
254
 
246
255
  function emptySignals(): FeedSignals {
247
- return { live: false, delayed: false, stale: false, flagged: 0, staleTimes: [], sessions: [] };
256
+ return { live: false, delayed: false, stale: false, flagged: 0, staleTimes: [], nominal: 0, sessions: [] };
248
257
  }
249
258
 
250
259
  function readFeedSignals(record: Record<string, unknown>, signals: FeedSignals): void {
@@ -271,11 +280,17 @@ function readSession(record: Record<string, unknown>, time: ReportTime | null, s
271
280
  });
272
281
  }
273
282
 
274
- /** A row's or series' own stale flag; worst of across them, counted so a partly stale board says how much. */
283
+ /**
284
+ * A row's or series' own stale flag; worst of across them, counted so a partly
285
+ * stale board says how much. A row at a nominal price (`nominal`: an untraded
286
+ * counter's, whose last trade is old) is its venue's latest price, counted as
287
+ * nominal rather than stale.
288
+ */
275
289
  function readUnitStale(record: Record<string, unknown>, time: ReportTime | null, signals: FeedSignals): void {
276
290
  if (typeof record.stale !== "boolean") return;
277
291
  signals.flagged += 1;
278
- if (record.stale) signals.staleTimes.push(time);
292
+ if (record.nominal === true) signals.nominal += 1;
293
+ else if (record.stale) signals.staleTimes.push(time);
279
294
  }
280
295
 
281
296
  function observedTime(record: Record<string, unknown>, now: number, keys: readonly string[] = OBSERVATION_KEYS): ReportTime | null {
@@ -602,6 +617,7 @@ function resolveFreshness({ declared, signals, observations, now }: FreshnessInp
602
617
  ...(minDelayMinutes != null && minDelayMinutes > 0 ? { minDelayMinutes } : {}),
603
618
  ...(status === "stale" && staleAt ? { ageMinutes: Math.max(0, Math.floor((now - staleAt.time) / 60_000)) } : {}),
604
619
  ...(partial ?? {}),
620
+ ...(signals.nominal > 0 ? { nominalCount: signals.nominal, observationCount: signals.flagged } : {}),
605
621
  ...(status === "not-a-feed" && declared.basis ? { basis: declared.basis } : {}),
606
622
  ...(periodicity ? { periodicity } : {}),
607
623
  ...(periodToDate && !declaredAsOf ? { periodToDate: { period: periodToDate.period, ...(periodToDate.through ? { through: isoTime(periodToDate.through) } : {}) } } : {}),
@@ -824,8 +840,25 @@ export function staleRowsText(freshness: Pick<ReportFreshness, "staleCount" | "o
824
840
  return `${short ? freshness.staleCount : `${freshness.staleCount} of ${freshness.observationCount}`} stale`;
825
841
  }
826
842
 
827
- /** `short` counts stale rows without their total (`2 stale`), for a narrow capture. */
843
+ /**
844
+ * How many rows are at a nominal price: `nominal` when all are, `1 of 3
845
+ * nominal` (`1 nominal` when `short`) when some are. Null when none is.
846
+ */
847
+ function nominalRowsText(freshness: Pick<ReportFreshness, "nominalCount" | "observationCount">, short = false): string | null {
848
+ const { nominalCount: count, observationCount: total } = freshness;
849
+ if (!count || total == null) return null;
850
+ if (count >= total) return "nominal";
851
+ return `${short ? count : `${count} of ${total}`} nominal`;
852
+ }
853
+
854
+ /** `short` counts stale and nominal rows without their total (`2 stale`), for a narrow capture. */
828
855
  function statusText(freshness: ReportFreshness, short = false): string {
856
+ const nominal = nominalRowsText(freshness, short);
857
+ const feed = feedStatusText(freshness, short);
858
+ return nominal ? [feed, nominal].filter(Boolean).join(", ") : feed;
859
+ }
860
+
861
+ function feedStatusText(freshness: ReportFreshness, short: boolean): string {
829
862
  switch (freshness.status) {
830
863
  case "live":
831
864
  return "live";
@@ -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 (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).",
1004
- usage: ["AUCT", "AUCT 10Y", "AUCT 91282CRF0", "AUCT 7Y --history-days 3650 --view after --sort btc-pctl"],
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] };
@@ -53,20 +53,32 @@ export function shotStatusIssues(
53
53
  /**
54
54
  * For a pane that grows to fit its rows, the rows its table reports (every
55
55
  * one, `reportEveryRow`) and how many of them the image shows, by key;
56
- * section headers count in neither. Null for any other pane, or a table that
57
- * reports only what is drawn.
56
+ * section headers count in neither. For any other pane whose tables hold more
57
+ * rows than the image draws, the rows drawn of all they hold ("36 of 76").
58
+ * Null when the image holds every row, or no table says how many it holds.
58
59
  */
59
60
  export function shotTableRows(
60
61
  resolved: Pick<ResolvedPaneFunction, "pane" | "instance">,
61
- render: Pick<DesktopPaneShotRenderResult, "rows" | "reportRows">,
62
+ render: Pick<DesktopPaneShotRenderResult, "rows" | "reportRows" | "tableRowTotals">,
62
63
  ): { shown: number; total: number } | null {
63
- if (!paneFitsRows(resolved) || !render.reportRows?.length) return null;
64
+ if (!paneFitsRows(resolved) || !render.reportRows?.length) return cutTableRows(render);
64
65
  const reported = render.reportRows.filter((row) => !row.section && row.key);
65
66
  if (reported.length === 0) return null;
66
67
  const drawn = new Set(render.rows.flatMap((row) => row.key ? [`${row.tableIndex}:${row.key}`] : []));
67
68
  return { shown: reported.filter((row) => drawn.has(`${row.tableIndex}:${row.key}`)).length, total: reported.length };
68
69
  }
69
70
 
71
+ /** The rows drawn of all the visible tables hold, for the tables that say how many; null when nothing is left out. */
72
+ function cutTableRows(render: Pick<DesktopPaneShotRenderResult, "rows" | "tableRowTotals">): { shown: number; total: number } | null {
73
+ let shown = 0, total = 0;
74
+ for (const [tableIndex, rows] of (render.tableRowTotals ?? []).entries()) {
75
+ if (rows === null) continue;
76
+ total += rows;
77
+ shown += render.rows.filter((row) => row.tableIndex === tableIndex).length;
78
+ }
79
+ return total > shown ? { shown, total } : null;
80
+ }
81
+
70
82
  /** What a rendered capture shows, and whether it is fit to use. */
71
83
  export function assessPaneScreenshot(
72
84
  resolved: ResolvedPaneFunction,
@@ -66,6 +66,12 @@ export interface QuoteAnswer {
66
66
  /** Why there is no quote, when there is more to say than the source's own error. */
67
67
  failure?: { message: string; details?: string; oneLine: string };
68
68
  notes: string[];
69
+ /**
70
+ * Lines about another listing than the row's, printed under the table
71
+ * rather than as warnings on it: the HKEX listing a bare TWSE code is the
72
+ * code of too ("00700: for HKEX use 700.HK").
73
+ */
74
+ footnotes?: string[];
69
75
  }
70
76
 
71
77
  /**
@@ -108,7 +114,12 @@ export async function answerQuote(
108
114
  const venue = choice.length > 0 ? null : bareListingNote(listing, result.quote);
109
115
  // A row saved as 247540:KRX is quoted from KOSDAQ, the board it trades on.
110
116
  const board = tradingBoardNote(listing, result.quote);
111
- return { result, listing, notes: [...choice, venue ?? [], board ?? [], also(result.quote), currencyCodeNote(listing, result.quote) ?? []].flat() };
117
+ const hongKong = await hongKongCodeNote(listing, result.quote, market);
118
+ return {
119
+ result, listing,
120
+ notes: [...choice, venue ?? [], board ?? [], also(result.quote), currencyCodeNote(listing, result.quote) ?? []].flat(),
121
+ ...hongKong ? { footnotes: [hongKong] } : {},
122
+ };
112
123
  }
113
124
  // No answer from the data service: no venue lookup or other listing would get one either.
114
125
  if (isNetworkFailure(result.error)) return { result, listing, notes: [] };
@@ -147,6 +158,10 @@ export async function answerQuote(
147
158
  listing.exchange ? null : knownGapForTicker(listing.symbol),
148
159
  ].filter((line): line is string => !!line);
149
160
  if (!other && tryLines.length === 0) {
161
+ // ^GSPC typed in Windows' cmd.exe arrives as GSPC, the shell taking ^ for its escape character: said once no company
162
+ // of that name and no listing abroad answers for it, so a symbol listed abroad is still quoted. A known root (VIX) has its own line.
163
+ const caret = root ? null : await caretIndexLine(listing, result, market);
164
+ if (caret) return { result, listing, failure: { message: caret, oneLine: caret }, notes: [] };
150
165
  return await answerCompanyName(result, listing, market, request, refresh, datesChangeBasis)
151
166
  ?? { result: await withCurrencyPairHint(result, market), listing, notes: [] };
152
167
  }
@@ -276,6 +291,47 @@ export async function requireQuotedListing(
276
291
  return { listing: answer.listing, quote, notes: [...answer.notes, ...notUs ? [notUs] : []] };
277
292
  }
278
293
 
294
+ /** A bare symbol that may be an index's without its ^: letters, then letters or digits. */
295
+ const CARETLESS_INDEX = /^[A-Z][A-Z0-9]{1,9}$/;
296
+
297
+ /**
298
+ * "Not a ticker: GSPC. Did you mean ^GSPC (S&P 500)? Try "^GSPC"." for a
299
+ * bare symbol that is not a ticker while its ^ form is an index: cmd.exe
300
+ * takes ^ for its escape character and passes `gloom quote ^GSPC` on as
301
+ * GSPC, and search would offer Goldman's preferreds for it. Null for any
302
+ * other symbol, a named venue, and when the ^ form quotes no index.
303
+ */
304
+ async function caretIndexLine(listing: CliListing, result: QuoteBatchResult, market: MarketContext): Promise<string | null> {
305
+ if (listing.exchange || listing.saved || !CARETLESS_INDEX.test(listing.symbol)) return null;
306
+ const index = `^${listing.symbol}`;
307
+ const quote = await Promise.resolve().then(() => market.dataProvider.getQuote(index, ""))
308
+ .catch(logFailure("cli.quote-answer", "Quote a symbol's index form failed", null));
309
+ if (!quote || quote.instrumentType?.trim().toUpperCase() !== "INDEX") return null;
310
+ const said = notATickerSymbol(errorMessage(result.error) ?? "") ? `Not a ticker: ${listing.symbol}.` : `${listing.symbol} has no quote.`;
311
+ return `${said} Did you mean ${index}${quote.name ? ` (${quote.name})` : ""}? Try "${index}".`;
312
+ }
313
+
314
+ /** Five digits with a leading zero: a TWSE fund's code (00700), and how HKEXnews prints a Hong Kong one (00700 is 0700). */
315
+ const FIVE_DIGIT_CODE = /^0\d{4}$/;
316
+
317
+ /**
318
+ * A bare five-digit code quoted on another venue that HKEX lists too, as its
319
+ * own code without the leading zeros: 00700 is Fubon's Hang Seng China
320
+ * Enterprises ETF on TWSE and Tencent's 0700 on HKEX. The row stays the
321
+ * other venue's; the note names the HKEX listing, "00700: for HKEX use 700.HK
322
+ * (Tencent Holdings Limited)". Null for any other symbol, a named or saved
323
+ * listing, and a code HKEX does not list.
324
+ */
325
+ async function hongKongCodeNote(listing: CliListing, quote: Quote, market: MarketContext): Promise<string | null> {
326
+ if (listing.exchange || listing.saved || !FIVE_DIGIT_CODE.test(listing.symbol)) return null;
327
+ if (canonicalExchange(quote.listingExchangeName || quote.exchangeName) === "HKEX") return null;
328
+ const code = String(Number(listing.symbol));
329
+ const hongKong = await Promise.resolve().then(() => market.dataProvider.getQuote(code.padStart(4, "0"), "HKEX"))
330
+ .catch(logFailure("cli.quote-answer", "Quote a code's HKEX listing failed", null));
331
+ if (!hongKong || canonicalExchange(hongKong.listingExchangeName || hongKong.exchangeName) !== "HKEX") return null;
332
+ return `${listing.symbol}: for HKEX use ${code}.HK${hongKong.name ? ` (${hongKong.name})` : ""}`;
333
+ }
334
+
279
335
  /**
280
336
  * A symbol written like a currency pair that is not a ticker (USD_NGN, as some
281
337
  * FX feeds write a pair) names the listing `gloom search` finds nearest to
package/src/cli/result.ts CHANGED
@@ -3,6 +3,7 @@ import {
3
3
  cliPlainEnabled,
4
4
  cliStyles,
5
5
  cliTerminalWidth,
6
+ renderForFile,
6
7
  renderStats,
7
8
  renderTable,
8
9
  statValueWidth,
@@ -13,6 +14,7 @@ import {
13
14
  type CliTableColumn,
14
15
  } from "../utils/cli-output";
15
16
  import { serializeCsv } from "../utils/csv";
17
+ import { logFailure } from "../utils/log-failure";
16
18
  import { formatUtcTime, isEpochMilliseconds, isZonedIsoDateTime } from "../utils/utc-time";
17
19
  import { formatFreshnessLine, withSavedCopy, type ReportFreshness } from "./pane-functions/freshness";
18
20
  import { withSearchHints, type FredSeriesCheck } from "./not-a-ticker";
@@ -623,6 +625,19 @@ function renderTextRows<T, Row extends Record<string, unknown>>(
623
625
  : renderTextTable(rows as Row[], columns, renderOptions.rowNote);
624
626
  }
625
627
 
628
+ /** What `printCliResult` drew for the file `--output` names, since `takeCliFileExport` last took it. */
629
+ let fileExport: string[] = [];
630
+
631
+ /**
632
+ * The export a command printed for its `--output` file, or null when it
633
+ * printed none: the text the file is written with (dispatchCli).
634
+ */
635
+ export function takeCliFileExport(): string | null {
636
+ const taken = fileExport.filter(Boolean);
637
+ fileExport = [];
638
+ return taken.length > 0 ? taken.join("\n") : null;
639
+ }
640
+
626
641
  /** Settles once the result `printCliResult` last wrote has left the process: a pipe can hold it back. */
627
642
  let stdoutWritten: Promise<void> = Promise.resolve();
628
643
 
@@ -634,6 +649,22 @@ export function cliOutputWritten(): Promise<void> {
634
649
  return stdoutWritten;
635
650
  }
636
651
 
652
+ /** How long a command whose report is out waits for reads it stopped waiting for before it exits without them. */
653
+ const LEFT_BEHIND_EXIT_MS = 500;
654
+
655
+ /**
656
+ * For a command whose report is out while reads it gave up on are not
657
+ * (dividends past their deadline): exits once the output has left the
658
+ * process, not when the last of them answers or times out, which held a
659
+ * cold `portfolio show` open for fifteen seconds after it printed. Unref'd,
660
+ * so a process with nothing left exits first, with its own code.
661
+ */
662
+ export function exitLeavingReadsBehind(): void {
663
+ setTimeout(() => {
664
+ cliOutputWritten().then(() => process.exit()).catch(logFailure("cli.result", "Exit after the report failed"));
665
+ }, LEFT_BEHIND_EXIT_MS).unref();
666
+ }
667
+
637
668
  export function printCliResult<T, Row extends Record<string, unknown> = Record<string, unknown>>(
638
669
  result: CliResult<T>,
639
670
  options: CliGlobalOptions,
@@ -644,13 +675,18 @@ export function printCliResult<T, Row extends Record<string, unknown> = Record<s
644
675
  if (options.quiet && options.format === "text") return;
645
676
  // JSON keeps the router's own words; everything else is for a person, so a "Not a ticker" gets its hint.
646
677
  const hinted = (text: string) => options.format === "json" ? text : withSearchHints(text, args, isFredSeries);
647
- const serialized = hinted(serializeCliResult(result, options, renderOptions));
678
+ // An export `--output` names is drawn for the file (no colour), and held for the command's end to write.
679
+ const toFile = options.output !== undefined && options.format !== "text";
680
+ const serialized = hinted(toFile
681
+ ? renderForFile(() => serializeCliResult(result, options, renderOptions))
682
+ : serializeCliResult(result, options, renderOptions));
648
683
  // A CSV's closing source and note lines go to stderr with the warnings: in the file they are rows of junk to a spreadsheet.
649
684
  const { csv, footer } = options.format === "csv" ? splitCsvFooter(serialized) : { csv: serialized, footer: [] };
650
685
  const output = csv;
686
+ if (toFile) fileExport.push(output);
651
687
  // Bun's console writer can truncate a large pipe write after stdout has been
652
688
  // initialized. The stream queues the remaining bytes until the reader drains.
653
- if (output && !process.stdout.write(`${output}\n`)) {
689
+ else if (output && !process.stdout.write(`${output}\n`)) {
654
690
  stdoutWritten = new Promise((resolve) => process.stdout.once("drain", () => resolve()));
655
691
  }
656
692
  // JSON carries warnings in its envelope. Text, CSV and NDJSON are only the