@gloom-sh/terminal 0.20.9 → 0.20.11

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 (212) hide show
  1. package/package.json +1 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +16 -0
  3. package/src/api-client/auth.ts +6 -0
  4. package/src/api-client/data.ts +1 -0
  5. package/src/api-client/earnings.ts +15 -0
  6. package/src/api-client/index.ts +14 -3
  7. package/src/api-client/socket-connection.ts +355 -0
  8. package/src/api-client/socket-features.ts +75 -0
  9. package/src/api-client/socket-frames.ts +161 -0
  10. package/src/api-client/socket-listeners.ts +207 -0
  11. package/src/api-client/socket-quotes.ts +332 -0
  12. package/src/api-client/socket.ts +150 -983
  13. package/src/api-client/types/account.ts +10 -0
  14. package/src/api-client/types/billing.ts +10 -0
  15. package/src/api-client/types/econ.ts +19 -7
  16. package/src/api-client/types/market.ts +7 -0
  17. package/src/api-client/types/screener.ts +2 -0
  18. package/src/brokers/signed-in/adapter.ts +19 -5
  19. package/src/brokers/signed-in/client.ts +13 -1
  20. package/src/brokers/signed-in/sign-in-dialog.tsx +33 -9
  21. package/src/cli/commands/market.ts +18 -8
  22. package/src/cli/commands/overview.ts +26 -7
  23. package/src/cli/commands/ticker.ts +40 -15
  24. package/src/cli/desktop-pane-shot.ts +39 -0
  25. package/src/cli/errors.ts +20 -3
  26. package/src/cli/fx-pair.ts +11 -2
  27. package/src/cli/history-rows.ts +34 -3
  28. package/src/cli/index.ts +1 -1
  29. package/src/cli/listing-arg.ts +51 -13
  30. package/src/cli/pane-functions/headless.ts +4 -2
  31. package/src/cli/pane-functions/index.ts +1 -0
  32. package/src/cli/pane-functions/resolver.ts +2 -1
  33. package/src/cli/pane-functions/screenshot-assessment.ts +73 -5
  34. package/src/cli/pane-functions/screenshot-types.ts +4 -0
  35. package/src/components/chart/composite/chart-layout.ts +7 -4
  36. package/src/components/chart/composite/composite-chart.tsx +6 -16
  37. package/src/components/chart/composite/toolbar.tsx +258 -82
  38. package/src/components/chart/composite/use-composite-chart-keyboard.ts +5 -6
  39. package/src/components/chart/native/kitty/manager.ts +2 -0
  40. package/src/components/chart/native/surface/manager.ts +211 -11
  41. package/src/components/command-bar/list/model.ts +13 -0
  42. package/src/components/command-bar/panel/index.tsx +2 -13
  43. package/src/components/command-bar/panel/layout.ts +1 -7
  44. package/src/components/command-bar/panel/runtime.ts +0 -1
  45. package/src/components/command-bar/panel/types.ts +0 -2
  46. package/src/components/command-bar/routes/ticker-search/actions.ts +2 -0
  47. package/src/components/command-bar/routes/ticker-search/results.ts +15 -8
  48. package/src/components/command-bar/surface/index.tsx +10 -5
  49. package/src/components/command-bar/workflow/alert.ts +21 -7
  50. package/src/components/data-table/column-menu.tsx +89 -0
  51. package/src/components/data-table/sort-menu.tsx +9 -2
  52. package/src/components/data-table/table-pane.ts +3 -1
  53. package/src/components/data-table/view.tsx +33 -6
  54. package/src/components/form-modal/content.tsx +10 -0
  55. package/src/components/index.ts +1 -1
  56. package/src/components/layout/pane/footer/index.tsx +25 -11
  57. package/src/components/layout/pane/footer/model.ts +88 -21
  58. package/src/components/layout/pane/sidebar.tsx +125 -15
  59. package/src/components/layout/shell/active-drag.ts +18 -13
  60. package/src/components/layout/shell/drag/magnets.ts +34 -18
  61. package/src/components/metric-treemap/heat-surface.tsx +2 -1
  62. package/src/components/metric-treemap/index.tsx +3 -2
  63. package/src/components/ticker/list-table-view.tsx +5 -0
  64. package/src/components/ui/confirm-dialog.tsx +253 -7
  65. package/src/components/ui/data-table/column-order.ts +180 -0
  66. package/src/components/ui/data-table/index.tsx +13 -2
  67. package/src/components/ui/data-table/opentui/index.tsx +267 -23
  68. package/src/components/ui/data-table/opentui/model.ts +43 -4
  69. package/src/components/ui/data-table/types.ts +56 -0
  70. package/src/components/ui/data-table/use-column-order.ts +135 -0
  71. package/src/components/ui/index.ts +1 -1
  72. package/src/components/ui/list-view.tsx +4 -3
  73. package/src/components/ui/status.tsx +9 -6
  74. package/src/components/ui/table-layout.ts +120 -0
  75. package/src/docs/snapshot.json +39 -2
  76. package/src/i18n/es.ts +14 -0
  77. package/src/i18n/ja.ts +14 -0
  78. package/src/i18n/ko.ts +14 -0
  79. package/src/i18n/zh-cn.ts +14 -0
  80. package/src/i18n/zh-tw.ts +14 -0
  81. package/src/market-data/coordinator/index.ts +4 -3
  82. package/src/market-data/coordinator/quotes.ts +12 -4
  83. package/src/market-data/fx-closes.ts +14 -2
  84. package/src/market-data/market/change-basis.ts +35 -1
  85. package/src/market-data/market/status.ts +37 -0
  86. package/src/market-data/performance.ts +4 -1
  87. package/src/market-data/quotes/freshness.ts +12 -0
  88. package/src/market-data/quotes/live-valuation.ts +26 -3
  89. package/src/market-data/quotes/regular-session-valuation.ts +1 -1
  90. package/src/market-data/realized-volatility.ts +3 -0
  91. package/src/market-data/us-bond-market.ts +115 -0
  92. package/src/plugins/builtin/account-management/invite-row.tsx +54 -0
  93. package/src/plugins/builtin/account-management/keyboard.ts +3 -0
  94. package/src/plugins/builtin/account-management/model.ts +1 -0
  95. package/src/plugins/builtin/account-management/pane.tsx +51 -5
  96. package/src/plugins/builtin/account-management/trial-cancel.ts +32 -7
  97. package/src/plugins/builtin/broker-manager/detail.tsx +5 -3
  98. package/src/plugins/builtin/broker-manager/index.tsx +6 -6
  99. package/src/plugins/builtin/broker-manager/model.ts +15 -6
  100. package/src/plugins/builtin/broker-manager/pane-actions.tsx +11 -4
  101. package/src/plugins/builtin/broker-manager/sign-in-end.ts +50 -19
  102. package/src/plugins/builtin/broker-manager/table.ts +10 -4
  103. package/src/plugins/builtin/chat/sidebar.tsx +33 -16
  104. package/src/plugins/builtin/cloud/askg/pane-session.ts +94 -0
  105. package/src/plugins/builtin/cloud/askg/pane.tsx +40 -83
  106. package/src/plugins/builtin/cloud/askg/tool-timeline.tsx +2 -0
  107. package/src/plugins/builtin/congress-trades/pane.tsx +8 -2
  108. package/src/plugins/builtin/correlation/compute.ts +4 -3
  109. package/src/plugins/builtin/earnings/board-model.ts +33 -0
  110. package/src/plugins/builtin/earnings/board-table.ts +50 -11
  111. package/src/plugins/builtin/earnings/board.tsx +29 -13
  112. package/src/plugins/builtin/earnings/calendar.tsx +15 -3
  113. package/src/plugins/builtin/earnings/client.ts +4 -1
  114. package/src/plugins/builtin/earnings/headless.ts +27 -14
  115. package/src/plugins/builtin/econ/calendar-source.ts +3 -0
  116. package/src/plugins/builtin/equity-screener/live.ts +74 -18
  117. package/src/plugins/builtin/equity-screener/model.ts +19 -4
  118. package/src/plugins/builtin/equity-screener/pane.tsx +19 -14
  119. package/src/plugins/builtin/equity-screener/refresh-anchor.ts +45 -0
  120. package/src/plugins/builtin/equity-screener/results.ts +22 -2
  121. package/src/plugins/builtin/equity-screener/screen-check.ts +9 -3
  122. package/src/plugins/builtin/futures/index.tsx +15 -1
  123. package/src/plugins/builtin/futures/table.tsx +1 -1
  124. package/src/plugins/builtin/fx-matrix/index.tsx +2 -0
  125. package/src/plugins/builtin/help/index.tsx +1 -1
  126. package/src/plugins/builtin/holders/pane.tsx +30 -20
  127. package/src/plugins/builtin/ipo-calendar/model.ts +3 -3
  128. package/src/plugins/builtin/iv-history/events.ts +5 -0
  129. package/src/plugins/builtin/iv-history/headless.ts +19 -12
  130. package/src/plugins/builtin/kelly-sizer/sections.tsx +2 -0
  131. package/src/plugins/builtin/macro-day/headless.ts +27 -8
  132. package/src/plugins/builtin/macro-day/model.ts +17 -4
  133. package/src/plugins/builtin/macro-day/releases.ts +36 -15
  134. package/src/plugins/builtin/market-halts/model.ts +3 -2
  135. package/src/plugins/builtin/market-movers/headless.ts +2 -1
  136. package/src/plugins/builtin/market-movers/index.tsx +3 -2
  137. package/src/plugins/builtin/market-movers/model.ts +75 -22
  138. package/src/plugins/builtin/market-movers/screener.ts +2 -1
  139. package/src/plugins/builtin/market-movers/table.ts +7 -5
  140. package/src/plugins/builtin/options/view.tsx +2 -0
  141. package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
  142. package/src/plugins/builtin/pe-band/model.ts +4 -0
  143. package/src/plugins/builtin/perps/cascade-tabs.tsx +2 -1
  144. package/src/plugins/builtin/portfolio-list/cell-version.ts +4 -4
  145. package/src/plugins/builtin/portfolio-list/cli/render.ts +9 -4
  146. package/src/plugins/builtin/portfolio-list/pane/index.tsx +15 -1
  147. package/src/plugins/builtin/portfolio-list/summary/index.tsx +24 -7
  148. package/src/plugins/builtin/portfolio-list/summary/totals.ts +40 -11
  149. package/src/plugins/builtin/portfolio-list/table.tsx +18 -1
  150. package/src/plugins/builtin/rate-path/pane.tsx +2 -0
  151. package/src/plugins/builtin/research/analyst-headless.ts +9 -1
  152. package/src/plugins/builtin/research/analyst-pane.tsx +10 -4
  153. package/src/plugins/builtin/research/client.ts +25 -1
  154. package/src/plugins/builtin/research/corporate-actions-pane.tsx +2 -1
  155. package/src/plugins/builtin/research/event-model.ts +3 -13
  156. package/src/plugins/builtin/research/event-sources.ts +3 -1
  157. package/src/plugins/builtin/revenue-breakdown/pane.tsx +2 -0
  158. package/src/plugins/builtin/reverse-dcf/pane.tsx +2 -1
  159. package/src/plugins/builtin/seasonality/pane.tsx +2 -1
  160. package/src/plugins/builtin/short-interest/headless.ts +2 -0
  161. package/src/plugins/builtin/short-interest/publications-headless.ts +2 -0
  162. package/src/plugins/builtin/short-interest/watch-headless.ts +1 -0
  163. package/src/plugins/builtin/thirteenf/pane.tsx +2 -0
  164. package/src/plugins/builtin/ticker-detail/financials/model.ts +28 -6
  165. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +26 -9
  166. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +58 -35
  167. package/src/plugins/builtin/vol-surface/heat-grid.tsx +2 -1
  168. package/src/plugins/builtin/vol-surface/pane.tsx +2 -1
  169. package/src/plugins/builtin/world-indices/index.tsx +5 -1
  170. package/src/plugins/builtin/yield-curve/headless.ts +5 -1
  171. package/src/plugins/builtin/yield-curve/index.tsx +7 -1
  172. package/src/portfolio/column-values.ts +47 -14
  173. package/src/portfolio/return-metrics.ts +4 -2
  174. package/src/renderers/dom/data-table/column-drag.ts +147 -0
  175. package/src/renderers/dom/data-table/index.tsx +22 -0
  176. package/src/renderers/dom/data-table/row.tsx +27 -5
  177. package/src/renderers/dom/host/image-surface.tsx +19 -9
  178. package/src/renderers/dom/host/input.tsx +4 -0
  179. package/src/renderers/dom/styles.css +22 -0
  180. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +23 -1
  181. package/src/renderers/opentui/chart-surface.tsx +1 -0
  182. package/src/renderers/opentui/frame-hits.ts +33 -0
  183. package/src/renderers/opentui/host.tsx +2 -0
  184. package/src/renderers/opentui/native-surface.ts +14 -21
  185. package/src/renderers/opentui/test-utils.tsx +3 -0
  186. package/src/sources/gloomberb-cloud/normalizers.ts +2 -0
  187. package/src/sources/provider-errors.ts +12 -0
  188. package/src/sources/provider-router/index.ts +12 -4
  189. package/src/state/app/context/index.tsx +22 -0
  190. package/src/state/pane-session.ts +145 -0
  191. package/src/test-support/app-store.ts +24 -1
  192. package/src/tickers/search/home-listing.ts +44 -1
  193. package/src/tickers/search/index.ts +5 -2
  194. package/src/tickers/search/ranking.ts +7 -7
  195. package/src/tickers/us-listing.ts +11 -5
  196. package/src/time-series/base-series.ts +7 -1
  197. package/src/time-series/fundamentals/current-valuation.ts +8 -0
  198. package/src/time-series/fundamentals/series.ts +6 -0
  199. package/src/time-series/live-quotes.ts +3 -9
  200. package/src/time-series/resolve.ts +1 -0
  201. package/src/types/financials.ts +20 -0
  202. package/src/types/headless.ts +9 -0
  203. package/src/ui/host.tsx +20 -0
  204. package/src/ui/pointer-drag.ts +11 -2
  205. package/src/utils/exchanges.ts +13 -8
  206. package/src/utils/fundamentals.ts +14 -3
  207. package/src/utils/price-earnings.ts +17 -10
  208. package/src/utils/price-history-integrity.ts +15 -0
  209. package/src/utils/reason-codes.ts +79 -0
  210. package/src/utils/share-multiples.cases.json +1667 -0
  211. package/src/utils/share-multiples.ts +384 -0
  212. package/src/utils/untrusted-text.ts +11 -0
@@ -0,0 +1,384 @@
1
+ import type { FinancialStatement, Fundamentals, TickerFinancials } from "../types/financials";
2
+ import { resolveCurrencyUnit } from "./currency-units";
3
+ import { canonicalExchange, US_LISTING_EXCHANGES } from "./exchanges";
4
+ import { quarterRows } from "./financial-statements";
5
+
6
+ /** Beyond this either way, a trailing EPS is not net income over the shares. */
7
+ const OWN_EPS_RATIO_LIMIT = 10;
8
+
9
+ /** Nasdaq's fifth letter W, R or U is a warrant, a right or a unit (BZFDW, TDWDR, SAAQU). */
10
+ const NASDAQ_INSTRUMENT = /^[A-Z]{4}([WRU])$/;
11
+ /** NYSE's suffixes: NWAX.WS, ABC.U, ABC.RT. */
12
+ const NYSE_INSTRUMENT = /[.\-/ ](WS|WT|U|RT)(?:\.[A-Z])?$/;
13
+ /** A preferred share's symbol (PSA.PR.U): its last letter is its series, not a unit. */
14
+ const PREFERRED_SYMBOL = /\.PR(?:\.|$)/;
15
+ /** A warrant, right or unit by its name: the word at its end, or before its terms. */
16
+ const INSTRUMENT_NAME =
17
+ /(?:^|[\s,.(-])(warrants?|wts?|rights?|units?)(?:\s*(?:\([^)]*\))?\s*$|[\s,]+(?:each|exp(?:iring|ire|\.)?|exercisable|to\s+(?:purchase|buy|acquire|subscribe)|consisting)\b)/i;
18
+ /**
19
+ * Units that are the share: a partnership's, a trust's, a REIT's, an income
20
+ * fund's, depositary units and a holding company's (Brookfield Renewable
21
+ * Partners L.P. Units, Choice Properties REIT Units, Boralex Income Fund -
22
+ * Units, Icahn Enterprises Depositary Units, Hess Midstream Holdings Unit).
23
+ */
24
+ const SHARE_UNITS = /\b(?:common|partnership|ordinary|stapled|beneficial|trust|lp|l\.p\.|llc|class\s+[a-z]|reit|fund|depositary|holdings?)\s*[-–]?\s*units?\b/i;
25
+ /** A blank-check company's words: its units are a share and a warrant together. */
26
+ const SPAC_NAME = /\b(?:acquisition|blank\s+check|spac)\b/i;
27
+ /** SET's own warrants: JMART-W4. */
28
+ const SET_WARRANT = /-W\d*$/;
29
+ /**
30
+ * A Thai depositary receipt: the foreign company's code and the two-digit
31
+ * number of the Thai broker that issued it (SOFTBANK80, AAPL01, NVDA19). Its
32
+ * ratio to the company's share is the issuer's and is not on record.
33
+ */
34
+ const THAI_RECEIPT = /^[A-Z][A-Z0-9]{1,7}(?:01|03|06|11|13|19|23|24|80)$/;
35
+
36
+ /**
37
+ * A fund's own name: an exchange-traded fund, note or product (a UCITS one
38
+ * too), a Brazilian index fund ("Fundo de Índice", "Classe de Índice"), an
39
+ * index or mutual fund, a unit trust, an investment trust plc. A sponsor's
40
+ * name ("Global X ETFs") is not one, nor is a company named after the unit
41
+ * trusts it runs ("Unit Trust Corporation"), nor "Fund", "Trust" or "REIT"
42
+ * alone (Blackstone Secured Lending Fund, Northern Trust, Federal Realty
43
+ * Investment Trust).
44
+ */
45
+ const FUND_NAMES = [
46
+ /\b(?:ETF|ETN|ETP)\b/,
47
+ /\bUCITS\b/,
48
+ /\bexchange[- ]traded\s+(?:fund|note|product|commodity)\b/i,
49
+ /\b(?:fundos?|classes?)\s+de\s+[íi]ndice\b/i,
50
+ /\b(?:index|mutual)\s+funds?\b/i,
51
+ /\bunit\s+trusts?\b(?!\s+(?:corporation|company|bank)\b)/i,
52
+ /(?<!real[- ]estate\s|property\s)\binvestment\s+trust\s+(?:plc|ltd|limited)\b/i,
53
+ ];
54
+ /**
55
+ * A profile's first sentence saying the line is a fund: "The Inv-GW CHNXT 50
56
+ * ETF is an exchange-traded fund", "Cohen & Steers Infrastructure Fund, Inc.
57
+ * is a closed ended balanced mutual fund", "PIMCO Dynamic Income Fund is a
58
+ * closed ended fixed income mutual fund", "Literacy Capital plc is a British
59
+ * closed-ended investment company", "Sprott Physical Uranium Trust is a
60
+ * closed-end commodity trust", "... is an investment trust", an Australian
61
+ * listed investment company. Closed-end funds and investment trusts are
62
+ * valued on their assets, not their earnings. Not a company that sponsors or
63
+ * runs funds ("is an exchange-traded fund sponsor"), nor a real estate
64
+ * investment trust; a business development company is read apart.
65
+ */
66
+ const FUND_DESCRIPTION =
67
+ /\bis\s+(?:an?\s+|the\s+)?(?:(?:type|kind|form)\s+of\s+)?(?:(?!(?:of|sponsor|provider|manager|issuer|operator|administrator|distributor|advis[eo]r)\b)[\w&,'’-]+\s+){0,3}?(?:exchange[- ]traded\s+(?:funds?|notes?|products?|commodit(?:y|ies))|closed[- ]end(?:ed)?\s+(?:[\w-]+\s+){0,3}?(?:funds?|trusts?|(?:investment|management)\s+(?:compan(?:y|ies)|firms?|vehicles?))|mutual\s+funds?|unit\s+(?:investment\s+)?trusts?|index\s+funds?|listed\s+investment\s+compan(?:y|ies)|(?<!real[- ]estate\s|realty\s|property\s|mortgage\s)investment\s+trusts?)\b(?!\s+(?:sponsor|provider|manager|management|issuer|company|corporation|bank|business|platform|firm|operator|administrator|distributor)s?\b)/i;
68
+ /** A business development company lends to private companies and is valued on its earnings: it keeps its P/E, closed-end or not. */
69
+ const BUSINESS_DEVELOPMENT = /\bbusiness\s+development\s+compan(?:y|ies)\b/i;
70
+ /** Abbreviations whose period does not end a profile's first sentence: Inc., Ltd., Corp., Co., plc., U.S. */
71
+ const ABBREVIATIONS = /\b(?:Inc|Ltd|Corp|Co|Plc|plc|PLC|LLC|Pty|Pvt|Bhd)\.|\b(?:[A-Z]\.){2,}/g;
72
+ /** A profile's first sentence, read past abbreviations. */
73
+ const firstSentence = (text: string): string =>
74
+ text.trim().replace(ABBREVIATIONS, (match) => match.replaceAll(".", "")).split(/\.(?:\s|$)/)[0] ?? "";
75
+ /**
76
+ * The types a source gives a fund, as one exact list (spaces, dashes and
77
+ * underscores dropped, upper case): an exchange-traded fund, note or product,
78
+ * a mutual, money market or closed-end fund, a unit or investment trust.
79
+ * Gloom Cloud's screener reads the same list.
80
+ */
81
+ const FUND_TYPES = new Set([
82
+ "ETF", "ETN", "ETP", "EXCHANGETRADEDFUND", "EXCHANGETRADEDNOTE", "EXCHANGETRADEDPRODUCT", "FUND", "MUTUALFUND",
83
+ "MONEYMARKET", "MONEYMARKETFUND", "CEF", "CLOSEDEND", "CLOSEDENDFUND", "UNITTRUST", "UNITINVESTMENTTRUST", "UIT",
84
+ "INVESTMENTTRUST",
85
+ ]);
86
+ /** Words that name no particular company or fund, left out when two names are compared (ownProfileText). */
87
+ const GENERIC_NAME_WORDS = new Set([
88
+ "the", "and", "inc", "incorporated", "ltd", "limited", "plc", "corp", "corporation", "company", "group", "holdings",
89
+ "holding", "fund", "funds", "etf", "etfs", "etc", "etn", "etp", "trust", "ord", "shares", "share", "class", "common",
90
+ "stock", "units", "unit", "capital", "global", "international", "investment", "investments", "management", "asset",
91
+ "assets", "securities", "index", "ucits", "usd", "eur", "gbp", "acc", "dist", "new", "llc", "pty", "pvt", "bhd",
92
+ "mutual",
93
+ ]);
94
+ const nameWords = (name: string): string[] => [...new Set(name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase()
95
+ .split(/[^a-z0-9]+/).filter((word) => word.length >= 3 && !GENERIC_NAME_WORDS.has(word)))];
96
+ /** Two words name the same thing: equal, or one of four letters or more inside the other (Dspnifty, Nifty). */
97
+ const sameWord = (left: string, right: string): boolean =>
98
+ left === right || (Math.min(left.length, right.length) >= 4 && (left.includes(right) || right.includes(left)));
99
+ /** What a profile's first sentence is about: the words before its verb. */
100
+ const profileSubject = (description: string): string =>
101
+ firstSentence(description).split(/\s+(?:is|was|are|operates|engages|provides)\s/)[0] ?? "";
102
+
103
+ /**
104
+ * Whether a profile's name or first sentence is this listing's own: it shares a word with the quote's name, or names
105
+ * the listing's symbol (IBOV11 Fund). A receipt's profile is its underlying's, which it stands for (COPX on BYMA,
106
+ * Banco Comafi's CEDEAR of the Global X Copper Miners ETF). A profile can be another listing's under the same symbol
107
+ * (USAU, U.S. Gold Corp., carried the name of a Lyxor ETF): such a name says nothing of this listing. Without a quote
108
+ * name, or a word to compare, it stands.
109
+ */
110
+ function ownProfileText(financials: ShareInputs, text: string): boolean {
111
+ const quote = nameWords(financials.quote?.name ?? "");
112
+ const profile = nameWords(text);
113
+ if (!quote.length || !profile.length || isReceipt(financials)) return true;
114
+ if (financials.quote?.cedearRatio ?? financials.fundamentals?.cedearRatio) return true;
115
+ const code = (financials.quote?.symbol ?? "").split(":")[0]!.trim().toUpperCase();
116
+ if (code.length >= 3 && text.toUpperCase().split(/[^A-Z0-9.]+/).includes(code)) return true;
117
+ return profile.some((word) => quote.some((other) => sameWord(word, other)));
118
+ }
119
+
120
+ /**
121
+ * Whether a listing is a fund, whose units are no company's shares: its type (FUND_TYPES), its quote's name, or its
122
+ * profile's name or first sentence where each is the listing's own (ownProfileText). 159682 on SZSE, the ChiNext 50
123
+ * ETF a source types EQUITY, read 0.87x on an EPS of 1.27. Closed-end funds and investment trusts are funds wherever
124
+ * they list (Polar Capital Technology, Scottish Mortgage, Pershing Square, Literacy Capital); a business development
125
+ * company is not. Gloom Cloud's screener reads funds alike.
126
+ */
127
+ function isFund(financials: ShareInputs): boolean {
128
+ if (FUND_TYPES.has((financials.quote?.instrumentType ?? "").replace(/[\s_-]/g, "").toUpperCase())) return true;
129
+ const profileName = financials.profile?.name?.trim() ?? "";
130
+ const names = [financials.quote?.name ?? "", ownProfileText(financials, profileName) ? profileName : ""];
131
+ if (names.some((name) => FUND_NAMES.some((rule) => rule.test(name)))) return true;
132
+ const description = financials.profile?.description ?? "";
133
+ return ownProfileText(financials, profileSubject(description)) && !BUSINESS_DEVELOPMENT.test(description)
134
+ && FUND_DESCRIPTION.test(firstSentence(description));
135
+ }
136
+
137
+ type Instrument = "warrant" | "right" | "unit";
138
+
139
+ const instrumentOf = (code: string): Instrument => {
140
+ const lower = code.toLowerCase();
141
+ return lower.startsWith("r") ? "right" : lower.startsWith("u") ? "unit" : "warrant";
142
+ };
143
+
144
+ type ShareInputs = Pick<TickerFinancials, "quote" | "profile" | "fundamentals">;
145
+ type EpsInputs = ShareInputs & Partial<Pick<TickerFinancials, "financialCurrency" | "annualStatements" | "quarterlyStatements" | "trailingStatement">>;
146
+
147
+ /**
148
+ * Why a listing's price over its company's EPS is no P/E, if it is not: a
149
+ * warrant, a right or a unit is not the share (BZFDW, BuzzFeed's warrant at
150
+ * $0.0054, read 0.03x), and a depositary receipt with no ratio on record is
151
+ * on another count than the share (SOFTBANK80 on SET, a Thai receipt at
152
+ * 7.85 THB over SoftBank's 203.71 THB a share, read 0.04x; AMD on the TSX, a
153
+ * Canadian receipt Gloom Cloud flags because AMD's home line is elsewhere,
154
+ * read 17.1x for about 120x on the share). Gloom Cloud puts a receipt whose
155
+ * ratio is on record on the receipt already (TSM's 5 shares, a CEDEAR's
156
+ * published ratio). A unit is told by its name only on a US venue or for a
157
+ * blank-check company; a REIT's, a fund's or a partnership's units are its
158
+ * share, and PSA.PR.U is a preferred. Nor is a fund's price over the EPS a
159
+ * source gives it a P/E (isFund).
160
+ */
161
+ export function notTheShare(financials: ShareInputs): string | undefined {
162
+ const quote = financials.quote;
163
+ if (!quote) return undefined;
164
+ const venue = canonicalExchange(quote.listingExchangeName || quote.exchangeName);
165
+ const code = (quote.symbol ?? "").split(":")[0]!.trim().toUpperCase();
166
+ const name = quote.name ?? "";
167
+ const named = INSTRUMENT_NAME.exec(name)?.[1];
168
+ const byName = named && !(instrumentOf(named) === "unit"
169
+ && (SHARE_UNITS.test(name) || !(US_LISTING_EXCHANGES.has(venue) || SPAC_NAME.test(name))))
170
+ ? instrumentOf(named) : undefined;
171
+ const bySymbol = PREFERRED_SYMBOL.test(code) ? undefined
172
+ : US_LISTING_EXCHANGES.has(venue)
173
+ ? (venue === "NASDAQ" ? NASDAQ_INSTRUMENT.exec(code)?.[1] : undefined) ?? NYSE_INSTRUMENT.exec(code)?.[1]
174
+ : venue === "SET" && SET_WARRANT.test(code) ? "W" : undefined;
175
+ const instrument = byName ?? (bySymbol ? instrumentOf(bySymbol) : undefined);
176
+ if (instrument) return `a ${instrument} is not the share the EPS is per`;
177
+ if (isFund(financials)) return "a fund is not a company's share";
178
+ const country = financials.profile?.country?.trim().toUpperCase();
179
+ const fundamentals = financials.fundamentals;
180
+ const receipt = quote.isDepositaryReceipt || fundamentals?.isDepositaryReceipt || fundamentals?.shareBasis === "depositary_receipt"
181
+ // Thai receipts are not flagged as receipts.
182
+ || (venue === "SET" && THAI_RECEIPT.test(code) && country !== "TH");
183
+ const ratio = [quote.adrRatio, fundamentals?.adrRatio].some((value) => typeof value === "number" && value > 0)
184
+ || !!(quote.cedearRatio ?? fundamentals?.cedearRatio) || !!fundamentals?.trailingEpsBasis;
185
+ return receipt && !ratio ? "a depositary receipt with no ratio on record to the share the EPS is per" : undefined;
186
+ }
187
+
188
+ const isReceipt = (financials: ShareInputs) => !!(
189
+ financials.quote?.isDepositaryReceipt || financials.fundamentals?.isDepositaryReceipt
190
+ || financials.fundamentals?.shareBasis === "depositary_receipt" || financials.quote?.adrRatio || financials.fundamentals?.adrRatio
191
+ );
192
+
193
+ const finite = (value: number | null | undefined): value is number => typeof value === "number" && Number.isFinite(value);
194
+ /** A per-share figure in a reason: whole above 100, cents above 0.01, else two significant digits (BZT's 0.000089). */
195
+ const perShare = (value: number) => Math.abs(value) >= 100 ? value.toFixed(0)
196
+ : Math.abs(value) >= 0.01 ? value.toFixed(2) : value.toPrecision(2);
197
+ /** A currency's major unit; ZAC is South African cents here, as Gloom Cloud quotes it. */
198
+ const majorCurrency = (currency: string | null | undefined) =>
199
+ resolveCurrencyUnit(currency?.trim() === "ZAC" ? "ZAc" : currency).currency || undefined;
200
+
201
+ /** The latest statement's currency. */
202
+ function statementsCurrency(financials: EpsInputs): string | undefined {
203
+ return [...(financials.quarterlyStatements ?? []), ...(financials.annualStatements ?? [])]
204
+ .filter((row) => row.currency)
205
+ .sort((left, right) => left.date.localeCompare(right.date))
206
+ .at(-1)?.currency;
207
+ }
208
+
209
+ /** The currency of the trailing net income: the block's, else the financials', else the latest statement's. */
210
+ function incomeCurrency(financials: EpsInputs): string | undefined {
211
+ return majorCurrency(financials.fundamentals?.financialCurrency ?? financials.financialCurrency ?? statementsCurrency(financials));
212
+ }
213
+
214
+ const DAY_MS = 86_400_000;
215
+ const SAME_DATE_DAYS = 10;
216
+ const days = (from: string, to: string) => (Date.parse(to) - Date.parse(from)) / DAY_MS;
217
+ const quarterApart = (from: string, to: string) => days(from, to) >= 80 && days(from, to) <= 100;
218
+
219
+ /**
220
+ * The statements' trailing net income or diluted EPS in `currency`: the
221
+ * latest fiscal year when no quarter runs past it, four consecutive quarters,
222
+ * the year plus the half since it where Gloom Cloud serves one, or the latest
223
+ * year plus the quarters since it less the same quarters a year earlier.
224
+ * Gloom Cloud reads the same window to tell an EPS in the reporting currency.
225
+ */
226
+ function statementsTrailing(financials: EpsInputs, currency: string, field: "netIncome" | "eps"): number | undefined {
227
+ const usable = (rows: readonly FinancialStatement[]) => rows
228
+ .filter((row) => finite(row[field]) && Number.isFinite(Date.parse(row.date)) && row.currency === currency)
229
+ .sort((left, right) => left.date.localeCompare(right.date));
230
+ const quarters = usable(quarterRows(financials.quarterlyStatements ?? []));
231
+ const annual = usable(financials.annualStatements ?? []).at(-1);
232
+ const latest = quarters.at(-1);
233
+ const trailing = financials.trailingStatement;
234
+ const served = trailing?.trailing?.method === "annual-plus-interim" && Number.isFinite(Date.parse(trailing.date))
235
+ && trailing.currency === currency && finite(trailing[field])
236
+ && !(annual && days(annual.date, trailing.date) <= SAME_DATE_DAYS)
237
+ && !(latest && days(trailing.date, latest.date) > SAME_DATE_DAYS)
238
+ ? { value: trailing[field], end: trailing.date } : undefined;
239
+ if (!served && annual && (!latest || days(annual.date, latest.date) <= SAME_DATE_DAYS)) return annual[field]!;
240
+ if (!latest) return served?.value;
241
+ const lastFour = quarters.slice(-4);
242
+ if ((!served || Math.abs(days(latest.date, served.end)) <= SAME_DATE_DAYS) && lastFour.length === 4
243
+ && lastFour.every((row, index) => index === 0 || quarterApart(lastFour[index - 1]!.date, row.date))) {
244
+ return lastFour.reduce((total, row) => total + row[field]!, 0);
245
+ }
246
+ if (served) return served.value;
247
+ if (!annual) return undefined;
248
+ const interims = quarters.filter((row) => days(annual.date, row.date) > SAME_DATE_DAYS);
249
+ let previous = annual.date;
250
+ for (const row of interims) {
251
+ if (!quarterApart(previous, row.date)) return undefined;
252
+ previous = row.date;
253
+ }
254
+ const prior = interims.map((row) => quarters.find((candidate) => Math.abs(days(candidate.date, row.date) - 365) <= SAME_DATE_DAYS));
255
+ if (prior.some((row) => !row)) return undefined;
256
+ return annual[field]! + interims.reduce((total, row) => total + row[field]!, 0)
257
+ - prior.reduce((total, row) => total + row![field]!, 0);
258
+ }
259
+
260
+ /** An EPS the statements' own diluted EPS in `currency` matches, within 1% or half a cent (the source rounds to cents). */
261
+ function statementsOwnEps(financials: EpsInputs, currency: string, eps: number): boolean {
262
+ if (eps === 0) return false;
263
+ const annual = (financials.annualStatements ?? [])
264
+ .filter((row) => row.currency === currency && finite(row.eps) && Number.isFinite(Date.parse(row.date)))
265
+ .sort((left, right) => left.date.localeCompare(right.date))
266
+ .at(-1)?.eps;
267
+ return [annual, statementsTrailing(financials, currency, "eps")].some((own) =>
268
+ finite(own) && own !== 0 && Math.abs(eps - own) <= Math.max(0.01 * Math.abs(own), 0.005));
269
+ }
270
+
271
+ /**
272
+ * Why a trailing EPS in the statements' reporting currency beside a price in
273
+ * another gives no P/E: the served block names no rate it was converted at
274
+ * (the served P/E's `trailingPEConversion`). U.UN on the TSX divided its CA$26.47 by a
275
+ * USD 1.64 and read 16.14; NEW on Stuttgart €1.63 by GBP 0.0241, 67.63. The
276
+ * EPS is shown to be in the reporting currency where it is labelled so, sits
277
+ * beside a trailing block in it, the block's net income is the statements'
278
+ * own in it, or the EPS is their own diluted EPS for the latest fiscal year
279
+ * or their trailing twelve months (TBT on MUNICH's 308.64 JPY, Tokuyama's
280
+ * year to March 2026, beside €21.60 read 0.07x). The reason says what is
281
+ * known: Gloom Cloud labels a block's currency only with the rates at hand,
282
+ * so a labelled one was left unconverted because its source's P/E does not
283
+ * match the EPS; an unlabelled one has no conversion on record, which a
284
+ * missing rate and figures that do not tie to the statements both leave, and
285
+ * the payload does not say which. Gloom Cloud's screener, which knows its
286
+ * rates, says "no rate on record" only when it has none.
287
+ * Undefined for an EPS the filed quarters give (in the price's currency), a
288
+ * receipt's on its home line, and one whose currency cannot be told.
289
+ */
290
+ function noRateForEps(financials: EpsInputs): string | undefined {
291
+ const fundamentals = financials.fundamentals;
292
+ const eps = fundamentals?.eps;
293
+ const listing = majorCurrency(financials.quote?.currency);
294
+ const reporting = incomeCurrency(financials);
295
+ if (!fundamentals || !finite(eps) || !listing || !reporting || listing === reporting
296
+ || fundamentals.trailingEpsBasis || fundamentals.trailingEpsSource === "filed-quarters") return undefined;
297
+ const stated = majorCurrency(fundamentals.epsCurrency);
298
+ if (stated === listing) return undefined;
299
+ const conversion = fundamentals.trailingPEConversion;
300
+ if (conversion && majorCurrency(conversion.from) === reporting && finite(conversion.rate) && conversion.rate > 0) return undefined;
301
+ const income = fundamentals.netIncome;
302
+ const statements = finite(income) ? statementsTrailing(financials, reporting, "netIncome") : undefined;
303
+ const inReporting = stated === reporting || (!!fundamentals.financialCurrency && !fundamentals.epsCurrency)
304
+ || (finite(income) && finite(statements) && Math.abs(income - statements) <= 0.01 * Math.max(Math.abs(income), Math.abs(statements)))
305
+ || statementsOwnEps(financials, reporting, eps);
306
+ if (!inReporting) return undefined;
307
+ // Gloom Cloud labels a block's currency only with the rates at hand: such a block was left unconverted because
308
+ // its source's P/E is not the price over that EPS, not for want of a rate.
309
+ return fundamentals.financialCurrency
310
+ ? `EPS (TTM) in ${reporting} beside a price in ${listing}, and the source's P/E does not match that EPS`
311
+ : `EPS (TTM) in ${reporting} beside a price in ${listing}, with no conversion on record`;
312
+ }
313
+
314
+ /**
315
+ * Why a trailing EPS is not the company's, if it is not: of the other sign
316
+ * than the block's trailing net income over its shares outstanding, or more
317
+ * than OWN_EPS_RATIO_LIMIT times off it either way. STKH served an EPS of
318
+ * 96.00 beside a 7.01M loss over 605,876 shares (-11.57) and read 0.02x;
319
+ * SNBN's 577,618 CHF over 100,000 shares is its own and stands at 0.01x. The
320
+ * size is judged only on one share and in one currency: not for a receipt,
321
+ * whose shares can be ordinary ones, and not where the EPS is in another
322
+ * currency than the net income. The net income is in the block's currency,
323
+ * else the financials', else the latest statement's; the EPS in the one it
324
+ * is labelled in, else the statements' for one summed from the filed
325
+ * quarters, else the listing's. PAN on the JSE reports in dollars and is
326
+ * quoted in rand: its EPS of 2.98 beside 0.07 dollars a share is no sign of
327
+ * another company's. Undefined without the three figures.
328
+ */
329
+ export function epsAgainstIncome(financials: EpsInputs): string | undefined {
330
+ const fundamentals = financials.fundamentals;
331
+ const eps = fundamentals?.eps;
332
+ const income = fundamentals?.netIncome;
333
+ const shares = fundamentals?.sharesOutstanding;
334
+ if (!finite(eps) || eps === 0 || !finite(income) || income === 0 || !finite(shares) || shares <= 0) return undefined;
335
+ const own = income / shares;
336
+ const text = `trailing net income over shares outstanding (${perShare(own)})`;
337
+ if (Math.sign(eps) !== Math.sign(own)) return `EPS (TTM) ${perShare(eps)} has the other sign than ${text}`;
338
+ const epsCurrency = majorCurrency(fundamentals?.epsCurrency
339
+ ?? (fundamentals?.trailingEpsSource === "filed-quarters" ? statementsCurrency(financials) : undefined)
340
+ ?? financials.quote?.currency);
341
+ const incomeIn = incomeCurrency(financials);
342
+ if (isReceipt(financials) || (epsCurrency && incomeIn && epsCurrency !== incomeIn)) return undefined;
343
+ const ratio = eps / own;
344
+ return ratio > OWN_EPS_RATIO_LIMIT || ratio < 1 / OWN_EPS_RATIO_LIMIT
345
+ ? `EPS (TTM) ${perShare(eps)} is more than ${OWN_EPS_RATIO_LIMIT} times off ${text}`
346
+ : undefined;
347
+ }
348
+
349
+ type Withdrawn = NonNullable<Fundamentals["notMeaningful"]>;
350
+
351
+ /**
352
+ * The financials with the multiples that are no multiple of the share
353
+ * withdrawn and their reason under `notMeaningful`: every P/E and the PEG of
354
+ * a warrant, a right, a unit or a receipt with no ratio (notTheShare), and
355
+ * the trailing P/E and the PEG over an EPS in another currency with no rate
356
+ * (noRateForEps) or one that is not the company's (epsAgainstIncome), in
357
+ * that order. Only a multiple the block has, or a trailing one its EPS would
358
+ * give, is withdrawn: one it never had stays absent. Reads the trailing EPS
359
+ * withFiledTrailingEps leaves, so it runs after it. Returns the same object
360
+ * when nothing is withdrawn.
361
+ */
362
+ export function withShareMultiples<T extends EpsInputs>(financials: T): T {
363
+ const fundamentals = financials.fundamentals;
364
+ if (!fundamentals) return financials;
365
+ const share = notTheShare(financials);
366
+ const reason = share ?? noRateForEps(financials) ?? epsAgainstIncome(financials);
367
+ // A multiple an earlier pass withdrew is one the block had.
368
+ const had = fundamentals.notMeaningful ?? {};
369
+ const has: Record<keyof Withdrawn, boolean> = {
370
+ trailingPE: finite(fundamentals.trailingPE) || finite(fundamentals.eps) || !!had.trailingPE,
371
+ forwardPE: !!share && (finite(fundamentals.forwardPE) || !!had.forwardPE),
372
+ pegRatio: finite(fundamentals.pegRatio) || !!had.pegRatio,
373
+ };
374
+ const fields = reason ? (Object.keys(has) as Array<keyof Withdrawn>).filter((field) => has[field]) : [];
375
+ const reasons: Withdrawn = Object.fromEntries(fields.map((field) => [field, reason]));
376
+ if (fields.length === 0) {
377
+ if (!fundamentals.notMeaningful) return financials;
378
+ const { notMeaningful: _stale, ...rest } = fundamentals;
379
+ return { ...financials, fundamentals: rest };
380
+ }
381
+ const next: Fundamentals = { ...fundamentals, notMeaningful: reasons };
382
+ for (const field of fields) delete next[field];
383
+ return { ...financials, fundamentals: next };
384
+ }
@@ -26,6 +26,17 @@ export function withoutControlCharacters(value: string): string {
26
26
  return HAS_COMMAND_CONTROL.test(value) ? value.replace(COMMAND_CONTROL, "") : value;
27
27
  }
28
28
 
29
+ /**
30
+ * At most `maxLength` UTF-16 units of `value`, as a JavaScript string or a
31
+ * JSON Schema `maxLength` counts them, cut before a surrogate pair rather than
32
+ * through it, so an emoji at the limit is left out instead of halved.
33
+ */
34
+ export function sliceWholeCharacters(value: string, maxLength: number): string {
35
+ if (value.length <= maxLength) return value;
36
+ const last = value.charCodeAt(maxLength - 1);
37
+ return value.slice(0, last >= 0xd800 && last <= 0xdbff ? maxLength - 1 : maxLength);
38
+ }
39
+
29
40
  /**
30
41
  * Text another person's app wrote (a shared pane's item, a share's title), as
31
42
  * one line that draws as what it says: no terminal escape sequence, control