@gloom-sh/terminal 0.20.14 → 0.20.16

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 (144) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/index.ts +54 -0
  3. package/src/api-client/install-experiments.ts +8 -7
  4. package/src/api-client/paths.ts +2 -1
  5. package/src/api-client/product-waitlist.ts +63 -0
  6. package/src/api-client/request.ts +4 -2
  7. package/src/api-client/types/billing.ts +45 -0
  8. package/src/api-client/yearly-plan.ts +132 -0
  9. package/src/app/global-shortcuts.ts +5 -3
  10. package/src/app/pane-runtime/index.tsx +2 -2
  11. package/src/app/pane-runtime/plugin-bindings.ts +3 -1
  12. package/src/app/pane-runtime/ticker-open-runtime.ts +6 -1
  13. package/src/app/since-last-visit/keys.ts +26 -0
  14. package/src/app/since-last-visit/model.ts +266 -0
  15. package/src/app/since-last-visit/strip.tsx +193 -0
  16. package/src/app/since-last-visit/use-since-last-visit.ts +289 -0
  17. package/src/app/since-last-visit/visit-tracker.ts +191 -0
  18. package/src/app.tsx +15 -0
  19. package/src/cli/commands/market.ts +8 -4
  20. package/src/cli/commands/system.ts +29 -1
  21. package/src/cli/commands/ticker.ts +12 -5
  22. package/src/cli/desktop-pane-shot-api-policy.ts +4 -1
  23. package/src/cli/desktop-pane-shot-browser.ts +2 -1
  24. package/src/cli/desktop-pane-shot-view.ts +3 -7
  25. package/src/cli/desktop-pane-shot.ts +26 -28
  26. package/src/cli/help.ts +1 -0
  27. package/src/cli/history-rows.ts +24 -0
  28. package/src/cli/index.ts +4 -0
  29. package/src/cli/options.ts +29 -1
  30. package/src/cli/pane-functions/catalog.ts +41 -4
  31. package/src/cli/pane-functions/function-help.ts +1 -1
  32. package/src/cli/pane-functions/headless.ts +63 -1
  33. package/src/cli/pane-functions/index.ts +2 -2
  34. package/src/cli/pane-functions/resolver.ts +43 -0
  35. package/src/cli/pane-functions/screenshot-payload.ts +3 -0
  36. package/src/cli/report-tables.ts +20 -5
  37. package/src/cli/shot-temp-dir.ts +30 -0
  38. package/src/cli/suffixed-listing-rows.ts +11 -0
  39. package/src/components/chart/composite/composite-chart.tsx +3 -3
  40. package/src/components/command-bar/commands/direct/index.ts +31 -8
  41. package/src/components/command-bar/commands/registry.ts +7 -0
  42. package/src/components/command-bar/routes/root/command-items.ts +8 -0
  43. package/src/components/command-bar/routes/root/results.ts +16 -0
  44. package/src/components/company-logo.tsx +10 -3
  45. package/src/components/data-table/sections.ts +6 -1
  46. package/src/components/layout/pane/title.ts +6 -2
  47. package/src/components/layout/shell/index.tsx +5 -1
  48. package/src/components/layout/shell/ticker-link-menu.ts +12 -9
  49. package/src/components/ticker/badge/format.ts +12 -3
  50. package/src/components/ticker/badge/index.tsx +9 -3
  51. package/src/components/ticker/list-table-view.tsx +119 -17
  52. package/src/components/ui/data-table/display-columns.ts +16 -0
  53. package/src/components/ui/data-table/index.tsx +40 -9
  54. package/src/components/ui/data-table/types.ts +14 -0
  55. package/src/core/state/app/layout-reducer.ts +3 -1
  56. package/src/core/state/app/layout.ts +2 -2
  57. package/src/data/config/layout.ts +14 -0
  58. package/src/data/config/store/normalize.ts +11 -1
  59. package/src/i18n/es.ts +38 -0
  60. package/src/i18n/ja.ts +38 -0
  61. package/src/i18n/ko.ts +38 -0
  62. package/src/i18n/zh-cn.ts +38 -0
  63. package/src/i18n/zh-tw.ts +38 -0
  64. package/src/layout/pane-follow.ts +141 -4
  65. package/src/layout/pane-layout-move.ts +10 -7
  66. package/src/layout/ticker-navigation.ts +13 -19
  67. package/src/layout/ticker-retarget.ts +3 -2
  68. package/src/market-data/market/index-level.ts +19 -0
  69. package/src/plugins/builtin/account-management/keyboard.ts +14 -0
  70. package/src/plugins/builtin/account-management/model.ts +2 -0
  71. package/src/plugins/builtin/account-management/pane.tsx +79 -7
  72. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +97 -0
  73. package/src/plugins/builtin/account-management/yearly-plan-row.tsx +359 -0
  74. package/src/plugins/builtin/awards/pane.tsx +6 -8
  75. package/src/plugins/builtin/changelog/index.tsx +6 -44
  76. package/src/plugins/builtin/changelog/versions.ts +17 -68
  77. package/src/plugins/builtin/cloud/askg/executor.ts +2 -1
  78. package/src/plugins/builtin/cloud/askg/sources.ts +2 -1
  79. package/src/plugins/builtin/cpi/pane.tsx +1 -1
  80. package/src/plugins/builtin/debt-maturities/model.ts +1 -1
  81. package/src/plugins/builtin/earnings/board-table.ts +1 -1
  82. package/src/plugins/builtin/earnings/board.tsx +36 -16
  83. package/src/plugins/builtin/earnings/highlight.ts +47 -0
  84. package/src/plugins/builtin/earnings/history-table.ts +1 -1
  85. package/src/plugins/builtin/earnings/index.tsx +1 -1
  86. package/src/plugins/builtin/earnings-calls/pane.tsx +2 -2
  87. package/src/plugins/builtin/estimate-revisions/model.ts +1 -1
  88. package/src/plugins/builtin/exposure/index.tsx +1 -1
  89. package/src/plugins/builtin/macro-day/model.ts +6 -4
  90. package/src/plugins/builtin/market-valuation/detail.tsx +3 -3
  91. package/src/plugins/builtin/market-valuation/headless.ts +11 -4
  92. package/src/plugins/builtin/market-valuation/pane.tsx +3 -1
  93. package/src/plugins/builtin/market-valuation/view.ts +14 -0
  94. package/src/plugins/builtin/news/wire/news/detail-view.tsx +20 -8
  95. package/src/plugins/builtin/pe-band/pane.tsx +1 -1
  96. package/src/plugins/builtin/portfolio-list/cli/render.ts +8 -1
  97. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +176 -17
  98. package/src/plugins/builtin/portfolio-list/pane/groups.tsx +220 -0
  99. package/src/plugins/builtin/portfolio-list/pane/index.tsx +90 -15
  100. package/src/plugins/builtin/portfolio-list/table.tsx +13 -1
  101. package/src/plugins/builtin/research/corporate-actions-pane.tsx +4 -2
  102. package/src/plugins/builtin/research/relative-valuation-headless.ts +15 -5
  103. package/src/plugins/builtin/research/relative-valuation-model.ts +7 -1
  104. package/src/plugins/builtin/research/relative-valuation-pane.tsx +7 -4
  105. package/src/plugins/builtin/shared/headless-options.ts +1 -1
  106. package/src/plugins/builtin/social-mentions/model.ts +2 -2
  107. package/src/plugins/builtin/thirteenf/pane.tsx +1 -1
  108. package/src/plugins/builtin/ticker-detail/financials/model.ts +51 -16
  109. package/src/plugins/builtin/ticker-detail/financials/nopat.ts +16 -0
  110. package/src/plugins/builtin/ticker-detail/financials/ratios.ts +44 -13
  111. package/src/plugins/builtin/ticker-detail/financials/schema.ts +33 -2
  112. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +4 -2
  113. package/src/plugins/builtin/ticker-detail/headless-schema.ts +30 -4
  114. package/src/plugins/builtin/ticker-detail/headless.ts +254 -34
  115. package/src/plugins/builtin/ticker-detail/overview/model.ts +7 -3
  116. package/src/plugins/builtin/ticker-detail/pharma-signals/eligibility.ts +32 -0
  117. package/src/plugins/builtin/ticker-detail/pharma-signals/tab.tsx +162 -0
  118. package/src/plugins/builtin/ticker-detail/pharma-signals/waitlist.ts +126 -0
  119. package/src/plugins/builtin/ticker-detail/research-groups.ts +6 -4
  120. package/src/plugins/builtin/ticker-detail/research-tabs.ts +11 -0
  121. package/src/portfolio/column-values.ts +20 -8
  122. package/src/portfolio/suffixed-listings.ts +3 -1
  123. package/src/portfolio/watchlist-groups.ts +212 -0
  124. package/src/react/ticker-source.ts +3 -1
  125. package/src/renderers/dom/styles.css +7 -0
  126. package/src/state/app/bootstrap.ts +11 -0
  127. package/src/state/app/context/index.tsx +6 -0
  128. package/src/sync/collections-contributor.ts +5 -2
  129. package/src/sync/config-merge.ts +10 -2
  130. package/src/sync/sanitize.ts +28 -0
  131. package/src/telemetry/usage-counts.ts +17 -0
  132. package/src/time-series/chart-seed.ts +1 -1
  133. package/src/time-series/financial-period-coverage.ts +4 -12
  134. package/src/time-series/parsed-history-cache.ts +1 -1
  135. package/src/time-series/resolve.ts +1 -1
  136. package/src/time-series/use-chart-resolution.ts +6 -1
  137. package/src/types/config.ts +32 -0
  138. package/src/types/headless.ts +5 -0
  139. package/src/types/plugin-context.ts +5 -0
  140. package/src/types/ticker.ts +14 -0
  141. package/src/ui/ascii-font.ts +1 -4
  142. package/src/utils/async-deadline.ts +2 -2
  143. package/src/utils/csv.ts +44 -5
  144. package/src/utils/futures-generic.ts +3 -0
@@ -20,6 +20,7 @@ import { INDICATORS } from "./indicators";
20
20
  import { RANGE_OPTIONS, VALUATION_DEFAULTS } from "./settings";
21
21
  import { formatSigma } from "../shared/trend";
22
22
  import {
23
+ readingPeriodEnd,
23
24
  selectValuationViews,
24
25
  type IndicatorViewModel
25
26
  } from "./view";
@@ -148,7 +149,8 @@ export function MarketValuationPane({ focused, width, height }: PaneProps) {
148
149
  const footerInfo = useMemo<PaneFooterSegment[]>(() => {
149
150
  if (!selectedView) return [];
150
151
  const info: PaneFooterSegment[] = [
151
- { id: "as-of", parts: [{ text: `as of ${selectedView.asOf}`, tone: "muted" }] },
152
+ // The day the reading's period ends, as FA dates a period.
153
+ { id: "as-of", parts: [{ text: `as of ${readingPeriodEnd(selectedView.asOf, selectedView.periodicity)}`, tone: "muted" }] },
152
154
  ...(width >= 80 ? [DELAYED_SEGMENT] : []),
153
155
  ];
154
156
  if (selectedView.observationStale) {
@@ -152,3 +152,17 @@ export function selectValuationViews(
152
152
  ): IndicatorViewModel[] {
153
153
  return bundle.builds.map((build) => projectView(build, range));
154
154
  }
155
+
156
+ /** Months a period of each periodicity runs. */
157
+ const PERIOD_MONTHS = { monthly: 1, quarterly: 3, annual: 12 } as const;
158
+
159
+ /**
160
+ * A reading's as-of as FA dates a period, by the day it ends: a quarterly series dated 2026-04-01 (the start of Q2,
161
+ * as FRED dates it) is as of 2026-06-30. A reading dated by its own day stays as it is.
162
+ */
163
+ export function readingPeriodEnd(date: string, periodicity: keyof typeof PERIOD_MONTHS | null | undefined): string {
164
+ if (!periodicity || !/^\d{4}-\d{2}-\d{2}/.test(date)) return date;
165
+ const start = new Date(`${date.slice(0, 10)}T00:00:00Z`);
166
+ if (!Number.isFinite(start.getTime())) return date;
167
+ return new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + PERIOD_MONTHS[periodicity], 0)).toISOString().slice(0, 10);
168
+ }
@@ -15,7 +15,7 @@ import { truncateToDisplayWidth } from "../../../../../utils/format";
15
15
  import { wrapTextLines } from "../../../../../utils/text-wrap";
16
16
  import { formatDetailDate, formatDetailTime } from "../../../../../utils/datetime-format";
17
17
  import { logFailure } from "../../../../../utils/log-failure";
18
- import { mergeNewsArticle } from "../../../../../news/news-model";
18
+ import { mergeNewsArticle, newsArticleRevision } from "../../../../../news/news-model";
19
19
  import { usePluginPaneState } from "../../../../runtime";
20
20
  import { formatNewsCategory } from "../categories";
21
21
  import { shareItemExcerpt } from "../../../../../shares/item";
@@ -25,6 +25,11 @@ function hasStoryItems(article: MarketNewsItem | null): boolean {
25
25
  return (article?.items?.length ?? 0) > 0;
26
26
  }
27
27
 
28
+ /** A story as one answer covers it: the same id and revision ask nothing new, whatever the object. */
29
+ function storyRevisionKey(article: MarketNewsItem): string {
30
+ return `${article.id}\n${newsArticleRevision(article)}`;
31
+ }
32
+
28
33
  /**
29
34
  * The open story is pane state, not component state: it is part of what the
30
35
  * pane shows, so it survives a relaunch and travels with a shared pane. A
@@ -49,7 +54,10 @@ export function useNewsArticleDetail(
49
54
  loading: boolean;
50
55
  error: string | null;
51
56
  } | null>(null);
52
- const requestedArticle = useRef<MarketNewsItem | null>(null);
57
+ // The revisions of the open story asked for. The feed takes an answer in as a new object, and
58
+ // one with no coverage (no items, or an empty list) still has none: keyed by object, that copy
59
+ // would be asked for again, and its answer would make another, without end.
60
+ const requestedRevisions = useRef(new Set<string>());
53
61
  const standaloneRequestId = useRef<string | null>(null);
54
62
  const listedDetailArticle = useMemo(
55
63
  () => articles.find((article) => article.id === detailArticleId) ?? null,
@@ -96,15 +104,19 @@ export function useNewsArticleDetail(
96
104
  if (!baseDetailArticle || hasStoryItems(baseDetailArticle) || !loadArticleDetail) return;
97
105
  // A story fetched by id is already the detail; asking again adds nothing.
98
106
  if (baseDetailArticle === currentStandalone?.article) return;
99
- if (requestedArticle.current === baseDetailArticle) return;
100
- requestedArticle.current = baseDetailArticle;
107
+ const revision = storyRevisionKey(baseDetailArticle);
108
+ if (requestedRevisions.current.has(revision)) return;
109
+ requestedRevisions.current.add(revision);
101
110
  let active = true;
102
111
  setRequest({ base: baseDetailArticle, loading: true, error: null });
103
112
  void loadArticleDetail(baseDetailArticle.id)
104
113
  .then((article) => {
105
- if (!active) return;
106
114
  if (article && article.id !== baseDetailArticle.id) throw new Error("Story detail identity mismatch.");
107
- setRequest({ base: baseDetailArticle, article: article ? mergeNewsArticle(baseDetailArticle, article) : undefined, loading: false, error: null });
115
+ const merged = article ? mergeNewsArticle(baseDetailArticle, article) : undefined;
116
+ // The feed shows the story as merged here next: that revision is answered too.
117
+ if (merged) requestedRevisions.current.add(storyRevisionKey(merged));
118
+ if (!active) return;
119
+ setRequest({ base: baseDetailArticle, article: merged, loading: false, error: null });
108
120
  })
109
121
  .catch((error: unknown) => {
110
122
  if (!active) return;
@@ -114,12 +126,12 @@ export function useNewsArticleDetail(
114
126
  }, [baseDetailArticle, currentStandalone?.article, loadArticleDetail]);
115
127
 
116
128
  const openArticle = useCallback((article: MarketNewsItem) => {
117
- requestedArticle.current = null;
129
+ requestedRevisions.current.clear();
118
130
  standaloneRequestId.current = null;
119
131
  setDetailArticleId(article.id);
120
132
  }, [setDetailArticleId]);
121
133
  const closeDetail = useCallback(() => {
122
- requestedArticle.current = null;
134
+ requestedRevisions.current.clear();
123
135
  standaloneRequestId.current = null;
124
136
  setDetailArticleId(null);
125
137
  setRequest(null);
@@ -35,7 +35,7 @@ function tableColumns(conversion: PeBandModel["conversion"]): DataTableColumn[]
35
35
  { id: "known", label: "Known", width: 11, align: "left" },
36
36
  { id: "eps", label: conversion ? `EPS ${conversion.currency}` : "EPS", width: 9, align: "right" },
37
37
  ...(conversion ? [{ id: "fx", label: fxPairQuote(conversion.currency, conversion.latest.rate).pair, width: 9, align: "right" as const }] : []),
38
- { id: "yoy", label: "YoY", width: 8, align: "right" },
38
+ { id: "yoy", label: "YoY", width: 8, align: "right", omitWhenEmpty: true },
39
39
  { id: "price", label: "Price", width: 10, align: "right" },
40
40
  { id: "pe", label: "P/E", width: 7, align: "right" },
41
41
  ];
@@ -97,6 +97,7 @@ import { isoDateToday } from "../../../../utils/calendar-date";
97
97
  import { lastTradeDate } from "../../../../tickers/listing-fate";
98
98
  import type { PriceWindow } from "../../../../utils/price-window";
99
99
  import { showPeriodPnl } from "./period-report";
100
+ import { sectionWatchlistItems, UNGROUPED_LABEL, watchlistGroups } from "../../../../portfolio/watchlist-groups";
100
101
  import { DIVIDEND_READ_DEADLINE_MS, incomeGapNote, loadHoldingDividends, portfolioIncome, projectDrip, showsIncomeColumns, type DripYear, type HoldingDividend } from "../income";
101
102
 
102
103
  /** Money prices pad to the currency's minor unit ($337.90, not $337.9), as the ticker view does. */
@@ -1455,7 +1456,11 @@ async function showCollectionWithMarketData(
1455
1456
  if (unprojected.length > 0) console.log(cliStyles.muted(`Not projected: ${unprojected.join("; ")}.`));
1456
1457
  }
1457
1458
  } else {
1458
- const watched = await valueWatchlistRows({ tickers: filtered, quotes, dataProvider, currency, toBase });
1459
+ // A list with groups runs group by group, as PF shows it, and each row names its group.
1460
+ const sections = sectionWatchlistItems(watchlistGroups(config.watchlists.find((entry) => entry.id === id)), filtered, (ticker) => ticker.metadata.ticker);
1461
+ const groupOf = new Map(sections?.flatMap((section) => section.items.map((ticker) => [ticker.metadata.ticker, section.name] as const)));
1462
+ const valued = await valueWatchlistRows({ tickers: sections ? sections.flatMap((section) => section.items) : filtered, quotes, dataProvider, currency, toBase });
1463
+ const watched = sections ? valued.map((entry) => ({ ...entry, row: { ...entry.row, group: groupOf.get(entry.ticker.metadata.ticker) ?? null } })) : valued;
1459
1464
  if (structured) {
1460
1465
  ctx.printResult({
1461
1466
  data: watched.map((entry) => entry.row),
@@ -1477,6 +1482,7 @@ async function showCollectionWithMarketData(
1477
1482
  const changeText = quote?.delisting ? "—" : headline ? colorBySign(formatPercentRaw(headline.changePercent), headline.change) : "—";
1478
1483
  const staleText = quote?.delisting ? delistingLabel(quote.delisting) : lastTrade ? `STALE ${lastTrade}` : "STALE";
1479
1484
  return [
1485
+ ...sections ? [groupOf.get(ticker.metadata.ticker) ?? UNGROUPED_LABEL] : [],
1480
1486
  listingLabel(ticker),
1481
1487
  venue ?? "—",
1482
1488
  priceText,
@@ -1490,6 +1496,7 @@ async function showCollectionWithMarketData(
1490
1496
 
1491
1497
  console.log(renderTable(
1492
1498
  [
1499
+ ...sections ? [{ header: "Group" }] : [],
1493
1500
  { header: "Ticker" },
1494
1501
  { header: "Exchange" },
1495
1502
  { header: "Last", align: "right" },
@@ -4,7 +4,7 @@ import { withCollectionConfigData, withCollectionMarketData } from "../../../../
4
4
  import { countCollectionTickers, findWatchlist } from "../../../../cli/helpers";
5
5
  import { slugifyName } from "../../../../utils/slugify";
6
6
  import { takeOption } from "../../../../cli/commands/command-utils";
7
- import { EXCHANGE_OPTION, requireSavedListing, savedListingName } from "../../../../cli/listing-arg";
7
+ import { EXCHANGE_OPTION, loadSavedListingOf, requireSavedListing, savedListingCandidates, savedListingName } from "../../../../cli/listing-arg";
8
8
  import {
9
9
  cliStyles,
10
10
  renderSection,
@@ -13,31 +13,53 @@ import {
13
13
  } from "../../../../utils/cli-output";
14
14
  import type { AppConfig } from "../../../../types/config";
15
15
  import type { CliCommandContext, CliCommandDef } from "../../../../types/plugin";
16
- import type { Watchlist } from "../../../../types/ticker";
16
+ import type { TickerRecord, Watchlist } from "../../../../types/ticker";
17
17
  import type { ConfigContext, MarketContext } from "../../../../cli/types";
18
18
  import {
19
19
  addTickerToWatchlist,
20
20
  deleteWatchlist as deleteWatchlistConfig,
21
21
  removeTickerFromWatchlist as removeWatchlistMembership,
22
22
  } from "../../../../portfolio/mutations";
23
+ import {
24
+ parseWatchlistGroupName,
25
+ setWatchlistGroup,
26
+ watchlistGroups,
27
+ watchlistTakesGroups,
28
+ withoutWatchlistGroupSymbols,
29
+ } from "../../../../portfolio/watchlist-groups";
23
30
  import { collectionAddCommand, showCollection } from "./render";
24
31
  import { listingFields, misplacedSymbolList, refuseDryRun, takeCollectionName } from "./shared";
25
32
  import { addOneSymbol, addSymbols, FILE_OPTION, listAddLookups, printSymbolRows, progressNotice, removeSymbols, requireSymbolList, retryNotice, shellWord, SYMBOL_LIST_HELP } from "./bulk-symbols";
26
33
  import { readNameEntries } from "../../../../cli/name-entries";
27
34
  import { CLI_COMMAND_GROUPS } from "../../../../cli/help";
28
35
 
29
- const ADD_USAGE = "Usage: gloom watchlist add <watchlist> <symbols...> [--file <path>]";
36
+ const ADD_USAGE = "Usage: gloom watchlist add <watchlist> <symbols...> [--file <path>] [--group <name>]";
30
37
  const REMOVE_USAGE = "Usage: gloom watchlist remove <watchlist> <symbols...> [--file <path>]";
38
+ const MOVE_USAGE = "Usage: gloom watchlist move <watchlist> <symbols...> --group <name>";
39
+ const UNGROUP_USAGE = "Usage: gloom watchlist ungroup <watchlist> <symbols...> | --group <name>";
40
+
41
+ const GROUPS_HELP = {
42
+ title: "Groups",
43
+ lines: [
44
+ "A watchlist's tickers can sit in named groups (Energy, Tech, Index funds), which PF shows under headers that collapse, and watchlist show in a Group column; the rest show under Ungrouped. A ticker is in one group of a list at most, and a ticker on two lists can be in a different group on each.",
45
+ "add --group puts the symbols added, and those already in the list, in the group, made when new. move --group puts symbols of the list in it. ungroup takes symbols out of their group, and ungroup --group takes every symbol out of that group. A group with no symbols left goes. Names are matched in any case.",
46
+ ],
47
+ };
48
+
49
+ const GROUP_OPTION = {
50
+ flags: "--group <name>",
51
+ description: "add, move: put the symbols in this group of the watchlist, made when new; ungroup: take every symbol out of it",
52
+ };
31
53
 
32
54
  /** Actions that change a watchlist without a preview, so --dry-run would change it anyway. add previews. */
33
- const MUTATING_ACTIONS = new Set(["create", "delete", "rm", "remove"]);
55
+ const MUTATING_ACTIONS = new Set(["create", "delete", "rm", "remove", "move", "ungroup"]);
34
56
 
35
57
  /** The watchlist the leading arguments name and the symbols after it; fails naming the watchlists there are. */
36
58
  function requireWatchlistArgs(
37
59
  config: AppConfig,
38
60
  args: readonly string[],
39
61
  file: string | undefined,
40
- verb: "add" | "remove",
62
+ verb: "add" | "remove" | "move" | "ungroup",
41
63
  usage: string,
42
64
  ctx: CliCommandContext,
43
65
  ): { watchlist: Watchlist; rest: string[] } {
@@ -45,7 +67,9 @@ function requireWatchlistArgs(
45
67
  const match = takeCollectionName(args, config.watchlists);
46
68
  if (!match) {
47
69
  // A pasted list in the place of the name is a list, not a watchlist that is missing.
48
- const pasted = misplacedSymbolList(args, file, { noun: "watchlist", verb, collections: config.watchlists, usage });
70
+ const pasted = verb === "add" || verb === "remove"
71
+ ? misplacedSymbolList(args, file, { noun: "watchlist", verb, collections: config.watchlists, usage })
72
+ : null;
49
73
  if (pasted) ctx.fail(pasted.message, pasted.details);
50
74
  // The watchlist goes first: `watchlist add USDJPY=X USDCHF=X` read USDJPY=X as its name, so the form is said too.
51
75
  ctx.fail(
@@ -93,9 +117,34 @@ async function deleteWatchlist(name: string, ctx: CliCommandContext) {
93
117
  });
94
118
  }
95
119
 
120
+ /** The group `--group` names, checked before anything is looked up; a team list takes none. */
121
+ function requireGroupName(watchlist: Watchlist, group: string | undefined, usage: string, ctx: CliCommandContext): string | null {
122
+ if (group == null) return null;
123
+ if (!watchlistTakesGroups(watchlist)) ctx.fail(`"${watchlist.name}" is a team watchlist; only your own watchlists have groups.`);
124
+ if (!group.trim()) ctx.fail("--group needs a group name.", usage);
125
+ try {
126
+ return parseWatchlistGroupName(group);
127
+ } catch (error) {
128
+ return ctx.fail(error instanceof Error ? error.message : String(error), usage);
129
+ }
130
+ }
131
+
132
+ /** Puts the rows an add stored or found in the list into its group, and says so on standard error beside the add's own lines. */
133
+ async function groupAdded(ctx: CliCommandContext, config: AppConfig, watchlist: Watchlist, keys: readonly string[], group: string | null) {
134
+ if (group == null || keys.length === 0 || ctx.cliOptions.dryRun) return;
135
+ const result = setWatchlistGroup(config, watchlist.id, keys, group);
136
+ if (result.moved.length === 0) return;
137
+ await saveConfig(result.config);
138
+ if (!ctx.cliOptions.quiet) {
139
+ console.error(cliStyles.muted(`Put ${result.moved.length === 1 ? result.moved[0] : `${result.moved.length} tickers`} in group "${result.group}".`));
140
+ }
141
+ }
142
+
96
143
  async function addTickerToWatchlistCommand(
97
144
  watchlist: Watchlist, symbol: string, notes: readonly string[], exchange: string | undefined, ctx: CliCommandContext, market: MarketContext,
145
+ group: string | null,
98
146
  ) {
147
+ const added: string[] = [];
99
148
  // A bare symbol is stored on the listing `quote` reads it as, and the notes say which; a match a list would leave for a choice fails.
100
149
  await addOneSymbol(ctx, market, {
101
150
  symbol,
@@ -103,23 +152,31 @@ async function addTickerToWatchlistCommand(
103
152
  collection: { kind: "watchlist", name: watchlist.name },
104
153
  notes,
105
154
  retry: (key) => `gloom watchlist add ${shellWord(watchlist.name)} ${key}`,
106
- add: (ticker) => addTickerToWatchlist(ticker, watchlist.id),
155
+ add: (ticker) => {
156
+ const result = addTickerToWatchlist(ticker, watchlist.id);
157
+ added.push(result.ticker.metadata.ticker);
158
+ return result;
159
+ },
107
160
  member: (ticker) => ticker.metadata.watchlists.includes(watchlist.id),
108
161
  });
162
+ await groupAdded(ctx, market.config, watchlist, added, group);
109
163
  }
110
164
 
111
- async function addToWatchlistCommand(args: string[], file: string | undefined, exchange: string | undefined, ctx: CliCommandContext) {
165
+ async function addToWatchlistCommand(args: string[], file: string | undefined, exchange: string | undefined, rawGroup: string | undefined, ctx: CliCommandContext) {
112
166
  await withCollectionMarketData(ctx, async (market) => {
113
167
  const { watchlist, rest } = requireWatchlistArgs(market.config, args, file, "add", ADD_USAGE, ctx);
168
+ const group = requireGroupName(watchlist, rawGroup, ADD_USAGE, ctx);
114
169
  // Reading the names and looking the symbols up share their answers, so nothing is asked twice.
115
170
  const lookups = await listAddLookups(market.dataProvider);
116
171
  const list = await requireSymbolList(ctx, rest, file, ADD_USAGE, (entries) => readNameEntries(entries, lookups));
117
172
  if (list.single) {
118
- await addTickerToWatchlistCommand(watchlist, list.single, list.notes, exchange, ctx, market);
173
+ await addTickerToWatchlistCommand(watchlist, list.single, list.notes, exchange, ctx, market, group);
119
174
  return;
120
175
  }
121
176
  const retry = (key: string) => `gloom watchlist add ${shellWord(watchlist.name)} ${key}`;
122
177
  const dryRun = ctx.cliOptions.dryRun;
178
+ // The rows added, or found already in the list, which `--group` puts in its group.
179
+ const added: string[] = [];
123
180
  const rows = await addSymbols({
124
181
  symbols: list.symbols,
125
182
  exchange,
@@ -130,15 +187,94 @@ async function addToWatchlistCommand(args: string[], file: string | undefined, e
130
187
  retry,
131
188
  suggest: true,
132
189
  dryRun,
133
- add: (ticker) => addTickerToWatchlist(ticker, watchlist.id),
190
+ add: (ticker) => {
191
+ const result = addTickerToWatchlist(ticker, watchlist.id);
192
+ added.push(result.ticker.metadata.ticker);
193
+ return result;
194
+ },
134
195
  member: (ticker) => ticker.metadata.watchlists.includes(watchlist.id),
135
196
  });
136
197
  printSymbolRows(ctx, rows, { verb: "add", collection: { kind: "watchlist", name: watchlist.name }, repeated: list.repeated, notes: list.notes, retry, dryRun });
198
+ await groupAdded(ctx, market.config, watchlist, added, group);
199
+ });
200
+ }
201
+
202
+ /**
203
+ * The saved rows of the list the symbols name, by key, as `remove` reads a
204
+ * symbol (SAN:EPA, `--exchange`, GARAN.IS); fails naming every symbol that is
205
+ * not in the list, before anything changes.
206
+ */
207
+ async function requireListedKeys(
208
+ symbols: readonly string[], exchange: string | undefined, store: ConfigContext["store"], watchlist: Watchlist, usage: string, ctx: CliCommandContext,
209
+ ): Promise<string[]> {
210
+ const held = (ticker: TickerRecord) => ticker.metadata.watchlists.includes(watchlist.id);
211
+ const keys: string[] = [];
212
+ const missing: string[] = [];
213
+ for (const input of symbols) {
214
+ let listings;
215
+ try {
216
+ listings = savedListingCandidates(input, exchange, { ownExchangeWins: true });
217
+ } catch (error) {
218
+ return ctx.fail(error instanceof Error ? error.message : String(error), usage);
219
+ }
220
+ const saved = listings[0]!.symbol ? await loadSavedListingOf(store, listings, held) : null;
221
+ if (saved && held(saved.ticker)) keys.push(saved.ticker.metadata.ticker);
222
+ else missing.push(listings[0]!.key || input.trim());
223
+ }
224
+ if (missing.length > 0) ctx.fail(`Not in "${watchlist.name}": ${missing.join(", ")}.`, usage);
225
+ return keys;
226
+ }
227
+
228
+ /**
229
+ * `watchlist move <list> <symbols...> --group <name>` puts the symbols in the
230
+ * group; `watchlist ungroup <list> <symbols...>` takes them out of theirs, and
231
+ * `watchlist ungroup <list> --group <name>` every symbol out of that group.
232
+ */
233
+ async function groupWatchlistSymbols(
234
+ action: "move" | "ungroup", args: string[], exchange: string | undefined, rawGroup: string | undefined, ctx: CliCommandContext,
235
+ ) {
236
+ const usage = action === "move" ? MOVE_USAGE : UNGROUP_USAGE;
237
+ await withCollectionConfigData(ctx, async ({ config, store }) => {
238
+ const { watchlist, rest } = requireWatchlistArgs(config, args, undefined, action, usage, ctx);
239
+ if (action === "move" && rawGroup == null) ctx.fail("watchlist move needs --group <name>: the group to put the symbols in.", usage);
240
+ const group = requireGroupName(watchlist, rawGroup, usage, ctx);
241
+ let keys: string[];
242
+ if (rest.length === 0) {
243
+ // `ungroup --group Energy` empties the group, which then goes.
244
+ const named = action === "ungroup" && group != null
245
+ ? watchlistGroups(watchlist).find((entry) => entry.name.toLocaleLowerCase() === group.toLocaleLowerCase())
246
+ : null;
247
+ if (action === "ungroup" && group != null && !named) ctx.fail(`"${watchlist.name}" has no group "${group}".`, usage);
248
+ if (!named) ctx.fail(usage);
249
+ keys = [...named.symbols];
250
+ } else {
251
+ const list = await requireSymbolList(ctx, rest, undefined, usage);
252
+ keys = await requireListedKeys(list.symbols, exchange, store, watchlist, usage, ctx);
253
+ }
254
+ const result = setWatchlistGroup(config, watchlist.id, keys, action === "move" ? group : null);
255
+ if (result.moved.length > 0) await saveConfig(result.config);
256
+ const data = { watchlist: watchlist.name, group: result.group, symbols: keys, moved: result.moved };
257
+ const named = (symbols: readonly string[]) => symbols.join(", ");
258
+ ctx.printResult({ data }, {
259
+ text: () => result.moved.length === 0
260
+ ? cliStyles.warning(result.group == null
261
+ ? `${named(keys)} ${keys.length === 1 ? "is" : "are"} in no group of "${watchlist.name}".`
262
+ : `${named(keys)} ${keys.length === 1 ? "is" : "are"} already in group "${result.group}" of "${watchlist.name}".`)
263
+ : cliStyles.success(result.group == null
264
+ ? `Took ${named(result.moved)} out of ${result.moved.length === 1 ? "its group" : "their groups"} in "${watchlist.name}".`
265
+ : `Moved ${named(result.moved)} to group "${result.group}" of "${watchlist.name}".`),
266
+ });
137
267
  });
138
268
  }
139
269
 
270
+ /** Rows that left the list leave its groups too: added back later, they start in none. */
271
+ async function withoutGroups(config: AppConfig, watchlist: Watchlist, keys: readonly string[]) {
272
+ const next = withoutWatchlistGroupSymbols(config, watchlist.id, keys);
273
+ if (next !== config) await saveConfig(next);
274
+ }
275
+
140
276
  async function removeTickerFromWatchlist(
141
- watchlist: Watchlist, symbol: string, notes: readonly string[], exchange: string | undefined, ctx: CliCommandContext, { store }: ConfigContext,
277
+ watchlist: Watchlist, symbol: string, notes: readonly string[], exchange: string | undefined, ctx: CliCommandContext, { store, config }: ConfigContext,
142
278
  ) {
143
279
  // SAN:EPA and SAN --exchange EPA name the stored listing, which a bare SAN may hold under another venue.
144
280
  // GARAN.IS is the row of GARAN:BIST, else a row still saved under that key (a broker's).
@@ -149,6 +285,7 @@ async function removeTickerFromWatchlist(
149
285
  if (!result.changed) ctx.fail(`${saved.key} is not in "${watchlist.name}".`);
150
286
 
151
287
  await store.saveTicker(result.ticker);
288
+ await withoutGroups(config, watchlist, [ticker.metadata.ticker]);
152
289
  ctx.printResult({ data: { changed: true, ...listingFields(saved), watchlist: watchlist.name }, ...notes.length > 0 ? { warnings: [...notes] } : {} }, {
153
290
  text: () => cliStyles.success(`Removed ${saved.label} from "${watchlist.name}".`),
154
291
  });
@@ -162,13 +299,19 @@ async function removeFromWatchlistCommand(args: string[], file: string | undefin
162
299
  await removeTickerFromWatchlist(watchlist, list.single, list.notes, exchange, ctx, context);
163
300
  return;
164
301
  }
302
+ const removed: string[] = [];
165
303
  const rows = await removeSymbols({
166
304
  symbols: list.symbols,
167
305
  exchange,
168
306
  store: context.store,
169
307
  holds: (ticker) => ticker.metadata.watchlists.includes(watchlist.id),
170
- remove: (ticker) => removeWatchlistMembership(ticker, watchlist.id),
308
+ remove: (ticker) => {
309
+ const result = removeWatchlistMembership(ticker, watchlist.id);
310
+ if (result.changed) removed.push(ticker.metadata.ticker);
311
+ return result;
312
+ },
171
313
  });
314
+ await withoutGroups(context.config, watchlist, removed);
172
315
  printSymbolRows(ctx, rows, { verb: "remove", collection: { kind: "watchlist", name: watchlist.name }, repeated: list.repeated, notes: list.notes });
173
316
  });
174
317
  }
@@ -221,7 +364,7 @@ async function listWatchlists(ctx: CliCommandContext) {
221
364
  export const watchlistCliCommand: CliCommandDef = {
222
365
  name: "watchlist",
223
366
  aliases: ["watchlists"],
224
- description: "Show watchlist quotes, and add or remove symbols",
367
+ description: "Show watchlist quotes, add or remove symbols, and group them",
225
368
  help: {
226
369
  group: CLI_COMMAND_GROUPS.portfolios,
227
370
  usage: [
@@ -229,10 +372,13 @@ export const watchlistCliCommand: CliCommandDef = {
229
372
  "watchlist show <name>",
230
373
  "watchlist create <name>",
231
374
  "watchlist delete <name>",
232
- "watchlist add <watchlist> <symbols...> [--file <path>]",
375
+ "watchlist add <watchlist> <symbols...> [--file <path>] [--group <name>]",
233
376
  "watchlist remove <watchlist> <symbols...> [--file <path>]",
377
+ "watchlist move <watchlist> <symbols...> --group <name>",
378
+ "watchlist ungroup <watchlist> <symbols...>",
379
+ "watchlist ungroup <watchlist> --group <name>",
234
380
  ],
235
- options: [EXCHANGE_OPTION, FILE_OPTION],
381
+ options: [EXCHANGE_OPTION, FILE_OPTION, GROUP_OPTION],
236
382
  examples: [
237
383
  "watchlist show Growth",
238
384
  "watchlist create Growth",
@@ -243,15 +389,23 @@ export const watchlistCliCommand: CliCommandDef = {
243
389
  "watchlist add Growth --file holdings.csv",
244
390
  "watchlist add Growth --file holdings.csv --dry-run",
245
391
  "watchlist show Growth --csv",
392
+ "watchlist add Funds VTSAX FXAIX --group \"Index funds\"",
393
+ "watchlist move Growth XOM CVX --group Energy",
394
+ "watchlist ungroup Growth XOM",
246
395
  ],
247
- sections: [SYMBOL_LIST_HELP],
396
+ sections: [SYMBOL_LIST_HELP, GROUPS_HELP],
248
397
  },
249
398
  execute: async (rawArgs, ctx) => {
250
399
  const args = [...rawArgs];
251
400
  const exchange = takeOption(args, "--exchange");
252
401
  const hasFile = args.some((arg) => arg === "--file" || arg.startsWith("--file="));
253
402
  const file = hasFile ? takeOption(args, "--file") ?? "" : undefined;
403
+ const hasGroup = args.some((arg) => arg === "--group" || arg.startsWith("--group="));
404
+ const group = hasGroup ? takeOption(args, "--group") ?? "" : undefined;
254
405
  const action = args[0];
406
+ if (group != null && action !== "add" && action !== "move" && action !== "ungroup") {
407
+ ctx.fail(`--group is an option of watchlist add, move and ungroup, not watchlist ${action ?? "list"}.`, MOVE_USAGE);
408
+ }
255
409
  if (file != null && action !== "add" && action !== "remove") ctx.fail(`--file is an option of watchlist add and remove, not watchlist ${action ?? "list"}.`, ADD_USAGE);
256
410
  if (MUTATING_ACTIONS.has(action ?? "")) refuseDryRun(ctx, "watchlist", action!);
257
411
 
@@ -282,7 +436,12 @@ export const watchlistCliCommand: CliCommandDef = {
282
436
  }
283
437
 
284
438
  if (action === "add") {
285
- await addToWatchlistCommand(args.slice(1), file, exchange, ctx);
439
+ await addToWatchlistCommand(args.slice(1), file, exchange, group, ctx);
440
+ return;
441
+ }
442
+
443
+ if (action === "move" || action === "ungroup") {
444
+ await groupWatchlistSymbols(action, args.slice(1), exchange, group, ctx);
286
445
  return;
287
446
  }
288
447