@gloom-sh/terminal 0.20.4 → 0.20.5

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 (217) hide show
  1. package/README.md +2 -0
  2. package/bin/gloom +9 -0
  3. package/bin/without-bun.cjs +98 -0
  4. package/package.json +3 -1
  5. package/src/api-client/data.ts +138 -35
  6. package/src/api-client/types/econ.ts +12 -0
  7. package/src/api-client/yield-curves.ts +1 -1
  8. package/src/app/global-shortcuts.ts +4 -1
  9. package/src/app/keybindings/actions.ts +6 -0
  10. package/src/app/keybindings/config.ts +2 -1
  11. package/src/app/keybindings/index.ts +1 -0
  12. package/src/app/keybindings/labels.ts +6 -1
  13. package/src/app/keybindings/resolve.ts +23 -4
  14. package/src/app/keybindings/terminal-keys.ts +35 -0
  15. package/src/app/pane-runtime/index.tsx +2 -2
  16. package/src/app/pane-runtime/ticker-open-runtime.ts +68 -40
  17. package/src/architecture/ui-literals-allowlist.json +1 -1
  18. package/src/capabilities/chart-series.ts +27 -1
  19. package/src/cli/commands/keybindings.ts +5 -5
  20. package/src/cli/commands/market.ts +78 -21
  21. package/src/cli/commands/news-search.ts +59 -7
  22. package/src/cli/commands/overview.ts +16 -1
  23. package/src/cli/commands/remote.ts +16 -17
  24. package/src/cli/commands/system.ts +1 -1
  25. package/src/cli/fx-forward.ts +25 -7
  26. package/src/cli/glossary.ts +19 -5
  27. package/src/cli/history-rows.ts +5 -3
  28. package/src/cli/known-gaps.ts +27 -1
  29. package/src/cli/listing-arg.ts +11 -1
  30. package/src/cli/name-entries.ts +5 -1
  31. package/src/cli/not-a-ticker.ts +4 -0
  32. package/src/cli/pane-functions/function-help.ts +2 -2
  33. package/src/components/command-bar/pane-settings.ts +2 -2
  34. package/src/components/command-bar/routes/root/results.ts +6 -2
  35. package/src/components/input-search-bar.tsx +9 -2
  36. package/src/components/layout/pane/header.tsx +2 -0
  37. package/src/components/layout/shell/pane/capture.ts +4 -1
  38. package/src/components/layout/status-bar.tsx +6 -1
  39. package/src/components/onboarding/first-run-workspace.ts +44 -2
  40. package/src/components/onboarding/onboarding-frame.tsx +11 -2
  41. package/src/components/onboarding/onboarding-keyboard.ts +16 -0
  42. package/src/components/onboarding/onboarding-wizard.tsx +8 -8
  43. package/src/components/onboarding/portfolio-step/positions-panel.tsx +62 -1
  44. package/src/components/onboarding/use-onboarding-progress.ts +12 -4
  45. package/src/components/pane-settings-dialog/desktop.tsx +2 -2
  46. package/src/components/pane-settings-dialog/tui.tsx +2 -2
  47. package/src/components/pane-settings-dialog/value.ts +6 -0
  48. package/src/components/pane-settings-dialog.tsx +3 -3
  49. package/src/components/reader/detail-reader.tsx +4 -0
  50. package/src/components/ui/index.ts +1 -1
  51. package/src/components/ui/page-stack-view.tsx +3 -0
  52. package/src/components/ui/pane-link-chip.tsx +269 -54
  53. package/src/components/ui/query-bar.tsx +2 -1
  54. package/src/components/ui/tabs.tsx +97 -19
  55. package/src/core/state/app/layout-reducer.ts +7 -0
  56. package/src/core/state/app/layout.ts +44 -7
  57. package/src/core/state/app/state.ts +1 -1
  58. package/src/core/state/app/types.ts +22 -2
  59. package/src/docs/snapshot.json +27 -10
  60. package/src/market-data/depositary-pair.ts +5 -3
  61. package/src/market-data/market/dated-previous-close.ts +94 -15
  62. package/src/market-data/market/status.ts +17 -1
  63. package/src/plugins/builtin/analytics/risk-client.ts +10 -4
  64. package/src/plugins/builtin/analytics/risk-episodes.ts +5 -4
  65. package/src/plugins/builtin/analytics/risk-headless.ts +4 -2
  66. package/src/plugins/builtin/analytics/risk-sectors.ts +91 -0
  67. package/src/plugins/builtin/awards/index.tsx +1 -1
  68. package/src/plugins/builtin/buildout/index.tsx +1 -0
  69. package/src/plugins/builtin/catalysts/index.tsx +2 -2
  70. package/src/plugins/builtin/cds/headless.ts +4 -0
  71. package/src/plugins/builtin/chart-composer/headless.ts +2 -1
  72. package/src/plugins/builtin/chart-composer/index.tsx +1 -0
  73. package/src/plugins/builtin/chat/content/composer.tsx +5 -4
  74. package/src/plugins/builtin/chat/content/index.tsx +12 -2
  75. package/src/plugins/builtin/chat/content/layout-metrics.ts +3 -3
  76. package/src/plugins/builtin/chat/content/open-targets.ts +3 -3
  77. package/src/plugins/builtin/chat/layout.ts +5 -2
  78. package/src/plugins/builtin/chat/message/pane-chip.tsx +61 -40
  79. package/src/plugins/builtin/chat/message/terminal.tsx +13 -15
  80. package/src/plugins/builtin/chat/pane-links/previews.ts +51 -5
  81. package/src/plugins/builtin/chat/pane-links/share-card.ts +36 -0
  82. package/src/plugins/builtin/cloud/askg/tool-display.ts +1 -0
  83. package/src/plugins/builtin/cloud/terminal-relay/redact.ts +5 -3
  84. package/src/plugins/builtin/commodity-balances/index.tsx +1 -0
  85. package/src/plugins/builtin/company-attention/index.tsx +1 -1
  86. package/src/plugins/builtin/company-kpis/headless.ts +3 -1
  87. package/src/plugins/builtin/company-kpis/index.tsx +2 -2
  88. package/src/plugins/builtin/cot/index.tsx +1 -1
  89. package/src/plugins/builtin/cpi/index.tsx +1 -1
  90. package/src/plugins/builtin/crypto-board/index.tsx +1 -0
  91. package/src/plugins/builtin/dividend-yield/index.tsx +1 -0
  92. package/src/plugins/builtin/doe/index.tsx +1 -1
  93. package/src/plugins/builtin/earnings-calls/headless.ts +5 -1
  94. package/src/plugins/builtin/earnings-calls/index.tsx +1 -0
  95. package/src/plugins/builtin/econ/calendar-model.ts +74 -1
  96. package/src/plugins/builtin/econ/fred-catalog.ts +3 -1
  97. package/src/plugins/builtin/econ/index.tsx +1 -0
  98. package/src/plugins/builtin/econ-statistics/index.tsx +1 -0
  99. package/src/plugins/builtin/econ-statistics/pane.tsx +6 -0
  100. package/src/plugins/builtin/estimate-revisions/index.tsx +1 -0
  101. package/src/plugins/builtin/executives/index.tsx +1 -0
  102. package/src/plugins/builtin/filing-events/index.tsx +1 -0
  103. package/src/plugins/builtin/fixed-income/index.tsx +1 -0
  104. package/src/plugins/builtin/futures-curve/headless.ts +3 -3
  105. package/src/plugins/builtin/futures-curve/index.tsx +1 -1
  106. package/src/plugins/builtin/futures-curve/model.ts +18 -0
  107. package/src/plugins/builtin/gpu/index.tsx +1 -1
  108. package/src/plugins/builtin/help/functions-table.tsx +1 -1
  109. package/src/plugins/builtin/help/index.tsx +11 -1
  110. package/src/plugins/builtin/help/keybindings-editor.tsx +1 -1
  111. package/src/plugins/builtin/holders/index.tsx +1 -0
  112. package/src/plugins/builtin/holders/report-header.ts +2 -2
  113. package/src/plugins/builtin/insider/index.tsx +1 -0
  114. package/src/plugins/builtin/iv-history/index.tsx +1 -1
  115. package/src/plugins/builtin/jobs/index.tsx +1 -0
  116. package/src/plugins/builtin/macro-day/headless.ts +27 -8
  117. package/src/plugins/builtin/macro-day/index.tsx +1 -1
  118. package/src/plugins/builtin/macro-day/model.ts +19 -3
  119. package/src/plugins/builtin/macro-day/pane.tsx +14 -9
  120. package/src/plugins/builtin/macro-day/releases.ts +25 -7
  121. package/src/plugins/builtin/market-valuation/index.tsx +1 -0
  122. package/src/plugins/builtin/market-valuation/pane.tsx +8 -0
  123. package/src/plugins/builtin/members/index.tsx +1 -1
  124. package/src/plugins/builtin/mna/index.tsx +1 -0
  125. package/src/plugins/builtin/news/index.tsx +1 -0
  126. package/src/plugins/builtin/news/wire/index.tsx +5 -1
  127. package/src/plugins/builtin/news/wire/news/detail-view.tsx +4 -0
  128. package/src/plugins/builtin/news/wire/news/list-search.ts +5 -2
  129. package/src/plugins/builtin/options/index.tsx +1 -0
  130. package/src/plugins/builtin/options-positioning/index.tsx +1 -0
  131. package/src/plugins/builtin/pe-band/index.tsx +1 -1
  132. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +25 -0
  133. package/src/plugins/builtin/portfolio-list/headless.ts +15 -6
  134. package/src/plugins/builtin/power/index.tsx +1 -1
  135. package/src/plugins/builtin/realized-vol/index.tsx +1 -1
  136. package/src/plugins/builtin/research/headless.ts +10 -4
  137. package/src/plugins/builtin/research/index.tsx +4 -0
  138. package/src/plugins/builtin/research-search/index.tsx +1 -0
  139. package/src/plugins/builtin/research-search/pane.tsx +8 -0
  140. package/src/plugins/builtin/revenue-breakdown/index.tsx +1 -0
  141. package/src/plugins/builtin/reverse-dcf/index.tsx +1 -1
  142. package/src/plugins/builtin/risk-factors/index.tsx +1 -0
  143. package/src/plugins/builtin/scanner/headless.ts +52 -13
  144. package/src/plugins/builtin/seasonality/index.tsx +1 -1
  145. package/src/plugins/builtin/sec/index.tsx +1 -0
  146. package/src/plugins/builtin/series-inventory.ts +1 -1
  147. package/src/plugins/builtin/shared/scanner-capture.ts +11 -3
  148. package/src/plugins/builtin/shared/series-list-detail.tsx +5 -0
  149. package/src/plugins/builtin/short-interest/index.tsx +1 -0
  150. package/src/plugins/builtin/social-mentions/index.tsx +1 -1
  151. package/src/plugins/builtin/supply-chain/index.tsx +1 -0
  152. package/src/plugins/builtin/thirteenf/data.ts +43 -10
  153. package/src/plugins/builtin/thirteenf/headless.ts +55 -11
  154. package/src/plugins/builtin/thirteenf/model.ts +25 -9
  155. package/src/plugins/builtin/thirteenf/report-notes.ts +27 -6
  156. package/src/plugins/builtin/thirteenf/types.ts +2 -0
  157. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +1 -1
  158. package/src/plugins/builtin/ticker-detail/financials/model.ts +12 -0
  159. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +3 -3
  160. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +5 -5
  161. package/src/plugins/builtin/ticker-detail/headless.ts +18 -13
  162. package/src/plugins/builtin/ticker-detail/index.tsx +4 -0
  163. package/src/plugins/builtin/ticker-detail/overview/model.ts +6 -4
  164. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +6 -4
  165. package/src/plugins/builtin/time-sales/client.ts +9 -11
  166. package/src/plugins/builtin/time-sales/index.tsx +1 -1
  167. package/src/plugins/builtin/treasury-auctions/after.ts +267 -0
  168. package/src/plugins/builtin/treasury-auctions/cache.ts +18 -3
  169. package/src/plugins/builtin/treasury-auctions/client.ts +33 -2
  170. package/src/plugins/builtin/treasury-auctions/headless.ts +109 -19
  171. package/src/plugins/builtin/treasury-auctions/index.tsx +14 -4
  172. package/src/plugins/builtin/treasury-auctions/model.ts +256 -28
  173. package/src/plugins/builtin/treasury-auctions/pane.tsx +139 -28
  174. package/src/plugins/builtin/treasury-auctions/treasury-direct.ts +5 -2
  175. package/src/plugins/builtin/treasury-auctions/types.ts +7 -1
  176. package/src/plugins/builtin/vol-surface/index.tsx +1 -1
  177. package/src/plugins/builtin/world-venue-map/index.ts +1 -0
  178. package/src/plugins/builtin/yield-curve/curves.ts +10 -4
  179. package/src/plugins/builtin/yield-curve/headless.ts +6 -2
  180. package/src/plugins/builtin/yield-curve/index.tsx +3 -3
  181. package/src/plugins/builtin/yield-curve/series.ts +10 -0
  182. package/src/plugins/builtin/yield-curve/world.ts +3 -1
  183. package/src/portfolio/column-values.ts +2 -1
  184. package/src/public/__snapshots__/public-api.test.ts.snap +4 -0
  185. package/src/public/remote.ts +7 -1
  186. package/src/remote/client.ts +191 -11
  187. package/src/remote/controller-utils.ts +13 -1
  188. package/src/remote/controller.ts +88 -26
  189. package/src/remote/endpoint.ts +24 -0
  190. package/src/remote/form.ts +59 -4
  191. package/src/remote/resources.ts +44 -18
  192. package/src/remote/schema.ts +21 -9
  193. package/src/remote/secrets.ts +12 -0
  194. package/src/remote/semantic-tree.tsx +14 -2
  195. package/src/remote/server.ts +2 -1
  196. package/src/remote/surface.tsx +192 -0
  197. package/src/remote/types.ts +5 -0
  198. package/src/renderers/opentui/host.tsx +6 -0
  199. package/src/series/standalone.ts +2 -2
  200. package/src/shares/api.ts +21 -4
  201. package/src/shares/item.ts +73 -0
  202. package/src/shares/pane-item.ts +205 -0
  203. package/src/shares/pane.ts +4 -0
  204. package/src/shares/payload.ts +9 -5
  205. package/src/sources/gloomberb-cloud/news.ts +2 -0
  206. package/src/tickers/renamed-listings.ts +105 -0
  207. package/src/tickers/search/index.ts +103 -16
  208. package/src/time-series/resolve.ts +2 -2
  209. package/src/types/financials.ts +1 -0
  210. package/src/types/plugin-pane-settings.ts +2 -0
  211. package/src/types/plugin-panes.ts +22 -0
  212. package/src/utils/central-banks.ts +86 -1
  213. package/src/utils/datetime-format.ts +12 -3
  214. package/src/utils/depositary-receipt.ts +28 -3
  215. package/src/utils/fundamentals.ts +14 -0
  216. package/src/utils/max-drawdown.ts +97 -16
  217. package/src/utils/untrusted-text.ts +29 -0
@@ -13,6 +13,10 @@ export interface CentralBank {
13
13
  aliases: readonly string[];
14
14
  /** The FRED series the board reads the row from; the other rows come from BIS. */
15
15
  fredSeriesIds?: readonly string[];
16
+ /** The committee and the rate its decisions are reported by, where those are not its names: Copom, Selic. */
17
+ decisionWords?: readonly string[];
18
+ /** Names another company goes by in the news too (BCB Bancorp), never searched for its stories or matched in them. */
19
+ sharedNames?: readonly string[];
16
20
  }
17
21
 
18
22
  /**
@@ -35,7 +39,7 @@ export const CENTRAL_BANKS: readonly CentralBank[] = [
35
39
  { id: "ID", place: "Indonesia", name: "Bank Indonesia", short: "Bank Indonesia", instrument: "7-day reverse repo rate", aliases: [] },
36
40
  { id: "KR", place: "South Korea", name: "Bank of Korea", short: "BoK", instrument: "base rate", aliases: [] },
37
41
  { id: "BR", place: "Brazil", name: "Central Bank of Brazil", short: "BCB", instrument: "Selic target",
38
- aliases: ["Banco Central do Brasil"] },
42
+ aliases: ["Banco Central do Brasil"], decisionWords: ["Copom", "Selic"], sharedNames: ["BCB"] },
39
43
  { id: "MX", place: "Mexico", name: "Bank of Mexico", short: "Banxico", instrument: "overnight rate target",
40
44
  aliases: ["Banco de México"] },
41
45
  { id: "RU", place: "Russia", name: "Bank of Russia", short: "Bank of Russia", instrument: "key rate",
@@ -69,6 +73,18 @@ export function centralBankNamed(query: string): CentralBank | null {
69
73
  return CENTRAL_BANKS.find((bank) => centralBankNames(bank).some((name) => nameKey(name) === wanted)) ?? null;
70
74
  }
71
75
 
76
+ /**
77
+ * The bank a single word is the short name of, in any case: what a sentence
78
+ * calls it or a one-word alias (ECB, BoJ, RBA, Fed, FOMC, Banxico). Never a
79
+ * name it shares with a company (BCB, BCB Bancorp's too). Null otherwise.
80
+ */
81
+ export function centralBankShortNamed(word: string): CentralBank | null {
82
+ const wanted = nameKey(word);
83
+ if (!wanted || wanted.includes(" ")) return null;
84
+ return CENTRAL_BANKS.find((bank) => [bank.short, ...bank.aliases]
85
+ .some((name) => nameKey(name) === wanted && !(bank.sharedNames ?? []).some((shared) => nameKey(shared) === wanted))) ?? null;
86
+ }
87
+
72
88
  /** Words a query puts beside a bank's name when it asks for its policy rate: "Bank of Japan rate", "ECB rate decision", "Fed funds rate". */
73
89
  const POLICY_RATE_WORDS = new Set([
74
90
  "rate", "rates", "policy", "interest", "decision", "decisions", "meeting", "meetings", "target", "funds",
@@ -116,3 +132,72 @@ export function centralBankCiting(fredSeriesId: string): CentralBank | null {
116
132
  const wanted = fredSeriesId.trim().toUpperCase();
117
133
  return CENTRAL_BANKS.find((bank) => bank.fredSeriesIds?.includes(wanted)) ?? null;
118
134
  }
135
+
136
+ /**
137
+ * The bank a news search names: by its names as `centralBankAskedAbout` reads
138
+ * them, or by the committee and rate its decisions are reported by ("copom",
139
+ * "copom selic", "Selic rate"). Null for anything else.
140
+ */
141
+ export function centralBankInNews(query: string): CentralBank | null {
142
+ const asked = centralBankAskedAbout(query);
143
+ if (asked) return asked;
144
+ const words = nameKey(query).split(" ").filter(Boolean);
145
+ if (words.length === 0) return null;
146
+ return CENTRAL_BANKS.find((bank) => {
147
+ const decision = (bank.decisionWords ?? []).map((word) => nameKey(word).split(" "));
148
+ if (decision.length === 0) return false;
149
+ // Every word is one of the decision words or a word asking for the rate, and at least one is a decision word.
150
+ const named = words.filter((word) => decision.some((parts) => parts.includes(word)));
151
+ return named.length > 0 && words.every((word) => named.includes(word) || POLICY_RATE_WORDS.has(word));
152
+ }) ?? null;
153
+ }
154
+
155
+ /** Words that ask for the newest of something without being what a story says: "latest Fed decision". */
156
+ const ASKING_WORDS = new Set(["current", "latest", "today"]);
157
+
158
+ /**
159
+ * What a news search asks of the bank besides naming it, lower case: "rate
160
+ * cut" of "fed rate cut", "" of "copom selic" or "Bank of Mexico". Its
161
+ * names, place and decision words are taken out, and the words that only ask
162
+ * for the newest.
163
+ */
164
+ export function centralBankNewsTopic(bank: CentralBank, query: string): string {
165
+ let words = nameKey(query).split(" ").filter(Boolean);
166
+ const names = [`${bank.place} central bank`, ...centralBankNames(bank), bank.place, ...bank.decisionWords ?? []]
167
+ .map((name) => nameKey(name).split(" ")).sort((left, right) => right.length - left.length);
168
+ for (const name of names) {
169
+ for (let start = wordsIndex(words, name); start >= 0; start = wordsIndex(words, name)) {
170
+ words = [...words.slice(0, start), ...words.slice(start + name.length)];
171
+ }
172
+ }
173
+ return words.filter((word) => !ASKING_WORDS.has(word)).join(" ");
174
+ }
175
+
176
+ /**
177
+ * What a bank's decisions are reported under, for a news search of each: its
178
+ * name, what a sentence calls it, its other names, "<place> central bank" and
179
+ * the committee and rate (Copom, Selic). Stories of the 5 Nov 2026 Banxico cut
180
+ * said "Bank of Mexico" or "Mexico's central bank", rarely "Banxico". A name
181
+ * another company shares (BCB) is left out.
182
+ */
183
+ export function centralBankNewsQueries(bank: CentralBank): string[] {
184
+ const names = centralBankNames(bank).filter((name) => !bank.sharedNames?.includes(name));
185
+ return [...new Set([...names, `${bank.place} central bank`, ...bank.decisionWords ?? []])];
186
+ }
187
+
188
+ /** An acronym (ECB, RBA, FOMC) is matched as a word in capitals: "the fomc" in lower case is no headline's. */
189
+ const ACRONYM = /^[A-Z]{2,5}$/;
190
+
191
+ /**
192
+ * Whether a story is about the bank: its title or summary names it as one of
193
+ * the phrases it is searched by, or as "<place>'s central bank", each as
194
+ * whole words. The search matches words anywhere, so "Bank of Mexico" also
195
+ * finds Citi Mexico's banks.
196
+ */
197
+ export function storyNamesCentralBank(bank: CentralBank, text: string): boolean {
198
+ const story = ` ${nameKey(text)} `;
199
+ const phrases = [...centralBankNewsQueries(bank), `${bank.place}s central bank`];
200
+ return phrases.some((phrase) => ACRONYM.test(phrase)
201
+ ? new RegExp(`(^|[^A-Za-z0-9])${phrase}([^A-Za-z0-9]|$)`).test(text)
202
+ : story.includes(` ${nameKey(phrase)} `));
203
+ }
@@ -155,15 +155,24 @@ function utcMidnight(date: Date): number {
155
155
  * in another year). A weekday never names a day a week or more back. With
156
156
  * `utc`, the same in UTC, for a column whose header names the zone.
157
157
  */
158
- export function formatFeedTime(value: DisplayDateValue, now = Date.now(), fallback = "-", { utc = false }: { utc?: boolean } = {}): string {
158
+ export function formatFeedTime(
159
+ value: DisplayDateValue,
160
+ now = Date.now(),
161
+ fallback = "-",
162
+ { utc = false, dayToday = false }: {
163
+ utc?: boolean;
164
+ /** Today's time carries its weekday too ("Sat 00:47"), for a column whose other rows name theirs ("Fri 21:00"). */
165
+ dayToday?: boolean;
166
+ } = {},
167
+ ): string {
159
168
  const date = parseDisplayDate(value);
160
169
  if (!date) return fallback;
161
170
  const today = new Date(now);
162
171
  const midnight = utc ? utcMidnight : localMidnight;
163
172
  // Rounded, since a day with a DST change is 23 or 25 hours long.
164
173
  const daysAgo = Math.round((midnight(today) - midnight(date)) / 86_400_000);
165
- if (daysAgo === 0) return (utc ? utcClockFormatter : clockFormatter).format(date);
166
- if (daysAgo > 0 && daysAgo < 7) return (utc ? utcWeekdayClockFormatter : weekdayClockFormatter).format(date).replace(",", "");
174
+ if (daysAgo === 0 && !dayToday) return (utc ? utcClockFormatter : clockFormatter).format(date);
175
+ if (daysAgo >= 0 && daysAgo < 7) return (utc ? utcWeekdayClockFormatter : weekdayClockFormatter).format(date).replace(",", "");
167
176
  const sameYear = utc ? date.getUTCFullYear() === today.getUTCFullYear() : date.getFullYear() === today.getFullYear();
168
177
  return formatShortDate(date, { year: sameYear ? false : "2-digit", utc });
169
178
  }
@@ -62,9 +62,34 @@ export function sharesOutstandingInReceipts(
62
62
  });
63
63
  }
64
64
 
65
- /** "1 ADR = 2 ordinary shares", or null without a usable ratio. */
66
- export function adrRatioText(ratio: number | null | undefined): string | null {
65
+ /**
66
+ * What a receipt's home line is a unit of, from how its market writes the
67
+ * code: a B3 code ending in 4 to 8 is a preferred share (PETR4, ITUB4) and
68
+ * one ending in 11 a unit; a BMV line marked CPO holds certificates
69
+ * (TLEVISACPO) and one marked UB, UBD or UBL units (FEMSAUBD, KOFUBL); a
70
+ * Korean code ending in 5, 7 or 9 is a preferred share (005935), and any
71
+ * other line on those three markets an ordinary share (VALE3, WALMEX). A home
72
+ * line elsewhere, or none, says plain shares: its code does not say its class
73
+ * (PFBCOLOM is Bancolombia's preferred).
74
+ */
75
+ function homeShareClass(home: string | null | undefined): { one: string; many: string } {
76
+ const ticker = (home ?? "").trim().toUpperCase();
77
+ const [code = "", venue = ""] = ticker.includes(":") ? ticker.split(":") : [ticker.replace(/\.[A-Z]+$/, ""), ticker.match(/\.([A-Z]+)$/)?.[1] ?? ""];
78
+ const b3 = venue === "SA" || venue === "B3" || venue === "BVMF" || venue === "SAO" || venue === "BOVESPA";
79
+ const bmv = venue === "MX" || venue === "BMV";
80
+ const korea = venue === "KS" || venue === "KQ" || venue === "KRX" || venue === "KOSDAQ";
81
+ if (b3 && /^[A-Z]{4}(4|5|6|7|8)$/.test(code)) return { one: "preferred share", many: "preferred shares" };
82
+ if (b3 && /^[A-Z]{4}11$/.test(code)) return { one: "unit", many: "units" };
83
+ if (bmv && /CPO$/.test(code)) return { one: "CPO", many: "CPOs" };
84
+ if (bmv && /UB[DLC]?$/.test(code)) return { one: "unit", many: "units" };
85
+ if (korea && /^\d{5}[579]$/.test(code)) return { one: "preferred share", many: "preferred shares" };
86
+ return b3 || bmv || korea ? { one: "ordinary share", many: "ordinary shares" } : { one: "share", many: "shares" };
87
+ }
88
+
89
+ /** "1 ADR = 2 shares" ("2 preferred shares" of PETR4.SA, `homeShareClass`), or null without a usable ratio. */
90
+ export function adrRatioText(ratio: number | null | undefined, home?: string | null): string | null {
67
91
  if (typeof ratio !== "number" || !Number.isFinite(ratio) || ratio <= 0) return null;
68
92
  const count = Number.isInteger(ratio) ? String(ratio) : String(Number(ratio.toPrecision(6)));
69
- return `1 ADR = ${count} ordinary share${ratio === 1 ? "" : "s"}`;
93
+ const unit = homeShareClass(home);
94
+ return `1 ADR = ${count} ${ratio === 1 ? unit.one : unit.many}`;
70
95
  }
@@ -126,6 +126,20 @@ export function enterpriseValueLabel(fundamentals: Parameters<typeof enterpriseV
126
126
  return status === "differs" ? "provider" : status === "withdrawn" || enterpriseValueWithdrawn(fundamentals) ? "unavailable" : undefined;
127
127
  }
128
128
 
129
+ /**
130
+ * Whether a company's overview names the gap between the provider's EV and market cap + debt - cash: past 10% of
131
+ * the computed figure. A smaller gap (a 4.87T EV beside 5T computed) is a data detail the
132
+ * valuation panes (RV, the reverse DCF) still give in full, not a warning to greet a first look at the company.
133
+ * Any other check (withdrawn, not meaningful) is always named: it is why a figure is missing.
134
+ */
135
+ export function enterpriseValueGapIsLarge(fundamentals: Parameters<typeof enterpriseValueCheck>[0]): boolean {
136
+ const check = enterpriseValueCheck(fundamentals);
137
+ if (check?.status !== "differs" || !finiteNumber(check.source) || !finiteNumber(check.computed) || check.computed <= 0) return true;
138
+ return Math.abs(check.source / check.computed - 1) > OVERVIEW_ENTERPRISE_VALUE_GAP;
139
+ }
140
+
141
+ const OVERVIEW_ENTERPRISE_VALUE_GAP = 0.1;
142
+
129
143
  /**
130
144
  * The reconciliation line under a labelled, withdrawn or not meaningful EV: "EV 61.75B USD (provider) vs 63.75B
131
145
  * computed from market cap + total debt - cash (balance sheet 2026-06-30).", "EV N/M: cash and short-term investments
@@ -1,64 +1,145 @@
1
+ import { toBasisPoints } from "./basis-points";
2
+
1
3
  /**
2
4
  * The largest fall from a close to a later close (docs/usage.md, under `history`):
3
5
  * the peak it fell from and the trough it reached, each with its date, the
4
6
  * fall as a fraction of the peak, and the first later close back at the peak,
5
7
  * if any. Read off closes, as returns are; a missing or non-positive close is
6
8
  * passed over. The earliest of equal falls is the one named.
9
+ *
10
+ * A series in yield units (^TNX, a yield in percent) falls and rises by its
11
+ * level: the largest fall in percentage points, said in basis points (`bp`),
12
+ * and its largest rise as well (`maxRunUp`). A ratio of two yields is no
13
+ * move anyone reads.
7
14
  */
8
15
  export interface MaxDrawdown {
9
16
  peak: { date: string; close: number };
10
17
  trough: { date: string; close: number };
11
18
  /** trough / peak - 1: 0 when no close fell below an earlier one, else negative. */
12
19
  drawdown: number;
20
+ /** A yield's fall, trough - peak in basis points to a tenth; absent for a price. */
21
+ bp?: number;
13
22
  /** The first date after the trough whose close is back at the peak; null when none is in the series. */
14
23
  recovered: string | null;
15
24
  /** The last date in the series, which a fall not yet recovered is measured to. */
16
25
  through: string;
17
26
  }
18
27
 
28
+ /** A yield's largest rise from a close to a later close: the low it rose from and the high it reached. */
29
+ export interface MaxRunUp {
30
+ low: { date: string; close: number };
31
+ high: { date: string; close: number };
32
+ /** high - low in basis points, to a tenth: 0 when no close rose above an earlier one. */
33
+ bp: number;
34
+ /** The first date after the high whose close is back at the low; null when none is in the series. */
35
+ recovered: string | null;
36
+ through: string;
37
+ }
38
+
39
+ /** How a series moves: a price by its return, a yield in percent by its level. */
40
+ export type DrawdownScale = "return" | "yield";
41
+
19
42
  interface ClosePoint {
20
43
  /** An ISO date or instant; points sort by it. */
21
44
  date: string;
22
45
  close: number | null | undefined;
23
46
  }
24
47
 
25
- /** The series' max drawdown, or null with fewer than two closes. */
26
- export function maxDrawdown(points: readonly ClosePoint[]): MaxDrawdown | null {
27
- const closes = points
28
- .filter((point): point is { date: string; close: number } => typeof point.close === "number" && Number.isFinite(point.close) && point.close > 0)
48
+ function sortedCloses(points: readonly ClosePoint[], scale: DrawdownScale) {
49
+ // A yield can sit at or below zero; a price there is no close.
50
+ return points
51
+ .filter((point): point is { date: string; close: number } => typeof point.close === "number" && Number.isFinite(point.close)
52
+ && (scale === "yield" || point.close > 0))
29
53
  .toSorted((left, right) => left.date.localeCompare(right.date));
54
+ }
55
+
56
+ /** The series' max drawdown, or null with fewer than two closes. */
57
+ export function maxDrawdown(points: readonly ClosePoint[], scale: DrawdownScale = "return"): MaxDrawdown | null {
58
+ const closes = sortedCloses(points, scale);
30
59
  if (closes.length < 2) return null;
60
+ const fallOf = (from: number, to: number) => scale === "yield" ? to - from : to / from - 1;
31
61
  let peak = closes[0]!;
32
- let worst = { peak, trough: peak, drawdown: 0 };
62
+ let worst = { peak, trough: peak, fall: 0 };
33
63
  for (const point of closes) {
34
64
  if (point.close > peak.close) peak = point;
35
- const fall = point.close / peak.close - 1;
36
- if (fall < worst.drawdown) worst = { peak, trough: point, drawdown: fall };
65
+ const fall = fallOf(peak.close, point.close);
66
+ if (fall < worst.fall) worst = { peak, trough: point, fall };
37
67
  }
38
- const recovered = worst.drawdown < 0
68
+ const recovered = worst.fall < 0
39
69
  ? closes.find((point) => point.date > worst.trough.date && point.close >= worst.peak.close)?.date ?? null
40
70
  : null;
41
71
  return {
42
72
  peak: { date: worst.peak.date, close: worst.peak.close },
43
73
  trough: { date: worst.trough.date, close: worst.trough.close },
44
- drawdown: worst.drawdown,
74
+ drawdown: scale === "yield" ? (worst.peak.close > 0 ? worst.trough.close / worst.peak.close - 1 : 0) : worst.fall,
75
+ ...(scale === "yield" ? { bp: toBasisPoints(worst.fall, 1) } : {}),
45
76
  recovered,
46
77
  through: closes.at(-1)!.date,
47
78
  };
48
79
  }
49
80
 
81
+ /** A yield series' largest rise from a close to a later close, or null with fewer than two closes. */
82
+ export function maxRunUp(points: readonly ClosePoint[]): MaxRunUp | null {
83
+ const closes = sortedCloses(points, "yield");
84
+ if (closes.length < 2) return null;
85
+ let low = closes[0]!;
86
+ let best = { low, high: low, rise: 0 };
87
+ for (const point of closes) {
88
+ if (point.close < low.close) low = point;
89
+ const rise = point.close - low.close;
90
+ if (rise > best.rise) best = { low, high: point, rise };
91
+ }
92
+ const recovered = best.rise > 0
93
+ ? closes.find((point) => point.date > best.high.date && point.close <= best.low.close)?.date ?? null
94
+ : null;
95
+ return {
96
+ low: { date: best.low.date, close: best.low.close },
97
+ high: { date: best.high.date, close: best.high.close },
98
+ bp: toBasisPoints(best.rise, 1),
99
+ recovered,
100
+ through: closes.at(-1)!.date,
101
+ };
102
+ }
103
+
104
+ interface MoveTextOptions { basis: string; price: (value: number) => string; date?: (text: string) => string }
105
+
106
+ /** Whole basis points, signed; a move that rounds to nothing is still a move, which 0bp would hide. */
107
+ function bpText(bp: number): string {
108
+ const whole = Math.round(bp);
109
+ if (whole === 0) return bp === 0 ? "0bp" : "under 1bp";
110
+ return `${whole > 0 ? "+" : ""}${whole}bp`;
111
+ }
112
+
50
113
  /**
51
114
  * The report line: `Max drawdown -69.6% (daily closes): peak 53.25 on 2007-05-30, trough 16.19 on 2009-03-09,
52
- * not back to the peak by 2009-12-31`. `price` and `date` draw a close and a date as the table does.
115
+ * not back to the peak by 2009-12-31`; a yield's fall in bp: `Max drawdown -16bp (daily closes): ...`.
116
+ * `price` and `date` draw a close and a date as the table does.
53
117
  */
54
- export function maxDrawdownText(
55
- value: MaxDrawdown,
56
- { basis, price, date = (text) => text.slice(0, 10) }: { basis: string; price: (value: number) => string; date?: (text: string) => string },
57
- ): string {
118
+ export function maxDrawdownText(value: MaxDrawdown, { basis, price, date = (text) => text.slice(0, 10) }: MoveTextOptions): string {
58
119
  const percent = (value.drawdown * 100).toFixed(1);
59
120
  // A fall that rounds to nothing is still a fall, which -0.0% would hide.
60
- const head = `Max drawdown ${percent === "-0.0" ? "under 0.1%" : `${percent}%`} (${basis})`;
61
- if (value.drawdown === 0) return `${head}: no close fell below an earlier one`;
121
+ const size = value.bp != null ? bpText(value.bp) : percent === "-0.0" ? "under 0.1%" : `${percent}%`;
122
+ const head = `Max drawdown ${size} (${basis})`;
123
+ if (value.peak.date === value.trough.date) return `${head}: no close fell below an earlier one`;
62
124
  const back = value.recovered ? `back to the peak on ${date(value.recovered)}` : `not back to the peak by ${date(value.through)}`;
63
125
  return `${head}: peak ${price(value.peak.close)} on ${date(value.peak.date)}, trough ${price(value.trough.close)} on ${date(value.trough.date)}, ${back}`;
64
126
  }
127
+
128
+ /** `Max run-up +45bp (daily closes): low 3.998 on 2025-11-26, high 4.448 on 2026-01-14, not back to the low by 2026-02-02`. */
129
+ export function maxRunUpText(value: MaxRunUp, { basis, price, date = (text) => text.slice(0, 10) }: MoveTextOptions): string {
130
+ const head = `Max run-up ${bpText(value.bp)} (${basis})`;
131
+ if (value.low.date === value.high.date) return `${head}: no close rose above an earlier one`;
132
+ const back = value.recovered ? `back to the low on ${date(value.recovered)}` : `not back to the low by ${date(value.through)}`;
133
+ return `${head}: low ${price(value.low.close)} on ${date(value.low.date)}, high ${price(value.high.close)} on ${date(value.high.date)}, ${back}`;
134
+ }
135
+
136
+ /** A series' largest fall, and a yield's largest rise as well, with the lines a report says them in. */
137
+ export function closeMoves(points: readonly ClosePoint[], scale: DrawdownScale, text: MoveTextOptions): {
138
+ drawdown: MaxDrawdown | null;
139
+ runUp: MaxRunUp | null;
140
+ lines: string[];
141
+ } {
142
+ const drawdown = maxDrawdown(points, scale);
143
+ const runUp = scale === "yield" ? maxRunUp(points) : null;
144
+ return { drawdown, runUp, lines: [...drawdown ? [maxDrawdownText(drawdown, text)] : [], ...runUp ? [maxRunUpText(runUp, text)] : []] };
145
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Terminal escape sequences: a CSI (`ESC [` or its one-byte C1 form) to its
3
+ * final byte, an OSC, DCS, SOS, PM or APC string to its BEL or ST (or the
4
+ * end), and the two-byte escapes.
5
+ */
6
+ const ESCAPE_SEQUENCE =
7
+ /(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]|(?:\u001b[\]PX^_]|[\u0090\u0098\u009d-\u009f])[^\u0007\u001b\u009c]*(?:\u0007|\u001b\\|\u009c)?|\u001b[ -/]*[0-~]/g;
8
+ /** Marks that turn, embed or hide text without showing themselves: bidi controls and zero-width characters. */
9
+ const INVISIBLE = /[\u061c\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/g;
10
+ /** Half of a broken surrogate pair, which no font draws and Postgres does not store. */
11
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
12
+ /** C0 and C1 controls: a line, a tab, a bell, what a terminal takes as a command. */
13
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g;
14
+
15
+ /**
16
+ * Text another person's app wrote (a shared pane's item, a share's title), as
17
+ * one line that draws as what it says: no terminal escape sequence, control
18
+ * character, bidi control or zero-width character, and no broken surrogate
19
+ * pair. The share service keeps an item's text to the same rule.
20
+ */
21
+ export function plainUntrustedLine(value: string): string {
22
+ return value
23
+ .replace(ESCAPE_SEQUENCE, "")
24
+ .replace(INVISIBLE, "")
25
+ .replace(LONE_SURROGATE, "")
26
+ .replace(CONTROL, " ")
27
+ .replace(/\s+/g, " ")
28
+ .trim();
29
+ }