@gloom-sh/terminal 0.19.6 → 0.20.0

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 (137) hide show
  1. package/LICENSE +0 -4
  2. package/package.json +6 -5
  3. package/patches/electrobun-devkit@2.0.5.patch +148 -0
  4. package/src/api-client/bond-trades.ts +59 -0
  5. package/src/api-client/data.ts +21 -0
  6. package/src/api-client/index.ts +2 -0
  7. package/src/api-client/types/account.ts +86 -0
  8. package/src/api-client/types/assist.ts +32 -0
  9. package/src/api-client/types/auth.ts +63 -0
  10. package/src/api-client/types/billing.ts +54 -0
  11. package/src/api-client/types/chat.ts +180 -0
  12. package/src/api-client/types/congress.ts +107 -0
  13. package/src/api-client/types/credit.ts +110 -0
  14. package/src/api-client/types/econ.ts +158 -0
  15. package/src/api-client/types/equity-diagnostic.ts +73 -0
  16. package/src/api-client/types/filings-and-calls.ts +350 -0
  17. package/src/api-client/types/index.ts +25 -0
  18. package/src/api-client/types/jobs.ts +147 -0
  19. package/src/api-client/types/market.ts +122 -0
  20. package/src/api-client/types/news.ts +91 -0
  21. package/src/api-client/types/notes-and-theses.ts +172 -0
  22. package/src/api-client/types/quotes.ts +28 -0
  23. package/src/api-client/types/scanners.ts +125 -0
  24. package/src/api-client/types/screener.ts +65 -0
  25. package/src/api-client/types/search.ts +107 -0
  26. package/src/api-client/types/sync.ts +14 -0
  27. package/src/api-client/types/team-collections.ts +43 -0
  28. package/src/api-client/types/team-views.ts +32 -0
  29. package/src/api-client/types/teams.ts +135 -0
  30. package/src/api-client/types/ticker-data.ts +57 -0
  31. package/src/api-client/types/tweets.ts +59 -0
  32. package/src/api-client/types/world-venues.ts +23 -0
  33. package/src/app/runtime/desktop-deeplink.ts +41 -6
  34. package/src/app/star-prompt/status-line.tsx +1 -1
  35. package/src/app.tsx +1 -7
  36. package/src/architecture/ui-tokens-allowlist.json +0 -8
  37. package/src/cli/commands/ticker.ts +17 -4
  38. package/src/cli/desktop-pane-shot-browser.ts +69 -3
  39. package/src/cli/pane-functions/catalog.ts +3 -1
  40. package/src/components/chart/composite/use-composite-chart-keyboard.ts +11 -2
  41. package/src/components/data-table/export.ts +4 -1
  42. package/src/components/layout/detached-pane-shell.tsx +10 -37
  43. package/src/components/layout/double-escape-close.ts +90 -0
  44. package/src/components/layout/header.tsx +3 -2
  45. package/src/components/layout/market-summary.ts +6 -3
  46. package/src/components/layout/pane/footer/index.tsx +2 -6
  47. package/src/components/layout/pane/footer/model.ts +6 -12
  48. package/src/components/layout/shell/active-drag.ts +53 -11
  49. package/src/components/layout/shell/drag/magnets.ts +128 -19
  50. package/src/components/layout/shell/pane/actions.ts +6 -2
  51. package/src/components/layout/shell/pane/management-shortcuts.ts +13 -51
  52. package/src/components/layout/status-bar.tsx +4 -78
  53. package/src/components/layout/status-widget-space.ts +5 -5
  54. package/src/components/onboarding/portfolio-step/positions-panel.tsx +1 -1
  55. package/src/components/ui/data-table/index.tsx +5 -1
  56. package/src/components/ui/data-table/render-cell.ts +19 -0
  57. package/src/components/ui/delayed-mark.tsx +59 -7
  58. package/src/components/ui/icon.tsx +1 -8
  59. package/src/components/ui/menu.tsx +6 -1
  60. package/src/i18n/es.ts +3 -3
  61. package/src/i18n/ja.ts +3 -3
  62. package/src/i18n/ko.ts +3 -3
  63. package/src/i18n/zh-cn.ts +3 -3
  64. package/src/i18n/zh-tw.ts +3 -3
  65. package/src/plugins/builtin/chat/content/composer.tsx +21 -27
  66. package/src/plugins/builtin/chat/content/index.tsx +31 -3
  67. package/src/plugins/builtin/chat/content/shortcuts.ts +4 -2
  68. package/src/plugins/builtin/chat/content/snapshot.ts +0 -3
  69. package/src/plugins/builtin/cloud/auth-actions.tsx +51 -23
  70. package/src/plugins/builtin/cloud/trial-offer-status-widget.tsx +3 -3
  71. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +32 -25
  72. package/src/plugins/builtin/congress-trades/model.ts +2 -1
  73. package/src/plugins/builtin/congress-trades/pane.tsx +3 -0
  74. package/src/plugins/builtin/custom-view/index.tsx +1 -1
  75. package/src/plugins/builtin/custom-view/loader.ts +85 -8
  76. package/src/plugins/builtin/custom-view/view-spec.ts +28 -0
  77. package/src/plugins/builtin/equity-screener/criterion-editor.tsx +13 -4
  78. package/src/plugins/builtin/equity-screener/headless.ts +33 -1
  79. package/src/plugins/builtin/equity-screener/model.ts +58 -15
  80. package/src/plugins/builtin/equity-screener/pane.tsx +36 -6
  81. package/src/plugins/builtin/executives/format.ts +5 -4
  82. package/src/plugins/builtin/executives/pane.tsx +1 -1
  83. package/src/plugins/builtin/help/index.tsx +55 -1
  84. package/src/plugins/builtin/insider/model.ts +30 -2
  85. package/src/plugins/builtin/jobs/model.ts +2 -2
  86. package/src/plugins/builtin/mna/model.ts +2 -2
  87. package/src/plugins/builtin/notes/files.ts +2 -0
  88. package/src/plugins/builtin/notes/owner.tsx +20 -1
  89. package/src/plugins/builtin/notes/quick-notes-pane.tsx +22 -4
  90. package/src/plugins/builtin/notes/store.ts +6 -1
  91. package/src/plugins/builtin/portfolio-list/header.tsx +1 -1
  92. package/src/plugins/builtin/research/corporate-actions-pane.tsx +29 -25
  93. package/src/plugins/builtin/series-inventory.ts +1 -0
  94. package/src/plugins/builtin/shared/earnings-report.ts +7 -2
  95. package/src/plugins/builtin/shared/use-quote-board.ts +85 -46
  96. package/src/plugins/builtin/short-interest/headless.ts +1 -1
  97. package/src/plugins/builtin/short-interest/model.ts +15 -6
  98. package/src/plugins/builtin/short-interest/types.ts +2 -0
  99. package/src/plugins/builtin/thirteenf/overlap-pane.tsx +3 -0
  100. package/src/plugins/builtin/thirteenf/pane.tsx +3 -0
  101. package/src/plugins/builtin/ticker-detail/overview/model.ts +5 -3
  102. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +4 -4
  103. package/src/plugins/builtin/trace-bonds/detail.tsx +198 -0
  104. package/src/plugins/builtin/trace-bonds/headless.ts +62 -4
  105. package/src/plugins/builtin/trace-bonds/history.ts +155 -0
  106. package/src/plugins/builtin/trace-bonds/pane.tsx +64 -5
  107. package/src/plugins/installer.ts +16 -3
  108. package/src/plugins/plugin-names.ts +11 -2
  109. package/src/remote/controller.ts +9 -2
  110. package/src/remote/schema.ts +2 -1
  111. package/src/renderers/cloudflare/http-proxy.ts +67 -8
  112. package/src/renderers/cloudflare/proxy-session.ts +1 -1
  113. package/src/renderers/cloudflare/worker.ts +29 -2
  114. package/src/renderers/dom/desktop/icons.tsx +0 -2
  115. package/src/renderers/dom/styles.css +0 -3
  116. package/src/renderers/electrobun/bun/desktop/install-records.ts +59 -0
  117. package/src/renderers/electrobun/bun/desktop/installer-folder.ts +208 -592
  118. package/src/renderers/electrobun/bun/desktop/macos-objc.ts +14 -0
  119. package/src/renderers/electrobun/bun/desktop/update.ts +1 -1
  120. package/src/renderers/electrobun/bun/index.ts +19 -13
  121. package/src/renderers/electrobun/bun/window/create.ts +23 -3
  122. package/src/renderers/electrobun/bun/window/electrobun-window-host.ts +4 -4
  123. package/src/renderers/electrobun/bun/window/events.ts +4 -4
  124. package/src/renderers/electrobun/bun/window/frame.ts +2 -1
  125. package/src/renderers/electrobun/bun/window/native-min-size.ts +322 -0
  126. package/src/renderers/electrobun/view/backend-rpc.ts +1 -1
  127. package/src/sources/gloomberb-cloud/index.ts +5 -7
  128. package/src/sources/provider-router/batches.ts +18 -3
  129. package/src/sources/provider-router/financials.ts +18 -4
  130. package/src/types/data-provider.ts +14 -0
  131. package/src/types/financials.ts +15 -3
  132. package/src/types/headless.ts +2 -0
  133. package/src/utils/double-escape-close.ts +38 -16
  134. package/src/utils/format.ts +23 -3
  135. package/src/utils/price-earnings.ts +18 -0
  136. package/patches/electrobun@1.18.1.patch +0 -633
  137. package/src/api-client/types.ts +0 -2441
@@ -62,8 +62,7 @@ import { describeFundamentalMarketCap } from "../../../utils/market-capitalizati
62
62
  import { liveFiftyTwoWeekRange, liveMarketCapitalization } from "../../../market-data/quotes/live-valuation";
63
63
  import { instrumentTypeLabel } from "../../../tickers/instrument-kind";
64
64
  import { ClippedText } from "../../../components/ui/display";
65
- import { DelayedMark, delayedMarkWidth } from "../../../components/ui/delayed-mark";
66
- import { useFreeQuoteDelay } from "../../../api-client/plan-access";
65
+ import { DelayedMark, delayedMarkWidth, useDelayedMarkMinutes } from "../../../components/ui/delayed-mark";
67
66
  import { safeExternalUrl } from "../../../utils/external-url";
68
67
  import { cashRunway, SHORT_RUNWAY_HISTORY } from "../../../utils/cash-runway";
69
68
  import { useOfferingNote } from "./financials/offerings";
@@ -151,7 +150,7 @@ function ResolvedOverviewTab({ width, height, focused = false, ticker, financial
151
150
  const figureCells = useFigureCells();
152
151
 
153
152
  const quote = financials?.quote;
154
- const quoteDelayMinutes = useFreeQuoteDelay(quote);
153
+ const quoteDelayMinutes = useDelayedMarkMinutes(quote);
155
154
  const fundamentals = financials?.fundamentals;
156
155
  const capitalization = liveMarketCapitalization(quote, fundamentals);
157
156
  const profile = financials?.profile;
@@ -276,7 +275,8 @@ function ResolvedOverviewTab({ width, height, focused = false, ticker, financial
276
275
  const venueText = listingVenue ? (companyName ? ` (${listingVenue})` : listingVenue) : "";
277
276
  const sessionLabel = quoteSessionLabel(quote);
278
277
  const marketStateText = sessionLabel ? t(sessionLabel) : "";
279
- // Signed out or free, the headline price is the delayed one: the mark says so after the session.
278
+ // Signed out or free, the headline price is the delayed one. The status bar says so for the
279
+ // app; where it is hidden, or in a capture of the pane alone, the mark says so after the session.
280
280
  const delayMinutes = sessionQuote ? quoteDelayMinutes : null;
281
281
  const delayCells = delayMinutes != null ? delayedMarkWidth(delayMinutes, nativePaneChrome === true) + 1 : 0;
282
282
  const hasIdentityLine = Boolean(companyName || venueText || marketStateText || delayMinutes != null);
@@ -0,0 +1,198 @@
1
+ import { useCallback, useMemo, useState } from "react";
2
+ import {
3
+ ChartTableHeader,
4
+ DataTableView,
5
+ loadingText,
6
+ spanAxisFormatter,
7
+ staticSeries,
8
+ useChartTableSelection,
9
+ type DataTableCell,
10
+ type DataTableColumn,
11
+ type StatItem,
12
+ } from "../../../components";
13
+ import { fitChartTableColumns } from "../../../components/chart-table";
14
+ import type { StoredBondPayload, StoredBondPrint } from "../../../api-client/bond-trades";
15
+ import { colors } from "../../../theme/colors";
16
+ import { MISSING_VALUE } from "../../../utils/format";
17
+ import { compareSortValues, nextHeaderSort, type SortPreference } from "../../../utils/sort-values";
18
+ import type { CorporateBond } from "./client";
19
+ import { bondPricePoints, formatPrintSide, formatPrintSize, standingPrints } from "./history";
20
+ import { formatBondDecimal } from "./model";
21
+
22
+ type PrintColumnId = "date" | "time" | "price" | "yield" | "size" | "side";
23
+ type PrintColumn = DataTableColumn & { id: PrintColumnId };
24
+
25
+ /** A kept print as a row: its place in the read names it, as two prints can share every field. */
26
+ interface PrintRow extends StoredBondPrint {
27
+ id: string;
28
+ }
29
+
30
+ const PRINT_COLUMNS: readonly PrintColumn[] = [
31
+ { id: "date", label: "Date", width: 11, align: "left" },
32
+ { id: "price", label: "Price", width: 9, align: "right" },
33
+ { id: "yield", label: "Yield", width: 8, align: "right" },
34
+ { id: "size", label: "Size", width: 7, align: "right" },
35
+ { id: "time", label: "Time", width: 9, align: "left" },
36
+ { id: "side", label: "Side", width: 5, align: "left" },
37
+ ];
38
+ /** A narrow pane keeps what was printed and when; the time of day and the dealer's side go first. */
39
+ const PRINT_DROP_ORDER: readonly PrintColumnId[] = ["side", "time", "size"];
40
+
41
+ type PrintSort = SortPreference<PrintColumnId>;
42
+ /** Newest print first; a third header click returns here. */
43
+ const DEFAULT_PRINT_SORT: PrintSort = { columnId: "date", direction: "desc" };
44
+
45
+ function printSortValue(columnId: PrintColumnId, row: PrintRow): string | number | null {
46
+ switch (columnId) {
47
+ case "date":
48
+ return `${row.date} ${row.time ?? ""}`;
49
+ case "time":
50
+ return row.time;
51
+ case "price":
52
+ return row.price;
53
+ case "yield":
54
+ return row.yield;
55
+ case "size":
56
+ return row.quantity;
57
+ case "side":
58
+ return row.side;
59
+ }
60
+ }
61
+
62
+ /** Rows in the sort, ties in the order the read listed them (newest first). */
63
+ function sortPrints(rows: readonly PrintRow[], sort: PrintSort): PrintRow[] {
64
+ const columnId = sort.columnId ?? "date";
65
+ return rows
66
+ .map((row, index) => ({ row, index }))
67
+ .sort((left, right) => compareSortValues(printSortValue(columnId, left.row), printSortValue(columnId, right.row), sort.direction)
68
+ || left.index - right.index)
69
+ .map(({ row }) => row);
70
+ }
71
+
72
+ const isPrintColumnId = (value: string): value is PrintColumnId => PRINT_COLUMNS.some((column) => column.id === value);
73
+
74
+ const NO_ROWS: PrintRow[] = [];
75
+ const printDate = (row: PrintRow) => new Date(`${row.date}T00:00:00Z`);
76
+ const printId = (row: PrintRow) => row.id;
77
+ /** Prices on the chart's axis: `52.5`, `101.25`. */
78
+ const formatPriceAxis = spanAxisFormatter((value, digits) => value.toFixed(digits));
79
+
80
+ function renderPrintCell(row: PrintRow, column: PrintColumn): DataTableCell {
81
+ switch (column.id) {
82
+ case "date":
83
+ return { text: row.date, value: row.date, color: colors.textMuted };
84
+ case "time":
85
+ return { text: row.time ?? MISSING_VALUE, color: colors.textDim };
86
+ case "price":
87
+ return { text: formatBondDecimal(row.price, 3), value: row.price, color: colors.textBright };
88
+ case "yield":
89
+ return { text: formatBondDecimal(row.yield, 3), value: row.yield, color: colors.text };
90
+ case "size":
91
+ return { text: formatPrintSize(row), value: row.quantity, color: colors.text };
92
+ case "side":
93
+ return { text: formatPrintSide(row.side), color: colors.textDim };
94
+ }
95
+ }
96
+
97
+ /**
98
+ * One bond's kept history: its last sale and since when its prints are kept,
99
+ * the daily closes as a line, then the prints behind them, newest first. The
100
+ * selected print is the chart's cursor. Without Gloom Pro, or while the
101
+ * history loads, the band says so and the table waits.
102
+ */
103
+ export function BondHistoryDetail({
104
+ bond,
105
+ history,
106
+ loading,
107
+ refusal,
108
+ focused,
109
+ width,
110
+ height,
111
+ }: {
112
+ bond: CorporateBond;
113
+ history: StoredBondPayload | null;
114
+ loading: boolean;
115
+ /** Why no history is read (`Kept price history needs Gloom Pro.`), or null. */
116
+ refusal: string | null;
117
+ focused: boolean;
118
+ width: number;
119
+ height: number;
120
+ }) {
121
+ const [sort, setSort] = useState<PrintSort>(DEFAULT_PRINT_SORT);
122
+ const listed = useMemo<PrintRow[]>(
123
+ () => (history ? standingPrints(history.trades).map((print, index) => ({ ...print, id: `${print.date}_${print.time ?? ""}_${index}` })) : NO_ROWS),
124
+ [history],
125
+ );
126
+ const rows = useMemo(() => sortPrints(listed, sort), [listed, sort]);
127
+ const [selectedId, setSelectedId] = useState<string | null>(null);
128
+ const shownId = selectedId && rows.some((row) => row.id === selectedId) ? selectedId : rows[0]?.id ?? null;
129
+ const select = useCallback((id: string | null) => setSelectedId(id), []);
130
+ const link = useChartTableSelection({ rows, getId: printId, getDate: printDate, selectedId: shownId, onSelect: select, focused });
131
+ // A server from before daily closes were served answers none.
132
+ const series = useMemo(() => [staticSeries(
133
+ bondPricePoints(history?.days ?? []),
134
+ { id: "bond-price", label: "Price", color: colors.positive, calendarSpaced: true },
135
+ )], [history]);
136
+ const charted = series[0]!.points.filter((point) => point.value != null).length;
137
+ const figures: StatItem[] = [
138
+ { id: "price", label: "Last", value: formatBondDecimal(bond.lastSalePrice, 3), ...(bond.lastTradeDate ? { detail: bond.lastTradeDate } : {}) },
139
+ { id: "yield", label: "Yield", value: formatBondDecimal(bond.lastSaleYield, 3) },
140
+ ...(history?.keptSince ? [{
141
+ id: "kept",
142
+ label: "Kept since",
143
+ value: history.keptSince,
144
+ ...(history.backfillPending ? { detail: "earlier prints being read", detailVariants: ["reading earlier"] } : {}),
145
+ }] : []),
146
+ ...(bond.cusip ? [{ id: "cusip", label: "CUSIP", value: bond.cusip }] : []),
147
+ ];
148
+ const columns = useMemo(() => fitChartTableColumns(PRINT_COLUMNS, width, PRINT_DROP_ORDER), [width]);
149
+ const empty = refusal
150
+ ?? (history?.backfillPending ? "No kept prints yet; the source's earlier prints are still being read." : null)
151
+ ?? (history?.keptSince ? `No kept prints since ${history.keptSince}.` : "No kept prints.");
152
+ const header = (
153
+ <ChartTableHeader
154
+ width={width}
155
+ height={height}
156
+ tableRows={rows.length}
157
+ figures={figures}
158
+ tableColumns={columns}
159
+ chart={charted >= 2 || loading ? {
160
+ series,
161
+ formatValue: (value: number) => formatBondDecimal(value, 3),
162
+ formatAxisValue: formatPriceAxis,
163
+ remoteKind: "bond-price-history",
164
+ loading,
165
+ ...link,
166
+ } : null}
167
+ />
168
+ );
169
+ return (
170
+ <DataTableView<PrintRow, PrintColumn>
171
+ focused={focused}
172
+ rootWidth={width}
173
+ rootHeight={height}
174
+ rootBefore={header}
175
+ selection={{ kind: "id", selectedId: shownId, getId: printId, onChange: select }}
176
+ columns={columns}
177
+ items={rows}
178
+ sortColumnId={sort.columnId}
179
+ sortDirection={sort.direction}
180
+ onHeaderClick={(columnId) => {
181
+ if (isPrintColumnId(columnId)) {
182
+ setSort((current) => nextHeaderSort(current, columnId, {
183
+ firstDirection: (id) => (id === "side" ? "asc" : "desc"),
184
+ resetTo: DEFAULT_PRINT_SORT,
185
+ }));
186
+ }
187
+ }}
188
+ onSortChange={(columnId, direction) => {
189
+ if (isPrintColumnId(columnId)) setSort({ columnId, direction });
190
+ }}
191
+ resetScrollKey={`${sort.columnId ?? ""}:${sort.direction}`}
192
+ getItemKey={printId}
193
+ renderCell={renderPrintCell}
194
+ selectedTextOverridesCellColor
195
+ emptyStateTitle={loading ? loadingText("kept prints") : empty}
196
+ />
197
+ );
198
+ }
@@ -5,10 +5,21 @@ import {
5
5
  fetchBondTape,
6
6
  issuerFallbackText,
7
7
  noPrintsText,
8
+ parseBondQuery,
8
9
  quotedCompanyName,
9
10
  type CorporateBond,
10
11
  } from "./client";
11
12
  import { bondStackPriority, formatBondChange, formatBondDecimal, sharesOneIssuer, type BondColumnId } from "./model";
13
+ import {
14
+ HISTORY_RANGES,
15
+ keptSinceText,
16
+ pricedDays,
17
+ readStoredHistory,
18
+ storedHistoryRefusal,
19
+ type HistoryRange,
20
+ } from "./history";
21
+ import { logFailure } from "../../../utils/log-failure";
22
+ import type { StoredBondPayload } from "../../../api-client/bond-trades";
12
23
 
13
24
  const decimal = (digits: number) => (value: unknown) => (
14
25
  typeof value === "number" ? formatBondDecimal(value, digits) : "—"
@@ -57,6 +68,29 @@ function reportRow(bond: CorporateBond) {
57
68
  };
58
69
  }
59
70
 
71
+ const HISTORY_COLUMNS: HeadlessPaneColumn[] = [
72
+ { key: "date", header: "Date" },
73
+ { key: "price", header: "Price", align: "right", format: decimal(3) },
74
+ { key: "yield", header: "Yield", align: "right", format: decimal(3) },
75
+ { key: "prints", header: "Prints", align: "right" },
76
+ ];
77
+
78
+ /** A bond's kept daily closes in the range, newest first, titled by since when prints are kept. */
79
+ function historySection(history: StoredBondPayload, range: HistoryRange) {
80
+ const days = HISTORY_RANGES.find((entry) => entry.value === range)!.days;
81
+ const from = new Date(Date.parse(`${history.to}T00:00:00Z`) - (days - 1) * 86_400_000).toISOString().slice(0, 10);
82
+ // A server from before daily closes were served answers none.
83
+ const rows = pricedDays(history.days ?? []).filter((day) => day.date >= from).reverse();
84
+ return {
85
+ title: history.keptSince ? `Daily closes, kept since ${history.keptSince}` : "Daily closes",
86
+ columns: HISTORY_COLUMNS,
87
+ rows: rows.map((day) => ({ id: day.date, date: day.date, price: day.price, yield: day.yield, prints: day.prints })),
88
+ empty: history.backfillPending
89
+ ? "No kept prints yet; the source's earlier prints are still being read."
90
+ : `No kept prints since ${from}.`,
91
+ };
92
+ }
93
+
60
94
  /** The latest corporate and agency bond sales, or one issuer's, symbol's or CUSIP's, asked of the tape itself. */
61
95
  export const traceBondsHeadless: HeadlessPaneDefinition<"bundle"> = {
62
96
  shape: "bundle",
@@ -66,20 +100,37 @@ export const traceBondsHeadless: HeadlessPaneDefinition<"bundle"> = {
66
100
  placeholder: "issuer, symbol or CUSIP",
67
101
  description: "Issuer name (matched from its start), symbol root, stock ticker or CUSIP. Leave it out for the market's latest sales.",
68
102
  },
69
- options: [],
103
+ options: [
104
+ {
105
+ key: "range",
106
+ type: "enum",
107
+ description: "How far back a CUSIP's kept daily closes reach (Gloom Pro).",
108
+ values: HISTORY_RANGES.map((entry) => ({ value: entry.value })),
109
+ defaultValue: "3M",
110
+ example: "--range 1Y",
111
+ },
112
+ ],
70
113
  discovery: {
71
114
  aliases: ["TRACE"],
72
- dataRequirements: ["Corporate and agency bond last sales"],
115
+ dataRequirements: ["Corporate and agency bond last sales", "Kept bond prints (Gloom Pro)"],
73
116
  limitations: [
74
117
  "One page of 100 bonds, most recent last sale first",
75
118
  "An issuer name matches the start of the issuer's name; a symbol matches the tape's own symbol root, which can differ from the stock ticker. A ticker with no bonds under either is asked once more by the name its quote gives the company",
76
119
  "An issuer's bonds that have matured are left out; a CUSIP shows its bond either way",
120
+ "A CUSIP or a ticker looked up here is kept from then on, with the prints the source still publishes for it (about three years); a CUSIP's daily closes start where its prints are kept, and nothing before that is shown",
77
121
  ],
78
122
  },
79
123
  describe: "Latest corporate and agency bond sales",
80
124
  freshness: { source: "FINRA", status: "not-a-feed", basis: "last sales", observedKey: "lastTradeDate" },
81
125
  async load(args, ctx) {
82
126
  const argument = Array.isArray(args.argument) ? args.argument.join(" ") : args.argument ?? "";
127
+ // A CUSIP's kept history, and a ticker's bonds kept from now on, read beside the tape: Gloom Pro, and never what fails it.
128
+ const stored = readStoredHistory(parseBondQuery(argument), ctx.apiClient, { signal: ctx.signal })
129
+ .then((history) => ({ history, note: null }))
130
+ .catch((error: unknown) => {
131
+ if (ctx.signal.aborted) return { history: null, note: null };
132
+ return { history: null, note: storedHistoryRefusal(error) ?? logFailure("trace-bonds.headless", "Load kept bond prints failed", "Kept price history unavailable.")(error) };
133
+ });
83
134
  const tape = await fetchBondTape(argument, {
84
135
  signal: ctx.signal,
85
136
  // A stock ticker with no bonds of its own: its company, as its quote names it.
@@ -90,6 +141,10 @@ export const traceBondsHeadless: HeadlessPaneDefinition<"bundle"> = {
90
141
  });
91
142
  const { query, bonds, tradeDate, truncated, issuer, failures } = tape;
92
143
  const shown = issuer && bonds.length > 0;
144
+ const range = (HISTORY_RANGES.some((entry) => entry.value === args.options.range) ? args.options.range : "3M") as HistoryRange;
145
+ const { history, note: historyNote } = await stored;
146
+ ctx.signal.throwIfAborted();
147
+ const kept = history ? keptSinceText(history) : null;
93
148
  return {
94
149
  sections: [{
95
150
  // An empty answer is its message alone, dated in its own words.
@@ -97,10 +152,12 @@ export const traceBondsHeadless: HeadlessPaneDefinition<"bundle"> = {
97
152
  columns: reportColumns(bonds),
98
153
  rows: bonds.map(reportRow),
99
154
  ...(query ? { empty: noPrintsText(query, tradeDate, issuer) } : {}),
100
- }],
155
+ }, ...(history ? [historySection(history, range)] : [])],
101
156
  complete: failures.length === 0,
102
157
  ...(failures.length > 0 ? { errors: failures } : {}),
103
- ...(truncated ? { notes: [TRUNCATED_TEXT] } : {}),
158
+ ...(truncated || kept || historyNote ? {
159
+ notes: [...(truncated ? [TRUNCATED_TEXT] : []), ...(kept ? [kept] : []), ...(historyNote ? [historyNote] : [])],
160
+ } : {}),
104
161
  ...(shown ? { warnings: [issuerFallbackText(query!, issuer)] } : {}),
105
162
  metadata: {
106
163
  tradeDate,
@@ -108,6 +165,7 @@ export const traceBondsHeadless: HeadlessPaneDefinition<"bundle"> = {
108
165
  ...(query ? { query: query.text } : {}),
109
166
  ...(issuer ? { issuerName: issuer.name, company: issuer.company } : {}),
110
167
  ...(truncated ? { truncated } : {}),
168
+ ...(history ? { keptSince: history.keptSince, backfillPending: history.backfillPending } : {}),
111
169
  },
112
170
  // One issuer's rows are each issue's own last sale, however old: a history, not stale rows.
113
171
  ...(query ? { freshness: { oldest: null } } : {}),
@@ -0,0 +1,155 @@
1
+ import { ApiRequestError } from "../../../api-client/errors";
2
+ import {
3
+ BOND_HISTORY_MAX_DAYS,
4
+ type StoredBondDay,
5
+ type StoredBondPayload,
6
+ type StoredBondPrint,
7
+ } from "../../../api-client/bond-trades";
8
+ import type { apiClient } from "../../../api-client";
9
+ import { signalWithTimeout } from "../../../utils/async-deadline";
10
+ import { formatCompact, MISSING_VALUE } from "../../../utils/format";
11
+ import { zonedDateKey } from "../../../utils/zoned-date-time";
12
+ import type { BondQuery } from "./client";
13
+ import type { TimeSeriesPoint } from "../../../time-series/types";
14
+
15
+ const TAPE_TIME_ZONE = "America/New_York";
16
+ const DAY_MS = 86_400_000;
17
+ /** How long a ticker's lookup waits for its bonds to be kept. */
18
+ const ISSUER_KEEP_TIMEOUT_MS = 5_000;
19
+ /** Prints a history read lists, newest first. */
20
+ const STORED_PRINTS_LIMIT = 200;
21
+
22
+ export type StoredBondClient = Pick<typeof apiClient, "getCloudStoredBond" | "getCloudStoredIssuerBonds">;
23
+
24
+ /** How far back the daily closes reach: their own range, at most the 1,100 days a read takes. */
25
+ export const HISTORY_RANGES = [
26
+ { value: "1M", days: 31 },
27
+ { value: "3M", days: 92 },
28
+ { value: "1Y", days: 366 },
29
+ { value: "3Y", days: BOND_HISTORY_MAX_DAYS },
30
+ ] as const;
31
+ export type HistoryRange = (typeof HISTORY_RANGES)[number]["value"];
32
+
33
+ /** The days a read asks for: `days` up to today in New York, the tape's calendar. */
34
+ function storedHistoryWindow(now = Date.now(), days: number = BOND_HISTORY_MAX_DAYS): { from: string; to: string } {
35
+ const to = zonedDateKey(now, TAPE_TIME_ZONE);
36
+ const from = new Date(Date.parse(`${to}T00:00:00Z`) - (Math.min(days, BOND_HISTORY_MAX_DAYS) - 1) * DAY_MS)
37
+ .toISOString().slice(0, 10);
38
+ return { from, to };
39
+ }
40
+
41
+ /**
42
+ * Since when a bond's prints are held: `Kept since 2023-11-03.`, and while
43
+ * the source's earlier prints are still to be read, that they are. Null
44
+ * before any day was read.
45
+ */
46
+ export function keptSinceText(payload: Pick<StoredBondPayload, "keptSince" | "backfillPending">): string | null {
47
+ if (!payload.keptSince) return null;
48
+ return payload.backfillPending
49
+ ? `Kept since ${payload.keptSince}; earlier prints are still being read.`
50
+ : `Kept since ${payload.keptSince}.`;
51
+ }
52
+
53
+ /** Trades and corrections no cancel names: the prints a history lists. A cancel and what it cancelled say nothing about the price. */
54
+ export function standingPrints(prints: readonly StoredBondPrint[]): StoredBondPrint[] {
55
+ return prints.filter((print) => print.status !== "cancel" && !print.cancelled);
56
+ }
57
+
58
+ /** Days with a price, oldest first: what the chart draws. */
59
+ export function pricedDays(days: readonly StoredBondDay[]): StoredBondDay[] {
60
+ return days.filter((day) => day.price != null);
61
+ }
62
+
63
+ /** Three weeks without a sale breaks the line instead of drawing prices nobody paid. */
64
+ const CHART_GAP_MS = 21 * DAY_MS;
65
+
66
+ /** The daily closes as the chart's points, oldest first, with a break across a long gap between sales. */
67
+ export function bondPricePoints(days: readonly StoredBondDay[]): TimeSeriesPoint[] {
68
+ const points: TimeSeriesPoint[] = [];
69
+ let previous: number | null = null;
70
+ for (const day of pricedDays(days)) {
71
+ const time = Date.parse(`${day.date}T00:00:00Z`);
72
+ if (!Number.isFinite(time)) continue;
73
+ if (previous !== null && time - previous > CHART_GAP_MS) {
74
+ const gap = new Date(previous + DAY_MS);
75
+ points.push({ date: gap, observedAt: gap, value: null });
76
+ }
77
+ const date = new Date(time);
78
+ points.push({ date, observedAt: date, value: day.price });
79
+ previous = time;
80
+ }
81
+ return points;
82
+ }
83
+
84
+ /** Par amount as published: `250K`, `1M+` where only a floor is published. */
85
+ export function formatPrintSize(print: Pick<StoredBondPrint, "quantity" | "quantityCapped">): string {
86
+ if (print.quantity == null) return MISSING_VALUE;
87
+ return `${formatCompact(print.quantity)}${print.quantityCapped ? "+" : ""}`;
88
+ }
89
+
90
+ /** The side the reporting dealer took. */
91
+ export function formatPrintSide(side: StoredBondPrint["side"]): string {
92
+ return side === "buy" ? "Buy" : side === "sell" ? "Sell" : MISSING_VALUE;
93
+ }
94
+
95
+ /** What a kept history says to an account without Gloom Pro. */
96
+ export const PRO_HISTORY_TEXT = "Kept price history needs Gloom Pro.";
97
+
98
+ /**
99
+ * Why a kept history could not be read, in the words the pane and `fn`
100
+ * show, or null for a failure worth reporting as one: the history is Gloom
101
+ * Pro, and a bond the store cannot tie to a company has none.
102
+ */
103
+ export function storedHistoryRefusal(error: unknown): string | null {
104
+ if (!(error instanceof ApiRequestError)) return null;
105
+ if (error.status === 401 || error.status === 403) return PRO_HISTORY_TEXT;
106
+ if (error.status === 404) return "No kept price history for this bond.";
107
+ return null;
108
+ }
109
+
110
+ /** A bond's kept history for the pane, or why there is none to read; any other failure is thrown. */
111
+ export async function loadStoredBond(
112
+ cusip: string,
113
+ client: Pick<StoredBondClient, "getCloudStoredBond">,
114
+ options: { signal?: AbortSignal; now?: number } = {},
115
+ ): Promise<{ history: StoredBondPayload | null; refusal: string | null }> {
116
+ try {
117
+ const history = await client.getCloudStoredBond(cusip, { ...storedHistoryWindow(options.now), limit: STORED_PRINTS_LIMIT }, { signal: options.signal });
118
+ return { history, refusal: null };
119
+ } catch (error) {
120
+ const refusal = storedHistoryRefusal(error);
121
+ if (!refusal) throw error;
122
+ return { history: null, refusal };
123
+ }
124
+ }
125
+
126
+ /**
127
+ * What a TRACE lookup reads of the kept history: one bond's, by its CUSIP;
128
+ * for a ticker, its company's bonds are kept from now on (no history is
129
+ * shown for them until one is opened). Null for a market-wide tape or a
130
+ * name the store cannot read.
131
+ */
132
+ export async function readStoredHistory(
133
+ query: BondQuery | null,
134
+ client: StoredBondClient,
135
+ options: { signal?: AbortSignal; days?: number; now?: number } = {},
136
+ ): Promise<StoredBondPayload | null> {
137
+ if (!query) return null;
138
+ if (query.kind === "cusip") {
139
+ return client.getCloudStoredBond(query.cusip, {
140
+ ...storedHistoryWindow(options.now, options.days),
141
+ limit: STORED_PRINTS_LIMIT,
142
+ }, { signal: options.signal });
143
+ }
144
+ // Asked so its bonds are kept, never waited on for long: the tape is the answer here.
145
+ if (query.ticker) {
146
+ const ticker = query.ticker;
147
+ await Promise.resolve()
148
+ .then(() => client.getCloudStoredIssuerBonds(ticker, { signal: signalWithTimeout(options.signal, ISSUER_KEEP_TIMEOUT_MS) }))
149
+ .catch(() => {
150
+ // Intentional ignore: keeping a company's bonds never changes the tape this report answers with.
151
+ return null;
152
+ });
153
+ }
154
+ return null;
155
+ }
@@ -1,6 +1,6 @@
1
- import { useCallback, useEffect, useMemo } from "react";
1
+ import { useCallback, useEffect, useMemo, useRef } from "react";
2
2
  import {
3
- DataTableView,
3
+ DataTableStackView,
4
4
  loadingText,
5
5
  Notice,
6
6
  QueryBar,
@@ -13,6 +13,8 @@ import {
13
13
  type DataTableRootKeyContext,
14
14
  } from "../../../components";
15
15
  import { usePaneRefreshKey } from "../../../components/data-table/table-pane";
16
+ import { apiClient } from "../../../api-client";
17
+ import { usePlanAccess } from "../../../api-client/plan-access";
16
18
  import { useAsyncResource } from "../../../react/async-resource";
17
19
  import { useAutoRefresh } from "../../../react/auto-refresh";
18
20
  import { usePaneInstance } from "../../../state/app/context";
@@ -31,6 +33,8 @@ import {
31
33
  quotedCompanyName,
32
34
  type CorporateBond,
33
35
  } from "./client";
36
+ import { BondHistoryDetail } from "./detail";
37
+ import { loadStoredBond, PRO_HISTORY_TEXT } from "./history";
34
38
  import {
35
39
  DEFAULT_BOND_SORT,
36
40
  TRACE_BONDS_PANE_ID,
@@ -55,6 +59,12 @@ function dash(value: string | null): string {
55
59
  return value ?? "—";
56
60
  }
57
61
 
62
+ /** What a bond's detail is called: its issuer, coupon and maturity, as a bond is named. */
63
+ function bondTitle(bond: CorporateBond): string {
64
+ return [bond.issuerName, bond.couponRate == null ? null : formatBondDecimal(bond.couponRate, 3), bond.maturityDate]
65
+ .filter(Boolean).join(" ");
66
+ }
67
+
58
68
  export function TraceBondsPane({ focused, width, height }: PaneProps) {
59
69
  const presetIssuer = usePaneInstance()?.params?.issuer ?? "";
60
70
  const [query, setQuery] = usePluginPaneState("issuer", presetIssuer);
@@ -73,7 +83,6 @@ export function TraceBondsPane({ focused, width, height }: PaneProps) {
73
83
  const { active: searchActive, focus: focusSearch, searchProps } = useQueryBarSearch();
74
84
 
75
85
  useAutoRefresh(updatedAt, load);
76
- usePaneRefreshKey(() => void reload(), { focused, enabled: !searchActive });
77
86
 
78
87
  // One issuer's tape says its name once, in what was asked, not on every row.
79
88
  const sharedIssuer = useMemo(() => sharesOneIssuer(bonds), [bonds]);
@@ -99,6 +108,38 @@ export function TraceBondsPane({ focused, width, height }: PaneProps) {
99
108
  if (!selectedId || !rows.some((row) => row.id === selectedId)) setSelectedId(rows[0]!.id);
100
109
  }, [answered, rows, selectedId, setSelectedId]);
101
110
 
111
+ // A bond opens on its kept prints: Enter on a row, and with Gloom Pro a CUSIP looked up opens on its own once.
112
+ const [detailOpen, setDetailOpen] = usePluginPaneState("detailOpen", false);
113
+ const selectedBond = rows.find((row) => row.id === selectedId) ?? null;
114
+ const access = usePlanAccess();
115
+ const pro = access.hasProAccess;
116
+ const openedFor = useRef<string | null>(null);
117
+ const asked = answered ? data.query : null;
118
+ useEffect(() => {
119
+ if (!pro || asked?.kind !== "cusip" || rows.length !== 1 || openedFor.current === asked.cusip) return;
120
+ openedFor.current = asked.cusip;
121
+ setDetailOpen(true);
122
+ }, [asked, pro, rows.length, setDetailOpen]);
123
+ // A ticker looked up keeps its company's bonds from now on, as `fn TRACE` does; nothing waits on it.
124
+ useEffect(() => {
125
+ if (!pro || asked?.kind !== "issuer" || !asked.ticker) return;
126
+ const controller = new AbortController();
127
+ void apiClient.getCloudStoredIssuerBonds(asked.ticker, { signal: controller.signal }).catch(() => {
128
+ // Intentional ignore: keeping the company's bonds is a side effect; the tape shows without it.
129
+ });
130
+ return () => controller.abort();
131
+ }, [asked, pro]);
132
+ const detailCusip = detailOpen && selectedBond?.cusip ? selectedBond.cusip : null;
133
+ const historyRequest = useCallback(() => loadStoredBond(detailCusip!, apiClient), [detailCusip]);
134
+ const history = useAsyncResource(detailCusip && pro ? historyRequest : null);
135
+ // Without Pro, refused or failed: the detail says why in place of the prints.
136
+ const historyRefusal = !pro ? PRO_HISTORY_TEXT
137
+ : history.data?.refusal ?? (history.error && !history.data ? unavailableText("Kept price history") : null);
138
+ usePaneRefreshKey(() => {
139
+ void reload();
140
+ if (detailCusip && pro) history.load();
141
+ }, { focused, enabled: !searchActive });
142
+
102
143
  const onHeaderClick = useCallback((columnId: string) => {
103
144
  if (!isBondColumnId(columnId)) return;
104
145
  setSort((current) => nextHeaderSort(shownBondSort(current, sharedIssuer), columnId, {
@@ -154,7 +195,7 @@ export function TraceBondsPane({ focused, width, height }: PaneProps) {
154
195
  // A failure or a load for another query is the table's own message; the footer keeps the answered query's status.
155
196
  usePaneStatusFooter({
156
197
  registrationId: TRACE_BONDS_PANE_ID,
157
- loading: loading && answered,
198
+ loading: (loading && answered) || (!!detailCusip && history.loading && !history.data),
158
199
  error: answered ? error : null,
159
200
  info: footerInfo,
160
201
  });
@@ -165,8 +206,26 @@ export function TraceBondsPane({ focused, width, height }: PaneProps) {
165
206
  });
166
207
 
167
208
  return (
168
- <DataTableView
209
+ <DataTableStackView
169
210
  focused={focused && !searchActive}
211
+ detailOpen={detailOpen && !!selectedBond}
212
+ onBack={() => setDetailOpen(false)}
213
+ detailTitle={selectedBond ? bondTitle(selectedBond) : undefined}
214
+ detailContent={selectedBond ? (
215
+ <BondHistoryDetail
216
+ bond={selectedBond}
217
+ history={history.data?.history ?? null}
218
+ loading={!!detailCusip && pro && history.loading && !history.data}
219
+ refusal={historyRefusal}
220
+ focused={focused && detailOpen}
221
+ width={width}
222
+ height={Math.max(0, height - 1)}
223
+ />
224
+ ) : null}
225
+ onActivate={(row) => {
226
+ setSelectedId(row.id);
227
+ setDetailOpen(true);
228
+ }}
170
229
  rootWidth={width}
171
230
  rootHeight={height}
172
231
  rootBefore={(
@@ -45,6 +45,18 @@ function ensurePluginsDir() {
45
45
 
46
46
  const GITHUB_SEGMENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*(?![\s\S])/;
47
47
  const COMMIT_PATTERN = /^[0-9a-f]{7,40}$/i;
48
+ /**
49
+ * A tag or branch name as git spells one: never starting with a dash, which
50
+ * git would read as an option, and without `..`, `//`, `@{`, a trailing slash
51
+ * or dot, or `.lock` at the end.
52
+ */
53
+ const PIN_REF_PATTERN = /^(?!.*\.\.)(?!.*\/\/)(?!.*@\{)(?!.*\.lock$)(?!.*[./]$)[A-Za-z0-9][A-Za-z0-9._/@+-]*$/;
54
+
55
+ /** The registry pin's tag or branch, refused unless it is plainly one. */
56
+ export function validatePinRef(ref: string): string {
57
+ if (ref.length > 200 || !PIN_REF_PATTERN.test(ref)) throw new Error(`Invalid ref in registry pin: ${JSON.stringify(ref)}.`);
58
+ return ref;
59
+ }
48
60
 
49
61
  export function validatePluginDirectoryName(name: string): string {
50
62
  if (!GITHUB_SEGMENT_PATTERN.test(name)) {
@@ -203,8 +215,9 @@ function pinMatches(commit: string | null, expected: string | undefined): boolea
203
215
  async function fetchPin(targetDir: string, pin: PluginPin, quiet: boolean): Promise<string> {
204
216
  const wanted = pin.ref ?? pin.commit;
205
217
  if (!wanted) throw new Error("The registry pin names no ref or commit.");
218
+ if (pin.ref) validatePinRef(pin.ref);
206
219
  if (pin.commit && !COMMIT_PATTERN.test(pin.commit)) throw new Error(`Invalid commit in registry pin: ${pin.commit}`);
207
- await git(["fetch", "--depth", "1", "origin", wanted], targetDir, quiet, `Could not fetch ${wanted}`);
220
+ await git(["fetch", "--depth", "1", "origin", "--", wanted], targetDir, quiet, `Could not fetch ${wanted}`);
208
221
  const commit = await git(["rev-parse", "FETCH_HEAD^{commit}"], targetDir, quiet, `Could not read ${wanted}`);
209
222
  if (!pinMatches(commit, pin.commit)) {
210
223
  throw new Error(`${pin.ref ?? "The pinned ref"} now points at ${commit.slice(0, 7)}, the registry reviewed ${pin.commit!.slice(0, 7)}.`);
@@ -348,8 +361,8 @@ export async function installPlugin(ref: string, options: PluginInstallOptions =
348
361
  const pin = options.pin ?? {};
349
362
  try {
350
363
  const cloneArgs = ["clone", "--depth", "1"];
351
- if (pin.ref) cloneArgs.push("--branch", pin.ref);
352
- cloneArgs.push(url, targetDir);
364
+ if (pin.ref) cloneArgs.push(`--branch=${validatePinRef(pin.ref)}`);
365
+ cloneArgs.push("--", url, targetDir);
353
366
  await git(cloneArgs, PLUGINS_DIR, quiet, `Failed to clone ${url}`);
354
367
  if (pin.ref) {
355
368
  const commit = readPluginCommit(targetDir);